#!/bin/python3
import requests, re, argparse, os, sys, random;
from time import sleep;
from decimal import Decimal as D;
DB=("\033[01;38;5;21m")
RD=("\033[01;38;5;9m")
YLW=("\033[01;38;5;220m")
PNK=("\033[01;38;5;135m")
PRP=("\033[01;38;5;55m")
GRN=("\033[01;38;5;10m")
BLUE=("\033[01;38;5;21m")
DRK=("\033[01;38;5;242m")
WHT=("\033[01;38;5;15m")
ORN=("\033[01;38;5;202m")
GRY=("\033[01;38;5;242m")
RESET=("\033[0m")
LOAD=("\033[1;49;32m")
version=(1.1)
if (os.path.isdir('/data/data/com.termux')):
    OS = ('Termux')
elif ('linux') in (sys.platform):
    OS = ('Linux')
elif ('win') in (sys.platform):
    OS = ('Windows')
script = (os.path.basename(sys.argv[0]))
if ('.py') in script:
    script = (script.split('.')[0])
counter = [0]
CHARS = ('/', '-', '\\', '|')
Agent = ('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36')
def cls():
    os.system('clear')
def loading(duration):
    for i in range(10):
        counter[0] += 1
        sys.stdout.write('\r')
        sys.stdout.write(f"{LOAD}%s{RESET}" % CHARS[counter[0] % len(CHARS)])
        sys.stdout.flush()
        sleep(duration)
    sys.stdout.write("\b ")
    return()
def echo(data):
    blank = ' '
    s = ''
    for l in blank:
        sys.stdout.write('\r')
        if 'Error' in data:
            sys.stdout.write(f"{DRK}[{RD}■{DRK}] {GRN}{data}")
        else:
            sys.stdout.write(f"{DRK}[{GRN}■{DRK}] {GRN}{data}")
        s += (f"{l}")
        sys.stdout.flush()
        sleep(0.3)
        sys.stdout.write("\n")
        return()
def icon(): #₿Ξ
    if (OS) == ('Termux'):
        icon = (f"""{GRN}┏━┓{DRK}┳┏
{GRN}┃{YLW}₿ {DRK}┣┻┓
{GRN}┗━┛{DRK}┇ ┛
{GRN}Crypto Toolkit """)
    else:
        icon = (f"""{GRN}┏━┓{DRK}┳━┓{DRK}┓ ┳{DRK}┳━┓{DRK}┏┓┓{DRK}┳┏ {PNK}o{DRK}┏┓┓
{GRN}┃  {DRK}┃┳┛{DRK}┗┏┛{DRK}┃━┛ {DRK}┃ {DRK}┣┻┓{DRK}┃ {DRK}┃
{GRN}┗━┛{RD}┇{DRK}┗┛ {RD}┇ {RD}┇ {YLW}₿ {RD}┇ {RD}┇{DRK} ┛{RD}┇ {RD}┇ """)
    sys.stdout.write(f"{icon}\n")
def usage():
    info = (f"""
{PNK}# {DRK}Convert Function {PNK}#
{PNK}# {DRK}Convert {PNK}$1500 {GRN}USD {DRK}into {GRN}Ξthereum
{GRN}{script} {RD}-c {GRN}usd {RD}-i {GRN} eth {RD}-n {GRN}1500
{PNK}# {DRK}Convert {PNK}3 {GRN}Ξthereum {DRK}into {GRN}₿TC
{GRN}{script} {RD}-c {GRN}eth {RD}-i {GRN}btc {RD}-n {GRN}3
{PNK}# {DRK}Convert {PNK}40 {GRN}Ðogecoin {DRK}into {GRN}GBP
{GRN}{script} {RD}-c {GRN}doge {RD}-i {GRN}gbp {RD}-n {GRN}40
{PNK}# {DRK}Convert {PNK}30 {GRN}Polygon{WHT}({PNK}MATIC{WHT}) {DRK}into {GRN}U$D
{GRN}{script} {RD}-c {GRN}matic {RD}-i {GRN}usd {RD}-n {GRN}30
{PNK}# {DRK}Convert {PNK}500 {GRN}Gwei {DRK}into {GRN}U$D
{GRN}{script} {RD}-c {GRN}gwei {RD}-i {GRN}usd {RD}-n {GRN}30
****************************
{PNK}# {DRK}Price Function {PNK}#
{PNK}# {DRK}Check price of just Ξthereum {PNK}& {DRK}₿itcoin
{GRN}{script} {RD}-p {PNK}[{WHT}blank{PNK}]
{PNK}# {DRK}Check price of Solana
{GRN}{script} {RD}-p {GRN}solana
 """)
    info = info.replace('\r','.')
    sys.stdout.write(f"{info}\b")
def msg(name=None) -> None:
    info = (f"""{PNK}#{DRK} {script} optional arguments{PNK}:{GRN}
{GRN}-c{WHT}, {GRN}--convert      {PNK}# {DRK}Currency to convert {PNK}[{GRN}USD{WHT}, {GRN}GBP{WHT}, {GRN}EUR{WHT}, {GRN}BTC{WHT}, {GRN}DOGE{WHT}, etc{PNK}]
{GRN}-i{WHT}, {GRN}--into         {PNK}# {DRK}Currency to convert into {PNK}[{GRN}BTC{WHT}, {GRN}MATIC{WHT}, {GRN}USD{WHT}, {GRN}GPB{WHT}, {GRN}etc{PNK}]
{GRN}-n{WHT}, {GRN}--amount       {PNK}# {DRK}Amount to convert {PNK}[{RD}0.00000001 {PNK}- {RD}1000000{PNK}]
{GRN}-u{WHT}, {GRN}--usage        {PNK}# {DRK}Show advanced help: {PNK}[{GRN}convert{WHT}, {GRN}today{WHT}, {GRN}price{WHT}, {GRN}all{PNK}]
{GRN}-p{WHT}, {GRN}--price        {PNK}# {DRK}Get crypto prices {PNK}[{GRN}all{WHT},{PNK}{{{GRN}specified coin{PNK}}}{WHT},{GRN}blank{PNK}]
{GRN}-l{WHT}, {GRN}--list         {PNK}# {DRK}List some common crypto currencies
{GRN}-e{WHT}, {GRN}--exchanges    {PNK}# {DRK}List exchanges
{GRN}-t{WHT}, {GRN}--today        {PNK}# {DRK}Get today's info on a coin
{GRN}-h{WHT}, {GRN}--help         {PNK}# {DRK}Show standard help menu """)
    info = info.replace('\r','.')
    sys.stdout.write(f"{info}\b")
def specific(query) -> None:
    if (query) == ('convert'):
        info = (f"""{PNK}#{DRK} Conversion examples{PNK}:{WHT}({RD}Use abreviations{WHT})
{GRN}{script} -c usd -i btc -n 125 {PNK}# {DRK}Convert $125 into ₿itcoin
{GRN}{script} --convert sol --into usd --amount 9.5 {PNK}# {DRK}Convert 9.5 Solana into USD.
{GRN}{script} -c matic -i eth -n 2000 {PNK}# {DRK}Convert 2000 MATIC into Ξthereum
{PNK}# {RD}*{DRK}Hint{PNK}: {DRK}run {WHT}({GRN}{script} {RD}--list{WHT}) {DRK}to get abreviations{RD}* """)
        info = info.replace('\r','.')
        sys.stdout.write(f"\n{info}\b")
    elif (query) == ('price'):
        info = (f"""{PNK}# {DRK}Price examples{PNK}:{WHT}({RD}Use full name{WHT}){GRN}
{script} -p litecoin {PNK}# {DRK}Get the price of Litecoin{GRN}
{script} -p 'ethereum classic' {PNK}# {DRK}Use quotes for two-word cryptos{GRN}
{script} -p [blank] {PNK}#{DRK} Leave blank for Ξthereum and ₿itcoin{GRN}
{script} -p all {PNK}#{DRK} Retrieve prices on 200+ crypto currencies""")
        info = info.replace('\r','.')
        sys.stdout.write(f"\n{info}\b")
    elif (query) == ('today'):
        info = (f"""{PNK}#{DRK} Price examples{PNK}:{WHT}({RD}Use full name{WHT}){GRN}
{script} -t litecoin {PNK}# {DRK}Get today's info on Litecoin{GRN}
{script} --today 'ethereum classic' {PNK}# {DRK}Use quotes for two-word cryptos{GRN}
{script} -p [blank] {PNK}#{DRK} Leave blank for ₿itcoin and Ξthereum {GRN}""")
        info = info.replace('\r','.')
        sys.stdout.write(f"\n{info}\b")
    elif (query) == ('help'):
        sys.stdout.write(f"{RD}You need help, we know.\n")
        msg()
    else:
        usage()
class get():
    def __init__(self) -> None:
        self.session = requests.Session()
        self.session.headers.update({'User-Agent':f"{Agent}"})
        parser = argparse.ArgumentParser(description=(f'{GRN}{script} | Crypto Toolkit'),add_help=(False))
        parser.add_argument('-h', '--help',action='help', default=argparse.SUPPRESS,help=(f'Show this help menu'))
        parser.add_argument('-t', '--today' ,nargs='?',const='bitcoin',required=False, action=('store'), help=(f"Get today's details on a coin"))
        parser.add_argument('-u', '--usage' ,nargs='?',const='general',required=False, action=('store'), help=(f"Advanced Usage"))
        parser.add_argument('-v', '--version' ,required=False, action=('store_true'), help=(f"{script} Version"))
        parser.add_argument('-l', '--list' ,required=False, action=('store_true'), help=(f"List some common crypto currencies"))
        parser.add_argument('-e', '--exchanges' ,required=False, action=('store_true'), help=(f"List ~100 decentralized exchanges"))
        parser.add_argument('-c', '--convert' ,required=False, action=('store'),type=(str.lower), help=(f"Currency to convert"))
        parser.add_argument('-i', '--into' ,required=False, action=('store'),type=(str.lower), help=(f"Currency to convert into"))
        parser.add_argument('-n', '--amount' ,required=False, action=('store'),type=(float), help=(f"Amount to convert"))
        parser.add_argument('-p', '--price' ,nargs='?',const='bitcoin' ,required=False, action=('store'), help=(f"Retrieve crypto prices"))
        args = (parser.parse_args())
        if args.today:
            icon()
            loading(0.05)
            coin = (args.today)
            self.today(coin)
            exit(0);
        if args.exchanges:
            loading(0.05)
            self.exchange()
            exit(0);
        else:
            pass
        if args.list:
            icon()
            loading(0.05)
            data = (f"{DRK}Some common crypto currencies {DRK}[{GRN}■{DRK}]")
            echo(data)
            self.list_cryptos()
            exit(0);
        else:
            pass
        if args.price:
            icon()
            loading(0.05)
            currency = (args.price)
            self.get_current_price(currency)
        else:
            pass
        if args.version:
            icon()
            data = (f"{DRK}Version: {GRN}{script} {PNK}{version} {DRK}[{GRN}■{DRK}]")
            echo(data)
            exit(0);
        try:
            if args.convert:
                to_convert = (args.convert)
                if (args.amount) == (0):
                    data = (f"{RD}Error{PNK}: {DRK}Cannot convert {RD}{args.amount} {DRK}[{RD}■{DRK}]")
                    echo(data)
                    exit(0);
                elif (args.amount) > (0):
                    amount = (args.amount)
                else:
                    data = (f"{RD}Error{PNK}: {DRK}You must supply an amount to convert {DRK}[{RD}■{DRK}]")
                    echo(data)
                    exit(0);
                if len(args.convert) < (3):
                    data = (f"{RD}Error {PNK}'{RD}{args.convert}{PNK}' {DRK}is not a currency abbreviation{PNK} {DRK}[{RD}■{DRK}]")
                    echo(data)
                    data = (f"{DRK}Examples{PNK}: {GRN}BTC{PNK}, {GRN}MATIC{PNK}, {GRN}USD{PNK}, {GRN}DOGE{PNK}, {GRN}SHIB {DRK}[{GRN}■{DRK}]")
                    echo(data)
                    data = (f"{PRP}*{GRN}Hint{PRP}*{PNK}::{WHT}({PNK}Doesn't need to be capitalized{WHT}) {DRK}[{GRN}■{DRK}]")
                    echo(data)
                    exit(0);
                if len(args.into) < (3):
                    data = (f"{RD}Error {PNK}'{RD}{args.into}{PNK}' {DRK}is not a currency abbreviation{PNK} {DRK}[{RD}■{DRK}]")
                    echo(data)
                    data = (f"{DRK}Examples{PNK}: {GRN}BTC{PNK}, {GRN}MATIC{PNK}, {GRN}USD{PNK}, {GRN}DOGE{PNK}, {GRN}SHIB {DRK}[{GRN}■{DRK}]")
                    echo(data)
                    data = (f"{PRP}*{GRN}Hint{PRP}*{PNK}::{WHT}({PNK}Doesn't need to be capitalized{WHT}) {DRK}[{GRN}■{DRK}]")
                    echo(data)
                    exit(0);
                else:
                    convert_to = (args.into)
                icon()
                loading(0.05)
                self.convert(to_convert,amount,convert_to)
                exit(0);
        except:
            pass
        if args.usage:
            if (args.usage) != ('general'):
                query = (args.usage)
                icon()
                loading(0.05)
                specific(query)
            else:
                msg()
        else:
            pass
    def list_cryptos(self):
        page = ('https://raw.githubusercontent.com/Waxxx333/cryptkit/main/coins.txt')
        coin_list = (self.session.get(page).text)
        coins = (re.findall('([0-9A-Za-z ]+)',coin_list))
        coins = [x.strip() for x in coins]
        title = ["Name", "Abreviation"]
        data = ('{:1s}{:8s} {:14s}{:24s}'.format(DRK,title[0],RD,title[1]))
        echo(data)
        for coin in coins:
            try:
                data = ("{:10s} {:20s}".format(coin.split()[0],coin.split()[1].lower()))
                echo(data)
                sleep(0.01);
            except KeyboardInterrupt:
                data = (f"{RD}Error{PNK}: {DRK}Keyboard Interruption {DRK}[{RD}■{DRK}]")
                echo(data)
                exit(0);
    def today(self,coin):
        if len(coin.split()) > 1:
            coin_raw = (coin.replace(' ','-'))
        else:
            coin_raw = (coin)
        try:
            price_page = (f"https://coinmarketcap.com/currencies/{coin_raw.lower()}/")
            retrieve2 = (self.session.get(price_page).text)
            price_data =  (re.findall('Price Live Data(.*?)
',retrieve2)[0])
            try:
                real_name =  (re.findall('<title>(.*?)price',retrieve2)[0])
                title = ["Real Name", "Price"]
            except:
                real_name = (coin.title())
                title = ["Query", "Price"]
            try:
                data2 =  (re.findall('">What Is(.*?)
',retrieve2)[0])
                info = (f"What is {data2}")
            except:
                info = (f"")
            try:
                price =  (re.findall('class="priceValue ">(.*?)',retrieve2)[0])
            except (IndexError):
                price =  (re.findall('class="priceValue smallerPrice">(.*?)',retrieve2)[0])
            CLEANR = re.compile('<.*?>')
            cleantext = re.sub(CLEANR, '', price_data)
            cleantext2 = re.sub(CLEANR, '', info)
            data = ('{:10s}{:12s} {:17s}{:20s}'.format(DRK,title[0],RD,title[1]))
            echo(data)
            data = ('{:10s}{:12s} {:17s}{:20s}'.format(DRK,real_name,RD,price))
            echo(data)
            sys.stdout.write(f"{GRN}{cleantext}")
            sys.stdout.write(f"\n{GRN}{cleantext2}")
        except (IndexError):
            data = (f"{RD}Error{PNK}: {DRK}Incorrect spelling, wrong name or unsupported coin {DRK}[{RD}■{DRK}]")
            echo(data)
            exit(0);
        except (KeyboardInterrupt):
            data = (f"{RD}Error{PNK}: {DRK}Keyboard Interruption {DRK}[{RD}■{DRK}]")
            echo(data)
            exit(0);
    def exchange(self):
        page = ('https://coinmarketcap.com/rankings/exchanges/dex/')
        retrieve = (self.session.get(page).text)
        exchanges = (list(set(re.findall('href="/exchanges/(.*?)/"',retrieve))))
        count = 0
        title = ["Name", "URL"]
        data = ('{:10s}{:12s} {:17s}{:20s}'.format(DRK,title[0],RD,title[1]))
        echo(data)
        if ('loopring-exchange') in exchanges: exchanges.pop(exchanges.index('loopring-exchange'))
        if ('mento') in exchanges: exchanges.pop(exchanges.index('mento'))
        for exchange in exchanges:
            try:
                page = (f"https://coinmarketcap.com/exchanges/{exchange}")
                get_links = (self.session.get(page).text)
                links = (list(set(re.findall('target="_blank">http(.*?)</',get_links))))
                for link in links:
                    if ('https://medium.com') in link:
                        link = ('Null')
                    data = ('{}{:13s} {}http{:23s}'.format(DRK,exchange,RD,link))
                    echo(data)
            except KeyboardInterrupt:
                data = (f"{RD}Error{PNK}: {DRK}Keyboard Interruption {DRK}[{RD}■{DRK}]")
                echo(data)
                exit(0);
    def all_crypto_prices(self):
        page = ('https://coinmarketcap.com/all/views/all/')
        retrieve = (self.session.get(page).text)
        names = (list(set(re.findall('"name":"(.*?)"',retrieve))))
        count = 0
        title = ["Name", "Price", "Alt"]
        data = ('{:10s}{:12s} {:6s}{:8s} {:17s}{:20s}'.format(DRK,title[0],GRN,title[1],RD,title[2]))
        echo(data)
        try:
            for name in names:
                try:
                    price_page = (f"https://coinmarketcap.com/currencies/{name.lower()}/")
                    retrieve2 = (self.session.get(price_page).text)
                    price =  (re.findall('class="priceValue ">(.*?)',retrieve2)[0])
                    alt =  (re.findall('height="32" width="32" alt="(.*?)"',retrieve2)[0])
                    data = ('{:10s}{:12s} {:6s}{:8s} {:17s}{:20s}'.format(DRK,name,GRN,price,RD,alt))
                    echo(data)
                except KeyboardInterrupt:
                    data = (f"{RD}Error{PNK}: {DRK}Keyboard Interruption {DRK}[{RD}■{DRK}]")
                    echo(data)
                    exit(0);
                except:
                    pass
                count += 1
        except KeyboardInterrupt:
            data = (f"{RD}Error{PNK}: {DRK}Keyboard Interruption {DRK}[{RD}■{DRK}]")
            echo(data)
            exit(0);
    def convert(self,to_convert,amount,convert_to):
        data = (f"{DRK}Conversion is from{PNK}: {PRP}cryps.info")
        echo(data)
        if ('gwei') in to_convert.casefold():
            currency1 = ('Gwei')
        else:
            currency1 = (to_convert.upper())
        if ('gwei') in convert_to.casefold():
            currency2 = ('Gwei')
        else:
            currency2 = (convert_to.upper())
        page = (f"https://www.cryps.info/en/{currency1}_to_{currency2}/{amount}/")
        retrieve = (self.session.get(page).text)
        result = (re.findall('

(.*?)
',retrieve))
        title = (re.findall('<title>(.*?)</title>',retrieve))
        retrieved_amount = (re.split('\s+', result[0])[0])
        retrieved_currency = (re.split('\s+', result[0])[1])
        if retrieved_currency == ('BTC'):
            retrieved_currency = ('₿TC')
        elif retrieved_currency == ('ETH'):
            retrieved_currency = ('ΞTH')
        elif retrieved_currency == ('DOGE'):
            retrieved_currency = ('ÐOGE')
        elif retrieved_currency == ('USD'):
            retrieved_currency = ('U$D')

        if currency1 == ('BTC'):
            currency1 = ('₿TC')
        elif currency1 == ('ETH'):
            currency1 = ('ΞTH')
        elif currency1 == ('DOGE'):
            currency1 = ('ÐOGE')
        elif currency1 == ('USD'):
            currency1 = ('U$D')

        if currency2 == ('BTC'):
            currency2 = ('₿TC')
        elif currency2 == ('ETH'):
            currency2 = ('ΞTH')
        elif currency2 == ('DOGE'):
            currency2 = ('ÐOGE')
        elif currency2 == ('USD'):
            currency2 = ('U$D')
        csymbol = ('')
        if len(str((amount))) >= 5:
            amount = format(amount, '.{}f'.format(len(str(amount))))
        try:
            title = (title[0])
            new_title = (title.split('|')[0])
            data = (f"{GRN}{new_title} {DRK}[{GRN}■{DRK}]")
            echo(data)
            data = (f"{GRN}{amount} {PNK}{currency1} {WHT}= {GRN}{retrieved_amount} {PNK}{retrieved_currency} {DRK}[{GRN}■{DRK}]")
            echo(data)
        except:
            data = (f"{GRY}Converting{PNK}: {GRN}{currency1} {GRY}into{PNK}: {GRN}{currency2} {PRP}|| {GRN}{amount} {PNK}{currency1} {WHT}= {GRN}{retrieved_amount} {PNK}{retrieved_currency} {DRK}[{GRN}■{DRK}]")
            echo(data)
    def get_current_price(self, currency):
        data = (f"{DRK}Price data is from of{PNK}: {BLUE}coinmarketcap.com")
        echo(data)
        btc_page = ('https://coinmarketcap.com/currencies/bitcoin/')
        eth_page = ('https://coinmarketcap.com/currencies/ethereum/')
        page2 = ("https://walletinvestor.com/converter/ethereum/usd/1")
        get_btc = (self.session.get(btc_page).text)
        get_eth = (self.session.get(eth_page).text)
        retrieve2 = (self.session.get(page2).text)
        try:
            btc_price = (re.findall('class="priceValue ">(.*?)',get_btc)[0])
        except:
            btc_price = (f'N/A')
        try:
            eth_price = (re.findall('class="priceValue ">(.*?)',get_eth)[0])
        except (IndexError):
            eth_price = (re.findall('class="priceValue smallerPrice">(.*?)',get_eth)[0])
        except:
            eth_price = ('N/A')
        try:
            btc_status = (re.findall('Bitcoin is down(.*?)%',get_btc)[0])
            btc_status = (btc_status.replace(' ',''))
            UP = (False)
        except (IndexError):
            btc_status = (re.findall('Bitcoin is up(.*?)%',get_btc)[0])
            btc_status = (btc_status.replace(' ',''))
            UP = (True)
        except:
            UP = ('')
            btc_status = ('')
        try:
            down = (re.findall('glyphicon-menu-down"> (.*?)</',retrieve2)[0])
            down_clean = (down.replace(" ", ""))
        except:
            down = (re.findall('glyphicon-menu-up"> (.*?)</',retrieve2)[0])
            down_clean = (down.replace(" ", ""))
        if currency != ('bitcoin'):
            if currency == ('all'):
                data = (f"{DRK}Stats brought to you by{PNK}: {BLUE}https{DRK}://{BLUE}coinmarketcap.com {DRK}[{GRN}■{DRK}]")
                echo(data)
                self.all_crypto_prices()
                exit(0);
            if len(currency.split()) > 1:
               currency = (currency.replace(' ', '-'))
            try:
                cpage = (f"https://coinmarketcap.com/currencies/{currency.lower()}/")
                retrievec = (self.session.get(cpage).text)
                try:
                    alt =  (re.findall('height="32" width="32" alt="(.*?)"',retrievec)[0])
                except (IndexError):
                    alt = ('')
                try:
                    real_name = (re.findall('<title>(.*?)price',retrievec)[0])
                    real_name = (real_name.rstrip())
                except (IndexError):
                    real_name = (currency.title())
                try:
                    ccurrency = (re.findall('class="priceValue ">(.*?)',retrievec)[0])
                except (IndexError):
                    ccurrency =  (re.findall('class="priceValue smallerPrice">(.*?)',retrievec)[0])
                except:
                    ccurency = ('')
                try:
                    coin_status = (re.findall(f"{real_name} is up(.*?)%",retrievec)[0])
                    coin_status_up = (True)
                except (IndexError):
                    coin_status = (re.findall(f"{real_name} is down(.*?)%",retrievec)[0])
                    coin_status_up = (False)
                except:
                    pass
                if (coin_status_up) == (True):
                    coin_status = (coin_status.replace(' ',''))
                    data = (f"{DRK}{real_name}{WHT}({GRN}{alt}{WHT}) {DRK}Price{PNK}: {GRN}{ccurrency} {PNK}.::. {DRK}Up{PNK}: {GRN}+{coin_status}%\r")
                    echo(data)
                elif (coin_status_up) == (False):
                    coin_status = (coin_status.replace(' ',''))
                    data = (f"{DRK}{real_name}{WHT}({GRN}{alt}{WHT}) {DRK}Price{PNK}: {GRN}{ccurrency} {PNK}.::. {DRK}Down{PNK}: {RD}-{coin_status}%\r")
                    echo(data)
                else:
                    data = (f"{DRK}{real_name}{WHT}({GRN}{alt}{WHT}) {DRK}Price{PNK}: {GRN}{ccurrency}")
                    echo(data)
            except:
                data = (f"{RD}Error{PNK}: {DRK}Check your spelling and try again.{DRK}[{RD}■{DRK}]")
                echo(data)
                data = (f"{PNK}*{GRN}Hint{PNK}*{PNK}::{WHT}({DRK}Complete spelling{PNK}: {GRN}litecoin{PNK}, '{GRN}Ethereum Classic{PNK}'{WHT}) {DRK}[{GRN}■{DRK}]")
                echo(data)
                data = (f"{RD}If the name is two words, use quotes {DRK}[{GRN}■{DRK}]")
                echo(data)
        if ('-') in down:
            if (UP) == (True):
                data = (f"{DRK}₿TC Price{PNK}: {GRN}${GRN}{btc_price} {PNK}.::. {DRK}Up{PNK}: {GRN}+{btc_status}%\r")
            elif (UP) == (False):
                data = (f"{DRK}₿TC Price{PNK}: {GRN}${GRN}{btc_price} {PNK}.::. {DRK}Down{PNK}: {RD}-{btc_status}%\r")
            else:
                data = (f"{DRK}₿TC Price{PNK}: {GRN}${GRN}{btc_price}")
            echo(data)
            loading(0.01)
            data = (f"{DRK}ΞTH Price{PNK}: {GRN}{eth_price} {PNK}.::. {DRK}Down{PNK}: {RD}{down_clean}%\r")
            echo(data)
        else:
            if (UP) == (True):
                btc_status = (btc_status.replace(' ',''))
                data = (f"{DRK}₿TC Price{PNK}: {GRN}${GRN}{btc_price} {PNK}.::. {DRK}Up{PNK}: {GRN}+{btc_status}%\r")
            elif (UP) == (False):
                btc_status = (btc_status.replace(' ',''))
                data = (f"{DRK}₿TC Price{PNK}: {GRN}${GRN}{btc_price} {PNK}.::. {DRK}Down{PNK}: {RD}-{btc_status}%\r")
            else:
                data = (f"{DRK}₿TC Price{PNK}: {GRN}${GRN}{btc_price}")
            echo(data)
            loading(0.01)
            data = (f"{DRK}ΞTH Price{PNK}: {GRN}{eth_price} {PNK}.::. {DRK}Up{PNK}: {GRN}+{down_clean}%\r")
            echo(data)

get()


"""
Sauvola.py

Project: Palmetto

Description: Implementation of the Sauvola thresholding method. This class forms a wrapper to an external
Sauvola program. This class uses subprocess to access the functionality.

Reference:
Christian Wolf , Jean-Michel Jolion and Francoise Chassaing. Text Localization,
Enhancement and Binarization in Multimedia Documents Proceedings of the International Conference
on Pattern Recognition (ICPR), volume 4, pages 1037-1040,
IEEE Computer Society. August 11th-15th, 2002, Quebec City, Canada. 4 pages.

Created on 11 Oct 2014

@author:  Jason Forte
@contact: <dev@dustio.com>
"""
import cv2
import numpy
import os
import subprocess

import structure.Base

from structure.Operation import Operation

class Sauvola(Operation):
    '''
    Description:
    Performs the sauvola threshold enhancement algorithm. This operation is
    actually a wrapper class for the Sauvola program

    With Reference to:

    @InProceedings{WolfICPR2002V,
      Author         = {C. Wolf and J.-M. Jolion and F. Chassaing},
      Title          = {Text {L}ocalization, {E}nhancement and {B}inarization in {M}ultimedia {D}ocuments},
      BookTitle      = {Proceedings of the {I}nternational {C}onference on {P}attern {R}ecognition},
      Volume         = {2},
      Pages          = {1037-1040},
      year           = 2002,
    }

    Requires: cv2, os, numpy, subprocess structure.Operation

    '''
    # Decribe the Operation
    NAME = 'Sauvola Operation'

    def __init__(self, input_image=numpy.ndarray, options=dict):
        '''
        Sauvola(input_image, options) -> ndarray

        options:
        widow  (x,y) -    window of the kernel
        k            -    multiplaction factor for the Sauvola method
        '''
        Operation.__init__(self, input_image=input_image, options=options)

        self.operation_name = 'Sauvola Method'

        # Check existence of values
        if not self.options.has_key('window'):
            options['window'] = (15, 15)
        if not self.options.has_key('k'):
            options['k'] = 0.03

        # save the image to a know location
        self.dirname = structure.Base.sample_dir

        cv2.imwrite(self.dirname + 'source.png', input_image)

        self.k = options['k']

    def execute(self):
        '''
        The Sauvola Method for Enhancement hs not been implemented in
        opencv. A module was found that performs the operation in C++
        this result is much faster than an implementation in python.

        Execute uses subprocess to call the program with the input
        image as the argument. The output image is presented in a
        an output file which is read and then returned

        '''
        prog_location = structure.Base.base_dir + 'operations/./Sauvola'

        # tries to call the Sauvola program which outputs to result.png
        try:
            # supress the standard error
            subprocess.check_output([prog_location, 's', '-x ' + str(self.options['window'][0]),
                                      '-y ' + str(self.options['window'][0]),
                                       '-k ' + str(self.options['k']),
                                        self.dirname + 'source.png',
                                         self.dirname + 'result.png'], stderr=False)
            # read the image output
            output = cv2.imread(self.dirname + 'result.png', 0)
        except subprocess.CalledProcessError:
            print('Error using Sauvola Method')

        return output

    def __str__(self):
        '''
        Returns string when printing the operation
        '''
        return self.NAME + ' --> ' + self.options.__str__()

if __name__ == '__main__':
    '''
    Example of the use of the Sauvola method to enhance an image.
    '''
    # select the sample image to transform
    sample_file = structure.Base.sample_dir + 'sample.png'

    img = cv2.imread(sample_file, 0)

    op = Sauvola(img, options={'window':(69, 13), 'k':0.01})

    print(op)

    # output the image in a window
    cv2.imshow("Sauvola Output", op.execute())
    cv2.waitKey(0)
    cv2.destroyAllWindows()


#!/usr/bin/env python3

import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='imem converter')
    parser.add_argument('imemdat', type=argparse.FileType('r'), metavar='PATH')
    parser.add_argument('-t', type=argparse.FileType('r'), metavar='PATH', dest='template')
    parser.add_argument('-o', type=argparse.FileType('w'), metavar='PATH', dest='outfile')
    args = parser.parse_args()
    ostr = ""
    for i, line in enumerate(args.imemdat):
        line = line.replace('\n', '')
        ostr += ("mem[{}] <= 32'h{};\n".format(i, line))
    text = args.template.read().replace("PLACEHOLDER", ostr)
    args.outfile.write(text)


#! /usr/bin/env python

from setuptools import setup
from distutils.extension import Extension

VERSION = '0.0.1'

DESCRIPTION = """\
A gevent (http://www.gevent.org) adaption of the asynchronous MySQL driver
from the Concurrence framework (http://opensource.hyves.org/concurrence)
"""

setup(
    name="gevent-MySQL",
    version=VERSION,
    license="New BSD",
    description=DESCRIPTION,
    package_dir={'': 'lib'},
    packages=['geventmysql'],
    install_requires=["gevent"],
    ext_modules=[Extension("geventmysql._mysql",
        ["lib/geventmysql/geventmysql._mysql.c"])]
)


from flask import Blueprint, request
import jwt, os
from user.models import User
from auth.utils import decode_jwt

user_blueprint = Blueprint("user", __name__)

@user_blueprint.route("/", methods=["GET"])
def get_user_profile():
    payload = decode_jwt(request.headers.get('Authorization'))
    if not payload:
        return {"error": "Token is not valid!"}, 401

    user = User.query.get(payload["user_id"])

    if not user:
        return {"error": "User not found!"}, 404

    return {
        'id': user.id,
        'username': user.username,
        'email': user.email
    }


import os
import sys

# Lessons learned
#  - read carefully: missed the cases with multiple hypernet sequences in 1 package
#    "____[------]____[----]____"
#  - set-operations
#    set.union(a, b, c, ...), set.intersect(...)

def has_abba(code):
    for i in range(len(code) - 3):
        if code[i] == code[i + 1]:
            continue
        if code[i] == code[i + 3] and code[i + 1] == code[i + 2]:
            return True
    return False

def get_abas(code, rev=False):
    abas = set()
    for i in range(len(code) - 2):
        if code[i] == code[i + 1]:
            continue
        if code[i] == code[i + 2] and not rev:
            abas.add(code[i:(i+2)])
        elif code[i] == code[i + 2] and rev:
            abas.add(code[(i+1):(i+3)])
    return abas

def run(indata):
    L = indata.splitlines(keepends=False)
    # ----------- PART 1 -----------
    #
    answer = 0
    for l in L:
        package = l.replace(']', '[').split('[')
        if any([has_abba(p) for p in package[1::2]]):
            continue
        if any([has_abba(p) for p in package[0::2]]):
            answer += 1
    print("Part 1: {}".format(answer))

    # ----------- PART 2 -----------
    #
    answer = 0
    for l in L:
        package = l.replace(']', '[').split('[')
        abas = set.union(*[get_abas(p, rev=False) for p in package[0::2]])
        babs = set.union(*[get_abas(p, rev=True) for p in package[1::2]])
        if len(set.intersection(abas, babs)) > 0:
            answer += 1
    print("Part 2: {}".format(answer))

if __name__ == '__main__':
    # Initialize
    ROOT = os.path.dirname(os.path.dirname(__file__))
    sys.path.append(ROOT)
    from aoc_utils import get_input, clipboard_set

    # Get input data
    day = int(os.path.basename(__file__)[3:5])
    year = int(os.path.basename(os.path.dirname(__file__)))
    indata = get_input(day, year)

    # Run
    answer = run(indata)

    # Copy to clipboard?
    if answer is not None:
        clipboard_set(str(answer))


from django.urls import path
from polls import views

app_name = 'polls'
urlpatterns = [
# regex, view, name
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.DetailsView.as_view(), name='detail'),
    path('<int:pk>/results/', views.ResultView.as_view(), name='results'),
    path('<int:pk>/vote/', views.vote, name='vote'),
]


#!/usr/bin/env python

"""Main Labeler task."""

import uuid
import urllib
import base64
import os
import json
import datetime
import math
import tempfile

from server_common import mturk_template, create_app, \
    database_session, mturk_save

from flask import jsonify, request
from flask.ext.restful import reqparse

from PIL import Image, ImageDraw

import boto
from boto.s3.key import Key

import database

from sqlalchemy import func, or_

APP = create_app(
    __name__,
    js_assets=[
        'js/three.min.js',
        'js/common.js',
        'js/task.js',
        'js/basetask.js',
        'js/labeler_task.js',
    ],
)

@APP.route('/')
def template():
    """Labeler template handler."""

    return mturk_template(request.args, 'labeler')

@APP.route('/load')
@database_session()
def load(session, user):
    """Labeler load handler."""

    parser = reqparse.RequestParser()
    parser.add_argument('pid', None, type=int)
    parser.add_argument('rid', None, type=int)
    args = parser.parse_args()

    if args.pid is not None and args.rid is not None:
        return 'only pid or rid allowed', 400

    if args.pid is None and args.rid is None:
        # pylint: disable-msg=E1101,E1103
        photo = session.query(database.Photo) \
            .outerjoin(database.Annotation) \
            .group_by(database.Photo.id) \
            .having(func.bool_and(or_(
                database.Annotation.uid != user.id,
                database.Annotation.uid == None))) \
            .having(func.count(database.Annotation.id) < 2) \
            .order_by(func.random()) \
            .filter(database.Photo.seesground == True) \
            .first()
        # pylint: enable-msg=E1101,E1103

        cameraheight = photo.aboveground if photo.aboveground > 0 else 1.75

        if photo:
            result = {
                'cameraheight': cameraheight,
                'cars': [],
            }
    elif args.pid and not args.rid:
        photo = session.query(database.Photo) \
            .filter_by(id=args.pid) \
            .one()
        cameraheight = photo.aboveground if photo.aboveground > 0 else 1.75
        result = {
            'cameraheight': cameraheight,
            'cars': [],
        }
    elif args.rid:
        revision = session.query(database.Revision) \
            .filter_by(id=args.rid) \
            .one()

        photo = revision.annotation.photo

        cameraheight = photo.aboveground if photo.aboveground > 0 else 1.75
        result = {
            'cameraheight': cameraheight,
            'cars': [],
        }
        cars = []
        for vehicle in revision.vehicles:
            car = {
                'x': vehicle.x,
                'z': vehicle.z,
                'theta': vehicle.theta,
                'type': vehicle.type,
            }
            cars += [car]
        result = {
            'cameraheight': revision.cameraheight,
            'cars': cars,
            'comment': revision.comment,
        }
        for flag in revision.annotation.flags:
            result['reason'] = flag.reason

    if photo is None:
        return jsonify(status='empty')
    else:
        fov = math.degrees(2 * math.atan2(photo.height, 2 * photo.focal))
        data = {
            'id': photo.id,
            'image': os.path.join(APP.config['HOST'], photo.name),
            'width': photo.width,
            'height': photo.height,
            'focal': photo.focal,
            'upx': photo.r21,
            'upy': photo.r22,
            'upz': -photo.r23,
            'forwardx': -photo.r31,
            'forwardy': -photo.r32,
            'forwardz': photo.r33,
            'lat': photo.lat,
            'lon': photo.lon,
            'fov': fov,
            'aspect': float(photo.width) / photo.height,
            'result': result,
        }

        return jsonify(status='ok', data=data)

@APP.route('/save', methods=['POST'])
@database_session()
@mturk_save()
def save(session, user, assignment):
    """Labeler save handler."""

    parser = reqparse.RequestParser()
    parser.add_argument('pid', type=int)
    parser.add_argument('rid', type=int)
    parser.add_argument('duration', type=int, required=True)
    parser.add_argument('cameraheight', type=float, required=True)
    parser.add_argument('cars', type=str, required=True)
    parser.add_argument('screenshot', type=str, required=True)
    parser.add_argument('final', type=bool, required=True)
    parser.add_argument('comment', type=str, required=True)
    args = parser.parse_args()

    if args.pid is not None and args.rid is not None:
        return 'only pid or rid allowed', 400

    if args.rid is None and args.pid is None:
        return 'rid or pid required', 400

    args.cars = json.loads(args.cars)

    if args.rid is not None:
        parent_revision = session.query(database.Revision) \
            .filter_by(id=args.rid) \
            .one()

        latest_revision = session.query(database.Revision) \
            .filter_by(parent_id=args.rid) \
            .first()

        if latest_revision is not None:
            return 'client is out of date', 400

        annotation = parent_revision.annotation

    else:
        annotation = database.Annotation(
            pid=args.pid,
            user=user,
        )
        session.add(annotation)

        parent_revision = None

    revision = database.Revision(
        annotation=annotation,
        cameraheight=args.cameraheight,
        creation=datetime.datetime.now(),
        duration=datetime.timedelta(milliseconds=args.duration),
        parent=parent_revision,
        final=args.final,
        comment=args.comment,
        assignment=assignment,
    )

    conn = boto.connect_s3(
        aws_access_key_id=APP.config['AWS_ACCESS_KEY_ID'],
        aws_secret_access_key=APP.config['AWS_SECRET_ACCESS_KEY'],
    )
    s3bucket = conn.lookup(APP.config['BUCKET'])
    k = Key(s3bucket)
    k.key = os.path.join(
        'screenshots',
        '%s.png' % uuid.uuid4(),
    )
    k.set_contents_from_string(args.screenshot)
    k.set_acl('public-read')
    revision.screenshot = k.key

    for car in args.cars:
        vehicle = database.Vehicle(
            type=car['type'],
            x=car['x'],
            z=car['z'],
            theta=car['theta'],
            x1=car['x1'],
            x2=car['x2'],
            y1=car['y1'],
            y2=car['y2'],
            revision=revision,
            bbox_priority=10,
        )

        # pylint: disable-msg=E1101
        vehicle.truncated = 1 - \
            (min(1, vehicle.x2) - max(0, vehicle.x1)) * \
            (min(1, vehicle.y2) - max(0, vehicle.y1)) / \
            ((vehicle.x2 - vehicle.x1) * (vehicle.y2 - vehicle.y1))
        # pylint: enable-msg=E1101
        session.add(vehicle)

    session.add(revision)

    session.flush()
    session.commit()

    with tempfile.NamedTemporaryFile(suffix='.jpg') as file_in:
        # pylint: disable-msg=E1101
        photo = revision.annotation.photo
        # pylint: enable-msg=E1101
        k = Key(s3bucket)
        k.key = photo.name
        k.get_contents_to_filename(file_in.name)
        image_in = Image.open(file_in.name)
        APP.logger.info(photo.name)
        APP.logger.info(file_in.name)

        for vehicle in revision.vehicles:
            if vehicle.cropped is not None:
                continue

            copy = image_in.copy()
            draw = ImageDraw.Draw(copy)

            x1 = vehicle.x1
            x2 = vehicle.x2
            y1 = vehicle.y1
            y2 = vehicle.y2

            width, height = copy.size
            box_width = width * (x2 - x1)
            box_height = height * (y2 - y1)
            box_x1 = int(math.ceil(
                max(0, min(width - 1, width * x1 - 0.25 * box_width))
            ))
            box_x2 = int(math.floor(
                max(0, min(width - 1, width * x2 + 0.25 * box_width))
            ))
            box_y1 = int(math.ceil(
                max(0, min(height - 1, height * y1 - 0.25 * box_height))
            ))
            box_y2 = int(math.floor(
                max(0, min(height - 1, height * y2 + 0.25 * box_height))
            ))
            if box_x1 == box_x2 or box_y1 == box_y2:
                box_x1 = 0
                box_x2 = 1
                box_y1 = 0
                box_y2 = 1
            draw.rectangle(
                (width * x1, height * y1, width * x2, height * y2),
                outline='red'
            )
            del draw
            cropped = copy.crop((box_x1, box_y1, box_x2, box_y2))

            with tempfile.NamedTemporaryFile(suffix='.jpg') as file_out:
                cropped.save(file_out.name, quality=90)
                k = Key(s3bucket)
                k.key = os.path.join('labels', '%d.jpg' % vehicle.id)
                k.content_type = 'image/png'
                k.set_contents_from_file(file_out)
                k.set_acl('public-read')
                vehicle.cropped = k.key

    session.flush()
    session.commit()

    # pylint: disable-msg=E1101
    return jsonify(status='ok', id=revision.id)
    # pylint: enable-msg=E1101

@APP.route('/flag', methods=['POST'])
@database_session()
def flagger(session, user):
    """Labeler flag handler."""

    parser = reqparse.RequestParser()
    parser.add_argument('pid', type=int)
    parser.add_argument('rid', type=int)
    parser.add_argument('reason', type=str, required=True)
    args = parser.parse_args()

    if args.rid is None and args.pid is None:
        return 'rid or pid is required', 400

    if args.rid is not None:
        revision = session.query(database.Revision) \
            .filter_by(id=args.rid) \
            .one()

        annotation = revision.annotation
    else:
        annotation = database.Annotation(
            pid=args.pid,
            user=user,
        )
        session.add(annotation)

    flag = database.Flag(
        annotation=annotation,
        reason=args.reason
    )

    session.add(flag)

    session.flush()
    # pylint: disable-msg=E1101
    session_id = flag.id
    # pylint: enable-msg=E1101
    session.commit()

    return jsonify(status='ok', id=session_id)

@APP.route('/screenshot', methods=['POST'])
def screenshot():
    """Submit screenshot to server."""

    parser = reqparse.RequestParser()
    parser.add_argument('screenshot', type=str, required=True)
    args = parser.parse_args()

    conn = boto.connect_s3(
        aws_access_key_id=APP.config['AWS_ACCESS_KEY_ID'],
        aws_secret_access_key=APP.config['AWS_SECRET_ACCESS_KEY'],
    )
    s3bucket = conn.lookup(APP.config['BUCKET'])
    k = Key(s3bucket)
    k.key = os.path.join(
        'problem_screenshots',
        '%s.png' % str(datetime.datetime.now())
    )
    prefix, data = args.screenshot.split(',')
    if prefix != 'data:image/png;base64':
        return 'wrong prefix', 400
    decoded = base64.b64decode(data)
    k.set_contents_from_string(decoded)
    k.set_acl('public-read')

    image = os.path.join(APP.config['HOST'], urllib.quote(k.key))

    data = {'image': image}

    return jsonify(status='ok', data=data)

if __name__ == '__main__':
    APP.run()


import chainer
import chainer.functions as F
import matplotlib.pyplot as plt
import numpy as np

def draw_figure(ax, w, b, xlim=(15, 35), ylim=(0, 12), x_range=(17, 33)):
    """グラフを描画するためのヘルパー関数"""

    ax.scatter(x, t, color='blue', linewidths='1')
    ax.plot(x_range, w * x_range + b, color='black')
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)

def train(x, t, initial_w, initial_b, epoch, alpha, show_figure):
    """学習を行う関数"""

    x = np.array(x, dtype=np.float32)
    t = np.array(t, dtype=np.float32)

    # 重みの初期化
    w = chainer.Variable(np.array(initial_w, dtype=np.float32))
    b = chainer.Variable(np.array(initial_b, dtype=np.float32))

    if show_figure:
        fig = plt.figure(figsize=(16, 9))

    for i in range(epoch):
        # 勾配をクリア
        w.cleargrad()
        b.cleargrad()

        # 家賃の予測値 y を計算
        y = w * x + b
        # 損失を計算
        loss = F.sum(F.squared_error(y, t))

        # グラフの描画
        if show_figure:
            ax = fig.add_subplot((epoch + 4) // 5, 5, i + 1)
            draw_figure(ax, w.array, b.array)

        # 自動微分により w, b の勾配を計算
        loss.backward()

        # 勾配を用いて w, b の値を更新
        w.array -= alpha * w.grad
        b.array -= alpha * b.grad

    if show_figure:
        plt.show()
    return w, b

x = [20, 25, 30]  # 入力（部屋の広さ）
t = [4, 7, 9]  # 教師データ（家賃）

initial_w = 0.4  # 傾きの初期値
initial_b = -6  # 切片の初期値
epoch = 20  # エポック数（データを何周するか）
alpha = 0.00004  # 学習率

# 学習
w, b = train(x, t, initial_w, initial_b, epoch, alpha, show_figure=True)
print(f'w = {w}, b = {b}')

# 最終結果の表示
ax = plt.figure().add_subplot(111)
draw_figure(ax, w.array, b.array)
plt.show()


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

# https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/37154/8-lines-of-python-solution-(reverse-preorder-traversal)

class Solution:
    def __init__(self):
        self.prev = None
    def flatten(self, root: TreeNode) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        if not root:
            return
        self.flatten(root.right)
        self.flatten(root.left)

        # print(root.val)
        root.right = self.prev
        root.left = None

        self.prev = root


from turtle import *
speed(0)
def poli(i):
	for j in range(i):
		forward(20 * i)
		right(360 / i)

for i in range(3, 13, 1):
	right(90 + 180 / i)
	poli(i)
	left(90 + 180 / i)
	penup()
	forward(23)
	pendown()


# function to create a Document sub-collection if it doesn't exist and set the 'docs' field of the document

import firebase_admin
import time
from firebase_admin import credentials
from firebase_admin import firestore

cred = credentials.Certificate("AccountServiceKey.json")
# Initializing the app
firebase_admin.initialize_app(cred)
db = firestore.client()

def doc_type_set(data,l_data):

	# getting the user_doc_id
	doc_ref = data['user_doc_id']

	# setting the timestamp
	ts = int(time.time())
	data['timestamp'] = ts

	# Set the default value of approver to folk_guide, from the profile section
	if data['approver'] == '':
		print('fuck')
		doc_folk_guide = db.collection('Profile').document(doc_ref).get().to_dict()['folk_guide']
		data['approver'] = doc_folk_guide

	#getting the doctype
	doc_type = data['doc_type']

	# Set default verification_status to pending
	if data['verification_status'] != '':
		data['verification_status'] = 'pending'

	doc = 0
	doc_ = db.collection('Profile').document(doc_ref).collection('Documents').stream()
	for i in doc_:
		doc += 1

	docs_ref = db.collection('Profile').document(doc_ref)
	if True:
		# create a reference to the docs section
		if (doc == 1):
			# First document so set the left side docs to the required format
			docs_ref.set({'docs': l_data}, merge=True)
		else:
			# get the verification status of the docs document
			ref_doc = docs_ref.get().to_dict()
			verify_status=''
			if 'docs' in ref_doc:
				if status in ref_doc['docs']:
					verify_status = ref_doc['docs'][status]
					verify_status = verify_status.lower()

			flag = 0
			if verify_status=='':
				flag=1
			if verify_status == 'pending' and data['verification_status'] == 'pending':
				flag = 1
			elif verify_status == 'pending' and data['verification_status'] == 'verified':
				flag = 1
			elif verify_status == 'verified' and data['verification_status'] == 'verified':
				flag = 1
			elif verify_status not in ['pending', 'verified']:
				flag = 1
			if flag == 1:

				if doc_type=='photo':
					docs_ref.set({'docs': {'photo_url': l_data['photo_url'],'last_timestamp':int(time.time()),
										   'photo_url_last_submission': l_data['photo_url_last_submission'],
										   'photo_verification_status': l_data['photo_verification_status']}},
								 merge=True)
				elif doc_type == 'id_proof':
					docs_ref.set({'docs': {'id_proof_url': l_data['id_proof_url'],'last_timestamp':int(time.time()),
										   'id_proof_last_submission': l_data[
											   'id_proof_last_submission'],
										   'id_proof_verification_status': l_data[
											   'id_proof_verification_status']}}, merge=True)

data = {'uploaded_by':'008jYwyjRDJDqLZwDcrJ',
        'doc_type':'certificate',
        'doc_link' : 'https://firebases//',
        'reference_file_name' :'Ahmedabad.jpg',
        'file_type':'jpg',
        'user_doc_id':'cGHgvv85qrbe16RDohXk',
        'verification_status':'verified',
        'doc_details':'Ration Card',
        'approver':'',
        'remarks':'verified'
        }
l_data = {
		# approver is common to all document types
		'approver': data['approver'],
		'documents_verification_status': '',
		'id_proof_last_submission': 0,
		'id_proof_url': '',
		'id_proof_verification_status': '',
		'last_submission': 0,
		'photo_url': '',
		'photo_url_last_submission': 0,
		'photo_verification_status': ''
	}

doc_type_set(data,l_data)


import pandas as pd
import numpy as np
#两种数据类型，serise,dataframe
#serise
id=['a','b','c']
s=pd.Series(25,index=id)
dt={'one':[1,2,3],'two':[4,5,6]}
d=pd.Series(dt)
print(d)
nd=pd.Series(np.arange(4),index=id+['d'])
ls=pd.Series([1,2,3],index=id)
#基本操作类似于ndarray,dict
d.get('f',10)
print('one' in d)#只判断自定义索引
print(ls[ls>1],'\n',ls[['a','b']],'\n',ls[[0,1]],'\n',ls[:2],'\n') #选择
print(nd+s)#补齐原则，相同索引元素相加,不同索引置nan
d.name='so'
d.index.name='ind'#name属性
print(d)
#dataframe,基于serise
dfdt=pd.DataFrame(dt)
print(dfdt)
dfnd=pd.DataFrame(np.arange(12).reshape(3,4),index=id,columns=id+['d'])
print(dfnd)
print(dfdt.loc[0,'one'],',',dfdt.iloc[0,0])#获取元素，loc,可以是label,iloc必须是整数
#对索引进行重排
dfnd.reindex(index=['c','a','b'],columns=['d','a','c','b'])
print(dfdt.drop(labels='one',axis=1))
#累加函数，相关分析函数


import os
import csv
import random as r2
import time

def pushToSpreadsheet(valve,data):
    #Separate buffer
    fdata = str(data[0])
    pdata = str(data[1])
    print(fdata)
    print(pdata)
    #Get file
    files = ["dataValue-1.csv"]
    #Open and write
    with open(files[valve - 1], 'a', encoding='UTF8') as f:
        writer = csv.writer(f)
        writer.writerows(zip(fdata,pdata))

def generateRandom():
    #Random flow
    flow = r2.randint(1,200)
    print(flow)
    #Random Pressure
    pres = r2.randint(1,10)
    dataCompiled = [flow,pres]
    return dataCompiled

while True:
    dataArray = generateRandom()
    pushToSpreadsheet(1,dataArray)


# -*-coding: utf-8 -*-

from sqlalchemy import (
    Column,
    Integer,
    String,
    Table,
    ForeignKey
    )
from sqlalchemy.orm import (
    relationship,
    backref
)

from ..models import (
    DBSession,
    Base
)

structure_contact = Table(
    'structure_contact',
    Base.metadata,
    Column(
        'structure_id',
        Integer,
        ForeignKey(
            'structure.id',
            ondelete='restrict',
            onupdate='cascade',
            name='fk_structure_id_structure_contact',
        ),
        primary_key=True,
    ),
    Column(
        'contact_id',
        Integer,
        ForeignKey(
            'contact.id',
            ondelete='restrict',
            onupdate='cascade',
            name='fk_contact_id_structure_contact',
        ),
        primary_key=True,
    )
)

structure_bank_detail = Table(
    'structure_bank_detail',
    Base.metadata,
    Column(
        'structure_id',
        Integer,
        ForeignKey(
            'structure.id',
            ondelete='restrict',
            onupdate='cascade',
            name='fk_structure_id_structure_bank_detail',
        ),
        primary_key=True,
    ),
    Column(
        'bank_detail_id',
        Integer,
        ForeignKey(
            'bank_detail.id',
            ondelete='restrict',
            onupdate='cascade',
            name='fk_bank_detail_id_structure_bank_detail',
        ),
        primary_key=True,
    )
)

structure_address = Table(
    'structure_address',
    Base.metadata,
    Column(
        'structure_id',
        Integer,
        ForeignKey(
            'structure.id',
            ondelete='restrict',
            onupdate='cascade',
            name='fk_structure_id_structure_address',
        ),
        primary_key=True,
    ),
    Column(
        'address_id',
        Integer,
        ForeignKey(
            'address.id',
            ondelete='restrict',
            onupdate='cascade',
            name='fk_address_id_structure_address',
        ),
        primary_key=True,
    )
)

class Structure(Base):
    __tablename__ = 'structure'

    id = Column(
        Integer,
        primary_key=True,
        autoincrement=True
    )
    resource_id = Column(
        Integer,
        ForeignKey(
            'resource.id',
            name="fk_resource_id_structure",
            ondelete='restrict',
            onupdate='cascade',
        ),
        nullable=False,
    )
    parent_id = Column(
        Integer(),
        ForeignKey(
            'structure.id',
            name='fk_structure_parent_id',
            onupdate='cascade',
            ondelete='restrict',
        )
    )
    company_id = Column(
        Integer(),
        ForeignKey(
            'company.id',
            name='fk_structure_company_id',
            onupdate='cascade',
            ondelete='restrict',
        ),
        nullable=False,
    )
    name = Column(
        String(length=32),
        nullable=False
    )
    resource = relationship(
        'Resource',
        backref=backref(
            'structure',
            uselist=False,
            cascade="all,delete"
        ),
        foreign_keys=[resource_id],
        cascade="all,delete",
        uselist=False
    )

    children = relationship(
        'Structure',
        backref=backref(
            'parent',
            remote_side=[id]
        ),
        uselist=True,
        lazy='dynamic',
    )
    company = relationship(
        'Company',
        backref=backref(
            'structures',
            uselist=True,
            lazy='dynamic'
        ),
        uselist=False,
    )
    contacts = relationship(
        'Contact',
        secondary=structure_contact,
        backref=backref(
            'structure',
            uselist=False
        ),
        uselist=True,
    )
    addresses = relationship(
        'Address',
        secondary=structure_address,
        backref=backref(
            'structure',
            uselist=False
        ),
        uselist=True,
    )
    banks_details = relationship(
        'BankDetail',
        secondary=structure_bank_detail,
        backref=backref(
            'structure',
            uselist=False
        ),
        uselist=True,
    )

    @classmethod
    def get(cls, id):
        if id is None:
            return None
        return DBSession.query(cls).get(id)

    @classmethod
    def by_resource_id(cls, resource_id):
        if resource_id is None:
            return None
        return (
            DBSession.query(cls).filter(cls.resource_id == resource_id).first()
        )

    @classmethod
    def condition_root_level(cls):
        return cls.parent_id == None

    @classmethod
    def condition_parent_id(cls, parent_id):
        return cls.parent_id == parent_id

    def get_all_descendants(self):
        all_structures = DBSession.query(Structure)
        structures = {}

        for item in all_structures:
            item_children = structures.setdefault(item.parent_id, [])
            item_children.append(item)
            structures[item.parent_id] = item_children

        def recurse_accumulate(item, result):
            if structures.get(item.id):
                for item in structures.get(item.id):
                    result.append(item)
                    recurse_accumulate(item, result)
            return result

        if structures.get(self.id):
            result = []
            return recurse_accumulate(self, result)
        return []

    def __repr__(self):
        return u"<Structure id=%d>" % self.id


import faulthandler;

faulthandler.enable()

import sys, getopt
import pickle
import os
import subprocess
import pandas as pd
from sklearn.cluster import MiniBatchKMeans
import warnings
import hdbscan
import umap
from tqdm import tqdm
import itertools
import time
import numpy as np
from sklearn.cluster import AgglomerativeClustering
from sklearn.pipeline import Pipeline
from sklearn.metrics import silhouette_score, calinski_harabasz_score, davies_bouldin_score

"""
Script to gridsearch with loads of different algorithms.
Did a search on lots of differnt algorithm not all made it to the paper
"""

class BaseAlg():
    """
    Base gridsearch class. This one assumes a sklearn Object. If other thing are used overwrite according methods.
    """

    def __init__(self):
        self.parameters = {}
        self.algorithm = None
        self.classes_ = None

    # Can be changed
    def set_classes(self, X):
        """
        Set the classes of the current run
        input variables:
            X: Train data
        """
        # Get the clasess of the fit algotroithm
        self.classes_ = self.algorithm.labels_

    def fit(self, X):
        """
        Fit the current model
        input variables:
            X: Train data
        """
        # Fit the model and time how long it takes
        self.classes_ = None
        start_time = time.time()
        self.algorithm.fit(X)
        fit_time = time.time() - start_time
        # Set the classes of the fit model
        self.set_classes(X)
        return fit_time

    def get_classes(self):
        """
        Get the current classes
        """
        if self.classes_ is not None:
            return self.classes_
        else:
            warnings.warn('Classes have not been set')

    def check_params(self, parameter):
        """
        Check the current gridsearch parameters if they exist in the model
        input variables:
            parameter: Parameters to check
        """
        for name in parameter:
            if name not in self.algorithm.__dict__:
                warnings.warn(f'{name} not in algorithm')

    def helper_set(self, parameter):
        """
        Set the current gridsearch parameters
        input variables:
            parameter: Parameters to check
        """
        # Set the parameters of the algorithm
        self.algorithm.set_params(**parameter)

    def set_params(self, parameter):
        """
        Set the current gridsearch parameters
        input variables:
            parameter: Parameters to check (Dictionary)
        """
        self.check_params(parameter)
        self.helper_set(parameter)

    def get_params(self):
        """
        Get the current gridsearch parameters
        """
        return self.parameters

# Hierarchical clustering need a change in the fit method for faster loading
class Hierachical(BaseAlg):
    """
    Gridsearch for hierarchical clustering (Not used R version is used instead)
    """
    def __init__(self, X):
        self.parameters = {'n_clusters': np.arange(2, 25),
                           }
        self.algorithm = AgglomerativeClustering()
        self.corr = 1 - np.absolute(pd.DataFrame(X).T.corr().values)

    def fit(self, X):
        """
        Fit the current model
        input variables:
            X: Train data
        """
        self.classes_ = None
        start_time = time.time()
        self.algorithm.fit(self.corr)
        fit_time = time.time() - start_time
        self.set_classes(X)
        return fit_time

# MAFIA is a tested algorithm that needed to overwrite everything
class MAFIA(BaseAlg):
    def __init__(self):
        """
        Gridsearch for MAFIA (Not used in report)
        """
        self.parameters = {'a': np.linspace(0.5, 5, 5),
                           'b': np.linspace(0.25, 0.75, 4),
                           'n': np.arange(100, 2001, 250),
                           'u': np.arange(1, 11, 5),
                           'M': np.arange(15, 31, 5),
                           }
        self.algorithm = None
        self.classes_ = None
        self.current_params = None

    def set_classes(self, X):
        """
        Set the classes of the current run
        input variables:
            X: Train data
        """
        # Load all the classes
        rows = []
        clusters = []
        directory = '/data/g0017139/MAFIA'
        # Get the algorithms as save in a file
        for filename in os.listdir(directory):
            if filename.endswith(".idx"):
                loadedrow = pd.read_table(f"{directory}/{filename}", sep="  ", header=None,
                                          engine='python').values.tolist()
                os.remove(f"{directory}/{filename}")
                clusters.extend(np.repeat(int(filename.split('-')[1].replace('.idx', '')), len(loadedrow)))
                rows.extend(loadedrow)
        rows = np.array(rows).ravel()
        clusters = np.array(clusters)
        # Get some outliers
        test = np.arange(0, len(X))
        for x in test:
            if x not in rows:
                rows = np.append(rows, x)
                clusters = np.append(clusters, -1)
        # Clean it
        rows_to_cluster = pd.DataFrame(clusters, index=rows)
        rows_to_cluster = rows_to_cluster[~rows_to_cluster.index.duplicated(keep='last')]
        rows_to_cluster = rows_to_cluster.sort_index()
        self.classes_ = rows_to_cluster.values.ravel()

    # Fit it in a terminal (Doesn't work anymore because the algorithm file is removed)
    def fit(self, X):
        """
        Fit the current model
        input variables:
            X: Train data
        """
        self.classes_ = None
        pd.DataFrame(X).to_csv("/data/g0017139/MAFIA/X.dat", sep=" ", header=False, index=False)
        start_time = time.time()
        subprocess.run(
            f"/home/g0017139/UMCG_Thesis/Working_Code/bin/cppmafia /data/g0017139/MAFIA/X.dat -a {self.current_params['a']} -b {self.current_params['b']} -n {self.current_params['n']} -u {self.current_params['u']} -M {self.current_params['M']}",
            shell=True)
        fit_time = time.time() - start_time
        self.set_classes(X)
        return fit_time

    def get_classes(self):
        """
        Get the current classes
        """
        if self.classes_ is not None:
            return self.classes_
        else:
            warnings.warn('Classes have not been set')

    # Can be changed
    def helper_set(self, parameter):
        """
        Set the current gridsearch parameters
        input variables:
            parameter: Parameters to check
        """
        self.current_params = parameter

    # parameter should be a dictionary
    def set_params(self, parameter):
        """
         Set the current gridsearch parameters
         input variables:
             parameter: Parameters to check (Dictionary)
         """
        self.helper_set(parameter)

    def get_params(self):
        """
        Get the current gridsearch parameters
        """
        return self.parameters

# Kmeans is sklearn so doesn't need any changes
class Kmeans(BaseAlg):
    """
    Gridsearch for K-means
    """
    def __init__(self):
        self.parameters = {'n_clusters': np.arange(2, 31), 'batch_size': [128, 256, 512, 1024]}
        self.algorithm = MiniBatchKMeans(random_state=0)
        self.classes_ = None

# ESSC another custom algorithm need some small changes
class ESSCGrid(BaseAlg):
    """
    Gridsearch for ESSC (Not used)
    """
    def __init__(self):
        self.parameters = {'n_cluster': np.arange(2, 15, 1),
                           'eta': [0.01, 0.25, 0.5, 0.75, 1.0],
                           'gamma': [1, 5, 10, 50, 100, 500, 1000]
                           }
        self.algorithm = ESSC(None)
        self.classes_ = None

    def set_classes(self, X):
        """
        Set the classes of the current run
        input variables:
            X: Train data
        """
        self.classes_ = self.algorithm.predict(X)
        self.classes_ = [np.argmax(q) for q in self.classes_]

    # parameter should be a dictionary
    def helper_set(self, parameter):
        """
        Set the current gridsearch parameters
        input variables:
            parameter: Parameters to check
        """
        for name in parameter:
            setattr(self.algorithm, name, parameter[name])

# Elasticsspace subnet basically sklearn object with some small changes
class ENSC(BaseAlg):
    """
    Gridsearch for Elasticsspace (Not used)
    """
    def __init__(self):
        self.parameters = {'n_clusters': np.arange(2, 6, 1),
                           'tau': np.linspace(0.1, 1, 3),
                           'gamma': [1, 5, 100, 500]
                           }
        self.algorithm = ElasticNetSubspaceClustering(algorithm='spams')
        self.classes_ = None

    def helper_set(self, parameter):
        """
        Set the current gridsearch parameters
        input variables:
            parameter: Parameters to check
        """
        for name in parameter:
            setattr(self.algorithm, name, parameter[name])

# UMAP + DBSCAN work the same as sklearn so only needs some small layout adjustments
class UHDBSCAN(BaseAlg):
    """
    Gridsearch for UMAP + DBSCAN
    """
    def __init__(self):
        self.parameters = {'DimReduction__n_neighbors': [25, 50],
                           'DimReduction__min_dist': [0.1, 0.75],
                           'DimReduction__n_components': [50, 10, 2],
                           'Clustering__min_cluster_size': [25, 100],
                           'Clustering__min_samples': [25, 100],
                           'Clustering__cluster_selection_epsilon': [0.1, 0.75],
                           #  'Clustering__cluster_selection_method': ['eom']
                           }
        for name in self.parameters:
            if isinstance(self.parameters[name], type(np.array)):
                self.parameters[name] = self.parameters[name].tolist()
        self.algorithm = Pipeline([('DimReduction',
                                    umap.UMAP()),
                                   ('Clustering',
                                    hdbscan.HDBSCAN(core_dist_n_jobs=-1))
                                   ])
        self.classes_ = None

    def set_classes(self, X):
        """
        Set the classes of the current run
        input variables:
            X: Train data
        """
        self.classes_ = self.algorithm['Clustering'].labels_

    def check_params(self, parameter):
        """
        Check the current gridsearch parameters if they exist in the model
        input variables:
            parameter: Parameters to check
        """
        for name in parameter:
            if name not in self.algorithm.get_params():
                warnings.warn(f'{name} not in algorithm')

    def helper_set(self, parameter):
        """
        Set the current gridsearch parameters
        input variables:
            parameter: Parameters to check
        """
        self.algorithm.set_params(**parameter)

# Gridsearch with a BaseAlg object or the alterations
class Gridsearch():
    def __init__(self, name, X):
        self.name = name
        self.X = X
        self.scores = []
        self.algorithm = self.get_alg(name)
        self.parameters = self.algorithm.get_params()

    def get_str(self, alg):
        """
        Get the name of the file to save it correctly with the name being the parameters used for this run
        input parameters:
            alg: current algorithm object
        returns:
            str containing the name of the algorithm + parameters checked
        """
        the_str = str(alg)
        the_str = the_str.replace('(', '_')
        the_str = the_str.replace(')', '')
        the_str = the_str.replace('=', '__')
        the_str = the_str.replace(',', '_')
        the_str = the_str.replace('\n', '')
        for x in range(30):
            the_str = the_str.replace(' ', '')
        the_str = the_str.replace('[', '')
        the_str = the_str.replace(']', '')
        the_str = the_str.replace("'", '')
        the_str = the_str.replace("DimReduction", '')
        the_str = the_str.replace("Clustering", '')
        the_str = the_str.replace("Pipeline_steps", '')
        the_str = the_str.replace("dens_frac__0.0_dens_lambda__0.0", '')
        the_str = the_str.replace("____", '__')
        the_str = the_str.replace("__UMAP_", 'UMAP_')
        # the_str = the_str.replace(".", 'c')
        return the_str

    def fit(self, parameter, folder):
        """
        Fit the algorithm with a set of parameters
        input parameters:
            parameter: parameters to check the accuracy
            folder: str to save the results
        returns:
            The scores of the current set of parameters
        """
        # Fit it
        self.algorithm.set_params(parameter)
        fit_time = self.algorithm.fit(self.X)
        # Save alg
        algorithm_name = self.get_str(self.algorithm.algorithm)
        if 'UMAP' not in algorithm_name:
            with open(f'/scratch/g0017139/Models/{folder}/{algorithm_name}.pkl', 'wb') as f:
                pickle.dump(self.algorithm.algorithm, f, pickle.HIGHEST_PROTOCOL)
                # Get the scores
        current_scores = self.get_score(self.algorithm.get_classes())
        current_scores['Fit_Time'] = fit_time
        current_scores.update(parameter)
        # If n_clusters doesn't exist make a custom entry with the amount of clusters
        if 'n_clusters' not in current_scores:
            current_scores['n_clusters'] = len(set(self.algorithm.get_classes()))
            if -1 in self.algorithm.get_classes():
                current_scores['n_clusters'] = current_scores['n_clusters'] - 1

        return current_scores

    def start(self, folder):
        """
        Check every combination given and calculate the score
        input parameters:
            folder: str to save the results
        returns:
            The scores of the all set of parameters
        """
        combinations = list(self.product_dict(**self.parameters))
        self.scores = []
        for combination in tqdm(combinations):
            self.scores.append(self.fit(combination, folder))
        return self.scores

        # The current supported algorithms (Based on baseAlg implemented above)

    def get_alg(self, name):
        """
        Get the class of the specified algorithm
        input parameters:
            name: str name of the algorithms
        returns:
            Class of the algorithm
        """
        if name == 'kmeans':
            class_alg = Kmeans()
        elif name == 'essc':
            class_alg = ESSCGrid()
        elif name == 'ensc':
            class_alg = ENSC()
        elif name == 'dbscan':
            class_alg = UHDBSCAN()
        elif name == 'mafia':
            class_alg = MAFIA()
        elif name == 'hierach':
            class_alg = Hierachical(self.X)
        else:
            raise ValueError(
                f'Algorithm {name} is not implemented chose "kmeans" "essc" "ensc" "dbscan" "MAFIA", "hierach"')
        return class_alg

    def get_score(self, labels):
        """
        Calculate a correlation and euclidean score based on the labels
        input parameters:
            labels: list of labels assigned by the current algorithm
        returns:
           Dictionary of Silhouette score with the euclidean and correlation distance
        """
        result = {}
        try:
            result['silhouette_score_euclidean'] = silhouette_score(self.X, labels, metric='euclidean', n_jobs=-1)
        except:
            result['silhouette_score_euclidean'] = np.nan
        try:
            result['silhouette_score_correlation'] = silhouette_score(self.X, labels, metric='correlation', n_jobs=-1)
        except:
            result['silhouette_score_correlation'] = np.nan
        return result

    def product_dict(self, **kwargs):
        """
        Get all possible combinations of variables in kwargs
        """
        keys = kwargs.keys()
        vals = kwargs.values()
        for instance in itertools.product(*vals):
            yield dict(zip(keys, instance))

if __name__ == "__main__":
    # Set some of pythons limitations
    sys.setrecursionlimit(50000)
    argv = sys.argv[1:]
    # Read the parameters in the command line
    try:
        opts, args = getopt.getopt(argv, "f:a:s:")
    except getopt.GetoptError:
        sys.exit(2)
    for opt, arg in opts:
        # File to read
        if opt == "-f":
            input_path = arg
        # algorithm to use
        elif opt == "-a":
            algorithm_name = arg
        # File to save
        elif opt == "-s":
            folder = arg
    # Read input file and start gridsearch on this dataset with the given algorithm
    df = pd.read_csv(input_path, sep=None, engine='python', header=None)
    search = Gridsearch(algorithm_name, df)
    result = search.start(folder)
    # Save results
    with open(f'/home/g0017139/UMCG_Thesis/Scripts/Results/{folder}/{algorithm_name}{time.time()}.pkl', 'wb') as f:
        pickle.dump(pd.DataFrame(result), f, pickle.HIGHEST_PROTOCOL)


import os
import random
import threading
from time import sleep
from unittest import TestCase

import asn1tools
import wx

import asn1editor
from asn1editor.wxPython.ViewSelect import ViewType, TagInfo
from tests import TestHelper

def actions(main_window: asn1editor.wxPython.MainWindow):
    def get_children(window: wx.Window):
        my_children = window.GetChildren()
        if my_children is not None:
            their_children = []
            for my_child in my_children:
                their_children += get_children(my_child)
            return list(my_children) + their_children
        else:
            return []

    sleep(1)

    key_codes = [wx.WXK_TAB, wx.WXK_DOWN, wx.WXK_UP, wx.WXK_LEFT, wx.WXK_RIGHT, wx.WXK_SPACE] + [c for c in range(ord('1'), ord('9'))]

    ui_sim = wx.UIActionSimulator()

    for _ in range(1000):
        main_window.SetFocus()
        key_code = random.choice(key_codes)
        ui_sim.KeyDown(key_code)
        ui_sim.KeyUp(key_code)
    try:
        main_window.save_data_to_file('test.json')
    except asn1tools.ConstraintsError:
        pass

    main_window.Close(True)
    wx.GetApp().ExitMainLoop()

class MonkeyTest(TestCase):
    def test_monkey(self):
        if os.getenv('TRAVIS') is not None or os.getenv('GITHUB_ACTIONS') is not None:
            return
        # noinspection PyUnusedLocal
        app = TestHelper.get_wx_app()
        main_window = asn1editor.wxPython.MainWindow()
        main_window.select_view_and_tag_info(ViewType.GROUPS, TagInfo.TOOLTIPS)

        test_types = [('example/example.asn', 'EXAMPLE.Sequence')]

        for spec, type_ in test_types:
            self.assertTrue(main_window.load_spec(spec, type_))
            action_thread = threading.Thread(target=actions, args=[main_window])
            action_thread.start()
            main_window.Show()
            app.MainLoop()
            action_thread.join(timeout=0.0)


import os
from datetime import datetime, timedelta

import customtkinter as ctk
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter

# Functions
def validate_numeric_input(new_value):
    if new_value == "":
        return True
    try:
        float(new_value)
        return True
    except ValueError:
        return False

def on_button_click():
    item_name = item_name_entry_box.get()
    item_price = item_price_entry_box.get()
    selected_date = date_combobox.get()

    if item_name and item_price and selected_date != "Select Date":
        workbook = load_workbook(file_path)
        sheet = workbook.active
        next_row = sheet.max_row + 1
        sheet[f"A{next_row}"] = item_name
        sheet[f"B{next_row}"] = item_price
        sheet[f"C{next_row}"] = selected_date
        workbook.save(file_path)
        message_label.configure(text="Information noted!")
        main_window.after(2000, lambda: message_label.configure(text=""))
    else:
        message_label.configure(text="Please fill all fields!")
        main_window.after(2000, lambda: message_label.configure(text=""))

def day_suffix(day):
    if 4 <= day <= 20 or 24 <= day <= 30:
        return "th"
    else:
        suffixes = {1: "st", 2: "nd", 3: "rd"}
        return suffixes.get(day % 10, "th")

# Database stuff
folder_path = "C:/Expense-Tracker"
file_path = f"{folder_path}/Expenses.xlsx"
workbook = Workbook()
if os.path.exists(file_path):
    workbook = load_workbook(file_path)
else:
    if os.path.exists(folder_path):
        os.makedirs(file_path)
    else:
        os.makedirs(folder_path)
        open(file_path, "w").close()

workbook.save(file_path)

sheet = workbook.active
sheet["A1"] = "Item"
sheet["B1"] = "Price in ₱"
sheet["C1"] = "Date of purchase"

column_widths = [20, 20, 20]
column_range = range(1, 4)
row_range = range(1, sheet.max_row + 1)
for col_num, width in enumerate(column_widths, start=1):
    column_letter = get_column_letter(col_num)
    sheet.column_dimensions[column_letter].width = width

workbook.save(file_path)

# Main window stuff
main_window = ctk.CTk()
ctk.set_appearance_mode("dark")
ctk.set_default_color_theme("green")
main_window.title("Tkinter GUI")
screen_width = main_window.winfo_screenwidth()
screen_height = main_window.winfo_screenheight()
window_width = 500
window_height = 330
x = (screen_width // 2) - (window_width // 2)
y = (screen_height // 2) - (window_height // 2)
main_window.geometry(f"{window_width}x{window_height}+{x}+{y}")
main_window.resizable(False, False)

# Widget stuff
main_frame = ctk.CTkFrame(master=main_window)
main_frame.pack(pady=15, padx=20, fill="both", expand=True)
frame_label = ctk.CTkLabel(master=main_frame, text="Expense Tracker", font=("Roboto", 15))
frame_label.pack(pady=10, padx=13)

# Product info stuff
item_frame = ctk.CTkFrame(master=main_frame)
item_frame.pack(pady=10, padx=13)
item_frame.grid_columnconfigure(0, weight=1)
item_frame.grid_columnconfigure(1, weight=1)
item_frame.grid_columnconfigure(2, weight=1)

item_name_entry_box = ctk.CTkEntry(master=item_frame, placeholder_text="Item", placeholder_text_color="white")
item_name_entry_box.grid(row=0, column=0, padx=13, pady=10, sticky="nsew")

item_price_entry_box = ctk.CTkEntry(master=item_frame, placeholder_text="Price", placeholder_text_color="white")
item_price_entry_box.grid(row=0, column=1, padx=13, pady=10, sticky="nsew")
validate_cmd = (main_window.register(validate_numeric_input), '%P')
item_price_entry_box.configure(validate='key', validatecommand=validate_cmd)

start_date = datetime.now().date()
end_date = start_date.replace(month=12, day=31)
delta = timedelta(days=1)
date_list = []
current_date = start_date
while current_date <= end_date:
    date_list.append(current_date.strftime("%B %d"))
    current_date += delta

date_combobox = ctk.CTkComboBox(master=item_frame, values=date_list, state="readonly")
date_combobox.grid(row=0, column=2, padx=13, pady=10, sticky="nsew")
date_combobox.set("Select Date")

# Enter information
enter_button = ctk.CTkButton(master=main_frame, text="Enter", command=on_button_click)
enter_button.pack(pady=5, padx=13)
message_label = ctk.CTkLabel(master=main_frame, text="")
message_label.pack(pady=3, padx=4)

# Monthly report
report_label = ctk.CTkLabel(master=main_frame, text="Monthly report:")
report_label.pack(pady=5, padx=13, anchor="w")

report_frame = ctk.CTkScrollableFrame(master=main_frame)
report_frame.pack(pady=8, padx=13, fill="both", expand=True)
last_day_of_month = (start_date.replace(day=1, month=start_date.month + 1) - timedelta(days=1)).day
text_to_display = ""

report_workbook = load_workbook(file_path)
report_sheet = report_workbook.active

item_count = report_sheet["A"]
number_of_items = sum(1 for cell in item_count if cell.value is not None) - 1

item_price_range = report_sheet["B"][1:]
total_price = sum(float(cell.value) for cell in item_price_range if cell.value is not None)

if start_date.day == last_day_of_month:
    formatted_date = start_date.strftime("%d{suffix} of %B, %Y").format(suffix=day_suffix(start_date.day))
    text_to_display = f"By the end of the month ({formatted_date}), you bought {number_of_items} items and spent ₱{total_price} within this month."
else:
    text_to_display = "It's not the end of the month yet. No need for a report."

text_label = ctk.CTkLabel(master=report_frame, text=text_to_display, wraplength=340, justify="center")
text_label.pack(pady=10, padx=13)

main_window.mainloop()


# Import the rasterstats package
import rasterstats

# Extract the nearest value in the raster for all mining sites
vegetation_raster = "central_africa_vegetation_map_foraf.tif"
mining_sites['vegetation'] = rasterstats.point_query(mining_sites.geometry, vegetation_raster, interpolate='nearest')
print(mining_sites.head())

#print (vegetation_types)
# Replace numeric vegation types codes with description
mining_sites['vegetation'] = mining_sites['vegetation'].replace(vegetation_types)

# Make a plot indicating the vegetation type
mining_sites.plot(column="vegetation", legend=True)
plt.show()


# cython: language_level=3, cpp_locals=True
from pathlib import Path

import cython
from cython.cimports.libc.stdlib import free, malloc  # type: ignore
from cython.cimports.relatepy.pipeline import CombineSections, Options, get_options  # type: ignore

from ..utils import output_working_directory

@output_working_directory
def combine_sections(
    *, output: Path, chunk_index: int, effective_population_size: float | None = None
):
    args = [b"relate", b"--output", output.name.encode()]
    if effective_population_size is not None:
        args.extend([b"--effectiveN", f"{effective_population_size}".encode()])
    argv: cython.pp_char = cython.cast(
        cython.pp_char, malloc(cython.sizeof(cython.p_char) * len(args))
    )
    for i, arg in enumerate(args):
        argv[i] = arg
    options: Options = get_options(len(args), argv)
    CombineSections(options, chunk_index)
    free(argv)


from turtle import Turtle, right

FONT = ("Courier", 24, "normal")

class Scoreboard(Turtle):
    def __int__(self):
        super().__init__()
        self.color("black")
        self.penup()
        self.goto(0,270)
        self.increase=0
        self.updateScore()
        self.hideturtle()

    def updateScore(self):
        self.write(f"Level",align="right",font=FONT)

    def game_over(self):
        self.goto(0,0)
        self.color("red")
        self.write(f"Game over ☠",align="right",font=FONT)

    def increase_Score(self):
        self.increase+=1
        self.clear()
        self.updateScore()


from fastapi import FastAPI
import caldav_schedule as schedule
import logging

logging.basicConfig(level=logging.INFO)

cal = schedule.CalendarAPI()
app = FastAPI()

#just for debug process
@app.get("/hello")
def hello():
    return("Hello")

#get all timeslots
@app.get("/timeslots")
def get_timeslots():
    cal.refresh()
    return cal.timeslots

#get single slot
@app.get("/timeslots/{uid}")
def get_single_timeslot(uid):
    cal.refresh()
    return cal.timeslots[uid]

#get all PGMs
@app.get("/programs")
def get_programs():
    cal.refresh()
    return cal.programs

#get single PGM
@app.get("/programs/{uid}")
def get_single_program(uid):
    cal.refresh()
    return cal.programs[uid]


"""
ID: jameshu1
LANG: PYTHON3
TASK: nuggets
"""

import sys
from math import gcd
from functools import reduce

sys.stdin = open('nuggets.in', 'r')
sys.stdout = open('nuggets.out', 'w')

n = int(input())
nuggets = [int(input()) for _ in range(n)]

if reduce(gcd, nuggets) > 1:
    print(0)
else:
    possible = [False for _ in range(256)]
    possible[0] = True

    last = 0
    for i in range(2000000000):
        if i > 256 + last:
            break
        if not possible[i % 256]:
            last = i
        else:
            possible[i % 256] = False
            for nugget in nuggets:
                possible[(i + nugget) % 256] = True

    print(last)


import requests
import pandas as pd

access_token = "<YOUR_ACCESS_TOKEN>"
headers = {'Authorization':"Token "+access_token}
#private to get private repo, public to get public repositories
payload={"visibility":"private"}
url = "https://api.github.com/user/repos"
res= requests.get(url,headers=headers,params=payload)
#print("res.status_code: {}".format(res.status_code))
if res.status_code == 200:
  data=res.json()
  df = pd.json_normalize(data)
  print(df[['name','url','private']])


import pygame
import time
import random

pygame.init()

#Colors are here, color_name = (R,G,B)
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,155,0)
#The variables to be used for game
screen_height = 600
screen_width = 800

block_size = 10
FPS = 15

font = pygame.font.SysFont(None, 25)

#Makes a new snake
def snake(snake_list):
	''' This code checks for the (x,y) coordinates in snakeList and makes new snake
	at that point. The XnY keeps getting updated, thus it will move along with head.'''
	for XnY in snake_list:
		pygame.draw.rect(gameDisplay, green, [XnY[0],XnY[1],block_size,block_size])

def message_to_screen(msg, color):
	screen_text = font.render(msg,True ,color)
	gameDisplay.blit(screen_text, [screen_width/2, screen_height/2])

#Used for frames per seconds
clock = pygame.time.Clock()

#Modifications For Screen
gameDisplay = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption('Trial')

def gameLoop():
	#A boolean for running the window till the condition is false
	gameExit = False
	gameOver = False

	lead_x = screen_width/2
	lead_y = screen_height/2

	lead_x_change = 0
	lead_y_change = 0

	snakeList = []
	snakeLength = 1

	randAppleX = random.randrange(0, screen_width-block_size,10)
	randAppleY = random.randrange(0, screen_height-block_size,10)
	#Event Handling
	while not gameExit:

		while gameOver == True:
			message_to_screen("Game Over!! \n Press C to Play Again or Q to Quit", red)
			pygame.display.update()
			for event in pygame.event.get():
				if event.type == pygame.KEYDOWN:
					if event.key == pygame.K_q:
						gameExit = True
						gameOver = False
				if event.type == pygame.KEYDOWN:
					if event.key == pygame.K_c:
						gameLoop()

		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				gameExit = True
			if event.type == pygame.KEYDOWN:
				if event.key == pygame.K_LEFT:
					lead_x_change = -block_size
					lead_y_change = 0
				elif event.key == pygame.K_RIGHT:
					lead_x_change = block_size
					lead_y_change = 0
				elif event.key == pygame.K_UP:
					lead_y_change = -block_size
					lead_x_change = 0
				elif event.key == pygame.K_DOWN:
					lead_y_change = block_size
					lead_x_change = 0

			if event.type == pygame.KEYUP:
				if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT :
					lead_x_change = 0
				if event.key == pygame.K_UP or event.key == pygame.K_DOWN :
					lead_y_change =0

		lead_x += lead_x_change
		lead_y += lead_y_change

		#Logical Code
		if lead_x > (screen_width - block_size) or lead_x < 0:
			gameOver = True

		if lead_y > (screen_height - block_size) or lead_y < 0:
			gameOver = True

	#Graphics and Rendering code
		gameDisplay.fill(white)
		pygame.draw.rect(gameDisplay, red, [randAppleX,randAppleY,block_size,block_size])

		snakeHead = []
		snakeHead.append(lead_x)#It copies the current x - coordinate
		snakeHead.append(lead_y)#Same as above but y - coordinate
		snakeList.append(snakeHead)#It appends the list each time in the loop

		#This code make sures that the list wouldn't append infinitely
		#if len(snakeList) > snakeLength:
		#	del snakeList [0]

		#for eachSegment in snakeList[:-1]:
		#	if eachSegment == snakeHead:
		#		gameOver = True

		snake(snakeList)
		pygame.display.update()

		if lead_x == randAppleX and lead_y == randAppleY:
			randAppleX = random.randrange(0, screen_width-block_size,10)
			randAppleY = random.randrange(0, screen_height-block_size,10)
			snakeLength += 1

		clock.tick(15)

	pygame.quit()
	quit()

gameLoop()


# Created by Minbiao Han and Roman Sharykin
# AI fall 2018
import heapq
from scipy.spatial import distance
def search(maze, start, end):

    ### Your code should go here ###
    h_maze = [[manhattan([i,ii], [end[0],end[1]]) for ii in range(0, len(maze[0]))] for i in range(0, len(maze))]
    closed = set()
    frindge =[  (h_maze[start[0]][start[1]], start, [start])  ]
    heapq.heapify(frindge)
    path = []
    num_nodes_expanded = 0
    while True:
        if len(frindge) == 0:
            return False
        #node = frindge.pop()
        node = heapq.heappop(frindge)
        path = node[2]
        if node[1] == end:
            #print("A* implementation: {}".format(num_nodes_expanded))
            return path, num_nodes_expanded
        if node[1] not in closed:
            i = node[1][0]
            j = node[1][1]
            #Below
            if maze[i+1][j] != "%" and (i+1, j) not in closed:
                #print("Adding node below")
                temp = path[:]
                temp.append((i+1,j))
                heapq.heappush(frindge, ( h_maze[i+1][j] + len(temp),(i+1,j), temp))
                num_nodes_expanded+=1
            #Left
            if maze[i][j-1] != "%" and (i, j-1) not in closed:
                #print("Adding node to the left")
                temp = path[:]
                temp.append((i,j-1))
                heapq.heappush(frindge, ( h_maze[i][j-1] + len(temp), (i,j-1), temp))
                num_nodes_expanded+=1
            #Right
            if maze[i][j+1] != "%" and (i, j+1) not in closed:
                #print("Adding node to the right")
                temp = path[:]
                temp.append((i,j+1))
                heapq.heappush(frindge, ( h_maze[i][j+1] + len(temp), (i,j+1), temp))
                num_nodes_expanded+=1
            #Above
            if maze[i-1][j] != "%" and (i-1, j) not in closed:
                #print("Adding node above")
                temp = path[:]
                temp.append((i-1,j))
                heapq.heappush(frindge, ( h_maze[i-1][j] + len(temp),(i-1,j), temp))
                num_nodes_expanded+=1
        closed.add(node[1])

    ### Your search function should return the
    # path for the agent to take,
    # as well as the number of nodes your algorithm searches  ###

    return path, num_nodes_expanded

### feel free to add any aditional support functions for your search here ###

def manhattan(x,y):
    val = abs(x[0] - y[0])
    val += abs(x[1] - y[1])
    return val


#!/usr/bin/env python

"""
Forms bridges between pairs of atoms that share an interaction with a residue
matched by a user-specified regex. The output is a new list contact file where
interactions to atoms matching the regex have been replaced with bridges.

For example, running this app with the regex "A:CA:.*" and the contact list:
    0       vdw     A:ASP:52:C      A:CA:201:CA
    0       vdw     A:CA:201:CA     A:GLN:53:N
    0       vdw     A:ASP:52:N      A:PHE:48:O
will output the contact list
    0       br      A:ASP:52:C      A:GLN:53:N
    0       vdw     A:ASP:52:N      A:PHE:48:O
"""

from collections import defaultdict
import re
from itertools import combinations

from contact_calc.transformations import parse_contacts

def main(argv=None):
    # Parse command line arguments
    import argparse as ap
    parser = ap.ArgumentParser(description=__doc__, formatter_class=ap.RawTextHelpFormatter)
    optional = parser._action_groups.pop()
    required = parser.add_argument_group('required arguments')
    parser._action_groups.append(optional)  # added this line

    required.add_argument('--input',
                          required=True,
                          type=ap.FileType('r'),
                          metavar='FILE',
                          help='A contact-file generated by get_dynamic_contacts.py or get_static_contacts.py')
    required.add_argument('--bridge',
                          required=True,
                          type=str,
                          metavar='REGEX',
                          help='Regular expression matching any atom to be included as a bridge')
    required.add_argument('--bridges_only',
                          required=False,
                          type=bool,
                          metavar='BOOL',
                          default=False,
                          help='Indicates whether to output non-bridged interactions as well as the bridges')
    required.add_argument('--output',
                          required=False,
                          metavar='FILE',
                          type=ap.FileType('w'),
                          help='The name of the output contact-file')

    args = parser.parse_args(argv)
    contacts, total_frames = parse_contacts(args.input)
    bridges_only = args.bridges_only

    # Build the bridge_neighbor datastructure which for each frame has a dictionary mapping bridging-residues to
    # non-bridging neighbors. Also collects contacts in `bridged_contacts` that are not part of any bridges unless
    # `bridges_only` has been enabled
    bridge_neighbors = [defaultdict(list) for _ in range(total_frames)]
    bridge_pattern = re.compile(args.bridge)
    bridged_contacts = []
    for contact in contacts:
        frame = contact[0]
        a1_match = bridge_pattern.match(contact[2])
        a2_match = bridge_pattern.match(contact[3])
        if a1_match and not a2_match:
            a1_res = ":".join(contact[2].split(":")[0:3])
            bridge_neighbors[frame][a1_res].append(contact[3])
        elif a2_match:
            a2_res = ":".join(contact[3].split(":")[0:3])
            bridge_neighbors[frame][a2_res].append(contact[2])
        elif not bridges_only:
            bridged_contacts.append(contact)

    # Based on the neighbor-lists in `bridge_neighbors`, add atom pairs to `bridged_contacts`
    for frame, bridge_map in enumerate(bridge_neighbors):
        for bridge_res in bridge_map:
            for a1, a2 in combinations(bridge_map[bridge_res], 2):
                bridged_contacts.append([frame, 'br', a1, a2, bridge_res])

    # Sort the contacts and convert them to strings
    from operator import itemgetter
    bridged_contacts.sort(key=itemgetter(0))
    for contact in bridged_contacts:
        contact[0] = str(contact[0])
    bridged_contacts = ["\t".join(contact) for contact in bridged_contacts]

    # Write to output
    if args.output:
        args.output.write("# total_frames:%d\n" % total_frames)
        args.output.write("\n".join(bridged_contacts))
        args.output.close()
        print("Wrote residue contact file to " + args.output.name)
    else:
        print("\n".join(bridged_contacts))

if __name__ == "__main__":
    main()

__license__ = "Apache License 2.0"
__maintainer__ = "Rasmus Fonseca"
__email__ = "fonseca.rasmus@gmail.com"