#!/bin/env python3

import os
import sys

samps = os.getcwd().split("/")[-1]

NT_positions = []
asdflas = [
    '100',
    '178',
    '241',
    '335',
    '378',
    '632',
    '647',
    '686',
    '687',
    '689',
    '691',
    '692',
    '2269',
    '2470',
    '2832',
    '3037',
    '3745',
    '3967',
    '4181',
    '4184',
    '5386',
    '5648',
    '5779',
    '6080',
    '6120',
    '6135',
    '6441',
    '6513',
    '6514',
    '6515',
    '7977',
    '8140',
    '8393',
    '8739',
    '9204',
    '9344',
    '9707',
    '9711',
    '9751',
    '9992',
    '9994',
    '10029',
    '10030',
    '10039',
    '11081',
    '11279',
    '11283',
    '11284',
    '11285',
    '11286',
    '11287',
    '11288',
    '11289',
    '11290',
    '11291',
    '11537',
    '11947',
    '11950',
    '11956',
    '11960',
    '11963',
    '13195',
    '13647',
    '13729',
    '13730',
    '13731',
    '13732',
    '13827',
    '13828',
    '13829',
    '13830',
    '13831',
    '13832',
    '13833',
    '13834',
    '13835',
    '13836',
    '13837',
    '13838',
    '13839',
    '13840',
    '13928',
    '13929',
    '13930',
    '14201',
    '14320',
    '14408',
    '14409',
    '14410',
    '14411',
    '14412',
    '14413',
    '14414',
    '14415',
    '14416',
    '14419',
    '14420',
    '14543',
    '14541',
    '14542',
    '14543',
    '14544',
    '14545',
    '15414',
    '15424',
    '15240',
    '15474',
    '15490',
    '15735',
    '15907',
    '15956',
    '17051',
    '17054',
    '18105',
    '18163',
    '18421',
    '19080',
    '19684',
    '19955',
    '20055',
    '20393',
    '20407',
    '21255',
    '21595',
    '21603',
    '21762',
    '21765',
    '21766',
    '21767',
    '21768',
    '21769',
    '21770',
    '21846',
    '21789',
    '21846',
    '21987',
    '21988',
    '21989',
    '21990',
    '21991',
    '21992',
    '21993',
    '21994',
    '21995',
    '22194',
    '22195',
    '22196',
    '22012',
    '22069',
    '22070',
    '22079',
    '22081',
    '22083',
    '22104',
    '22194',
    '22195',
    '22196',
    '22449',
    '22566',
    '22578',
    '22661',
    '22673',
    '22682',
    '22685',
    '22686',
    '22690',
    '22691',
    '22692',
    '22713',
    '22813',
    '22882',
    '22884',
    '22896',
    '22898',
    '22907',
    '22942',
    '22992',
    '22995',
    '23010',
    '23012',
    '23013',
    '23018',
    '23019',
    '23039',
    '23040',
    '23048',
    '23055',
    '23063',
    '23075',
    '23140',
    '23141',
    '23142',
    '23179',
    '23180',
    '23184',
    '23188',
    '23200',
    '23202',
    '23212',
    '23219',
    '23237',
    '23403',
    '23481',
    '23483',
    '23525',
    '23599',
    '23604',
    '23854',
    '23948',
    '24130',
    '24153',
    '24380',
    '24424',
    '24469',
    '24480',
    '24503',
    '25000',
    '25020',
    '25584',
    '25708',
    '26111',
    '26182',
    '26183',
    '26270',
    '26527',
    '26530',
    '26538',
    '26577',
    '26590',
    '26709',
    '27259',
    '27476',
    '27807',
    '28085',
    '28311',
    '28362',
    '28363',
    '28364',
    '28365',
    '28366',
    '28367',
    '28368',
    '28369',
    '28370',
    '28472',
    '28881',
    '28882',
    '28883',
    '29249',
    '29332',
    '29510'
]
NTcall_variants = [] # ['C241CandC3037TandC14408CandA23403G'] # [] # ['C24044T'] # ['C1059TandC3543TandC7635GandA18982GandA23013CandA23056CandC23117AandT23119CandA23403GandG23576TandC23604AandC26060T'] # ['C241TandC14408CandA17496CandA22893CandA23013CandA23056CandA23403GandA25020CandA27330CandA28271TandA4178CandA5648CandA6328GandA9204GandC1059TandC11916TandC1616AandC23029TandC23039AandC23054TandC23117AandC23277AandC24044TandC24418TandC25936GandC27920TandC28887TandC3037TandC3267TandC4113TandC4230TandC5178AandC9711TandG11670AandG17196AandG22340AandG22599AandG25019AandG25116AandG25563TandG25947CandG29540AandG3849TandG9479TandT18660CandT22907CandT23031AandT23406CandT25570AandT27322CandT27384CandT27907GandT27929AandT5507GandT8296CandT9982C']
NT_multi_variants = [] # ['C241CandC3037TandC14408CandA23403GandG25563T']
AA_variants = [] #["E484del"] # "Q498Y", "Q498H", ["A1250C(K417T) A1331C(K444T) T1334C(V445A) T1345C(Y449H) T1355G(L452R) T1380G(N460K) A1451C(E484A) TTT1456-1458CCT(F486P) T1480G(S494A) CAA1492-1494TAT(Q498Y) C1495T(P499S) A1498T(T500S) A1502C(N501T) T1513C(Y505H)"] #['CTACAAGTT14408-14416del'] # ['Reference'] # ['L452Q'] # ['GCTA13729-13732Del'] # ["K417"and"N440K"and"G446S"and"L452R"and"S477N"and"N460K"and"K444"and"Q493"and"E484"and"Q498"and"1450-1452Del"and"N501Y"and"Y505H"] # [] # ['L828F'] #    ['K444E'and'D574E'] #
multi_var = ["T478KandnotS477N"] # ['N440EandL441RandK444delandK444SandK444TandV445delandV445AandV445NandG446delandG446DandY449HandY449RandY449SandL452KandY453FandL455WandF456LandN460KandT470NandT478RandV483AandV483delandE484delandE484PandF486AandF486PandF486VandF490HandF490PandF490YandQ493KandnotQ493RandQ493YandQ498HandQ498KandQ498YandQ498KandnotQ489RandP499HandP499SandN501SandN501TandY505NandY508HandH519NandT572IandT572N'] #  ["K417TandK444TandV445AandY449HandL452RandN460KandE484AandF486PandS494AandQ498YandP499SandT500SandN501TandY505H"] # ['K444TandY449RandN460KandE484AandF486PandQ493KandQ493RandQ498HandQ498YandN501SandN501TandY505H'] # ['440Eand441Rand444Sand445Nand446Dand449Hand449Rand449Sand452Qand452Kand453Fand455Wand456Land484Qand484Pand484Vand486Aand486Pand486Vand490Hand490Pand490Yand494Pand498Hand498Yand498Kand505Nand572I'] # ['K444TandV445AandY449andL452QandN460KandE484PandF486PandF490YandQ493KandQ498HandQ498YandN501SandN501T']
Omis = {"1" : {'NTD' : ["A67V", "T95I", "425-433Del", "632-634Del", "215EPE"], 'RBD' : ["1251T(K417N)", "1320G(N440K)", "1336A(G446S)", "1430A(S477N)", "1433A(T478K)", "1451C(E484A)", "1478G(Q493R)", "1486A(G496S)", "1493G(Q498R)", "1501T(N501Y)", "1513C(Y505H)", "1640A(T547K)"]},
        "2" : {'NTD' : ["not A67V", "not T95I", "G142D", "not 425-433Del", "not 632-634Del", "V213G"], 'RBD' : ["1251T(K417N)", "1320G(N440K)", "not G446", "1430A(S477N)", "1433A(T478K)", "1451C(E484A)", "1478G(Q493R)", "not G496", "1493G(Q498R)", "1501T(N501Y)", "1513C(Y505H)", "not T547"]},
        "3" : {'NTD' : ["A67V", "T95I", "425-433Del", "632-634Del", "not 215EPE"], 'RBD' : ["1251T(K417N)", "1320G(N440K)", "1336A(G446S)", "1430A(S477N)", "1433A(T478K)", "1451C(E484A)", "1478G(Q493R)", "not G496", "1493G(Q498R)", "1501T(N501Y)", "1513C(Y505H)", "not T547"]}}
Search_Omis = 0
search_ref = 0
Omi_matches = {}
NT_outfiles = {}
NT_mult_outfiles = {}
AA_outfiles = {}
multivar_fhs = {}
nt_call_dict = {}
NT_SRAs = {}
NT_Sample_dict = {}
NT_mult_Sample_dict = {}
Ref_Sample_dict = {}
POS_Sample_dict = {}
ref_NT_dict = {}

if NTcall_variants:
    i = 2
    for variant in NTcall_variants:
        NT_Sample_dict[variant] = {}
        Ref_Sample_dict[variant] = {}
        NT_outfiles[variant] = open(samps+"_NT_"+str(i)+".tsv","w")
        i += 1
if NT_multi_variants:
    for variant in NT_multi_variants:
        NT_mult_Sample_dict[variant] = {}
        NT_mult_outfiles[variant] = open(samps+"_NTmult_"+variant+".tsv","w")

if AA_variants:
    for variant in AA_variants:
        AA_outfiles[variant] = open(samps+"_AA_"+variant+".tsv","w")
if multi_var:
    i = 1
    for variant in multi_var:
        multivar_fhs[variant] = open(samps+"_multi"+str(i)+".tsv","w")
        multivar_fhs[variant].write(variant)
        multivar_fhs[variant].write("\n")
        i += 1
if search_ref == 1:
    ref_fh = open(samps+'_refs.tsv', 'w')
files_read = []

testcounter = 0
for subdir, dirs, files in os.walk(os.getcwd()):
    for file in files:
        if not file in files_read and not 'Assemblies' in subdir:
            files_read.append(file)
            if (file.endswith('_unique_seqs.tsv')) and (AA_variants or multi_var or NT_multi_variants) and not '_AA_' in file: # and not 'wgs' in file:  or file.endswith('_reads.tsv') or file.endswith('_covars.tsv')
                in_file = open(os.path.join(subdir, file), "r")
                NT_multi_matches = {}
                AA_matches = {}
                mv_matches = {}
                counts = 0
                ft = 0
                if file.endswith('_reads.tsv'):
                    ft = 1

                for line in in_file:
                    splitline = line.split("\t")
                    try:
                        splitline[1]
                    except:
                        pass
                    else:
                        if not splitline[1] == "Count":
                            if NT_multi_variants:
                                for variant in NT_multi_variants:
                                    mismatch = 0
                                    first = variant.split('and')[0][1:-1]
                                    try:
                                        if int(splitline[ft].split(' ')[0]) > int(first):
                                            continue
                                    except:
                                        pass

                                    for PM in variant.split('and'):
                                        if 'not' in PM:
                                            curPM = PM.strip('not')
                                            if curPM[0] == curPM[-1]:
                                                if PM[:-1] in splitline[ft]:
                                                    # for nt in ['A', 'T', 'C', 'G', 'N', '-']:
                                                        # if PM[:-1]+nt in splitline[0]:
                                                    mismatch += 1
                                            elif curPM in splitline[ft]:
                                                mismatch += 1
                                        elif PM[0] == PM[-1]:
                                            if PM[:-1] in splitline[ft]:
                                                # for nt in ['A', 'T', 'C', 'G', 'N', '-']:
                                                    # if PM[:-1]+nt in splitline[0]:
                                                mismatch += 1
                                        elif not PM in splitline[ft]:
                                            mismatch += 1
                                    if mismatch == 0:
                                        try:
                                            NT_multi_matches[variant].append(line) # str(mismatch) + "\t" + line)
                                            # counts += int(splitline[1])
                                        except:
                                            NT_multi_matches[variant] = [line]
                            if ft == 1 or (int(splitline[1]) >= 4):
                                if multi_var:
                                    for variant in multi_var:
                                        mismatch = 0
                                        match = 0
                                        for PM in variant.split('and'):
                                            if 'not' in PM:
                                                if PM.strip('not') in splitline[ft]:
                                                    mismatch += 1
                                            else:
                                                if PM in splitline[ft]:
                                                    match += 1

                                        if ((match - mismatch) > 0) and len(splitline[ft].split(" ")) < 25 and splitline[ft].count("insert") < 3 and splitline[ft].count("Del") < 4:
                                            try:
                                                mv_matches[variant].append(line)
                                            except:
                                                mv_matches[variant] = [line]
                            if AA_variants:
                                if (int(splitline[1]) > 0 or ft == 1):
                                    for variant in AA_variants:
                                        if variant in splitline[ft]:
                                            try:
                                                AA_matches[variant].append(line)
                                            except:
                                                AA_matches[variant] = [line]

                if NT_multi_matches:
                    for variant in NT_multi_matches:
                        NT_mult_outfiles[variant].write(file[:-4]+"\t")
                        NT_mult_outfiles[variant].write("\n")
                        for line in NT_multi_matches[variant]:
                            NT_mult_outfiles[variant].write(line)
                if mv_matches:
                    for variant in mv_matches:
                        multivar_fhs[variant].write(subdir+"/"+file[:-4]+"\t")
                        multivar_fhs[variant].write("\n")
                        for line in mv_matches[variant]:
                            multivar_fhs[variant].write(line)
                if AA_matches:
                    for variant in AA_matches:
                        if AA_matches[variant]:
                            AA_outfiles[variant].write(subdir+"/"+file+"\n")
                            for line in AA_matches[variant]:
                                AA_outfiles[variant].write(line)

                in_file.close()

            if file.endswith("_nt_calls.tsv") and (NTcall_variants or NT_positions):
                in_file = open(os.path.join(subdir, file), "r")
                match_lines = {}
                match_dict = {}
                ref_dict = {}
                for line in in_file:
                    splitline = line.split("\t")
                    try:
                        splitline[1]
                    except:
                        pass
                    else:
                        if splitline[0] == 'Position':
                            PosLine = line
                            for i in range(0, len(splitline)):
                                nt_call_dict[splitline[i]] = i
                        if NT_positions:
                            if splitline[0] in NT_positions:
                                try:
                                    POS_Sample_dict[file.split('_nt_calls')[0]][splitline[0]] = (int(splitline[int(nt_call_dict[splitline[1]])]) / int(splitline[int(nt_call_dict['Total'])]))
                                except:
                                    POS_Sample_dict[file.split('_nt_calls')[0]] = { splitline[0] : (int(splitline[int(nt_call_dict[splitline[1]])]) / int(splitline[int(nt_call_dict['Total'])]))}
                                try:
                                    ref_NT_dict[splitline[0]]
                                except:
                                    ref_NT_dict[splitline[0]] = splitline[1]

                        if NTcall_variants:
                            for var in NTcall_variants:
                                try:
                                    match_lines[var]
                                except:
                                    match_lines[var] = []
                                # if 'and' in var:
                                varPMs = var.split("and")
                                for subvar in varPMs:
                                    if subvar[1:-1] == splitline[0]:
                                        if int(splitline[int(nt_call_dict['Total'])]) > 50 and (int(splitline[int(nt_call_dict[subvar[-1]])]) > (.2 * int(splitline[int(nt_call_dict['Total'])]))):
                                            match_lines[var].append(line)
                                            try:
                                                match_dict[var][subvar] = (int(splitline[int(nt_call_dict[subvar[-1]])]) / int(splitline[int(nt_call_dict['Total'])]))
                                            except:
                                                match_dict[var] = { subvar : (int(splitline[int(nt_call_dict[subvar[-1]])]) / int(splitline[int(nt_call_dict['Total'])])) }
                                            try:
                                                ref_dict[var][subvar] = (int(splitline[int(nt_call_dict[subvar[0]])]) / int(splitline[int(nt_call_dict['Total'])]))
                                            except:
                                                ref_dict[var] = { subvar : (int(splitline[int(nt_call_dict[subvar[0]])]) / int(splitline[int(nt_call_dict['Total'])])) }
                            # elif var[1:-1] == splitline[0]:
                                # if int(splitline[int(nt_call_dict['Total'])]): # > 50 and (int(splitline[int(nt_call_dict[subvar[-1]])]) > (.01 * int(splitline[int(nt_call_dict['Total'])]))):
                                    # match_lines[var].append(line)

                if match_lines:

                    for variant in match_lines:
                        if len(match_lines[variant]) == len(variant.split('and')):
                            try:
                                NT_Sample_dict[variant][file.split('.')[0]] = match_dict[variant]
                                Ref_Sample_dict[variant][file.split('.')[0]] = ref_dict[variant]
                                NT_outfiles[variant].write(file.split('.')[0]+"\n")
                                NT_outfiles[variant].write("\t".join(PosLine.split("\t")[:int(nt_call_dict['Total'])+1])+"\tVarient\tAbundance\n")
                                for line in match_lines[variant]:
                                    splitline= line.split("\t")
                                    NT_outfiles[variant].write("\t".join(splitline[:int(nt_call_dict['Total'])+1]))
                                    for subvar in var.split("and"):
                                        if subvar[1:-1] == splitline[0]:
                                            NT_outfiles[variant].write(f"\t{subvar}\t{match_dict[variant][subvar]}")
                                    NT_outfiles[variant].write("\n")
                                try:
                                    NT_SRAs[variant].append(file.split('.')[0])
                                except:
                                    NT_SRAs[variant] = [(file.split('.')[0])]
                            except:
                                pass

                in_file.close()

            if file.endswith("_chim_rm.tsv") or file.endswith("_covar_deconv.tsv"):
                if Search_Omis == 1 or search_ref == 1:
                    samp_name = ""
                    if file.endswith("_covar_deconv.tsv"):
                        samp_name = file.strip("_covar_deconv.tsv")
                    else:
                        samp_name = "_".join(file.split("_")[:-3])
                    ref_lines = []
                    amp = ''
                    if 'NTD' in file:
                        amp = 'NTD'
                    elif 'S1S2' in file:
                        amp = 'S1S2'
                    elif 'RBD' in file:
                        amp = 'RBD'
                    if amp:
                        in_file = open(os.path.join(subdir, file), "r")
                        counts = {'1' : [0 ,0 ,0],
                                  '2' : [0 ,0 ,0],
                                  '3' : [0 ,0 ,0]} # counts['2'][1] == abundance of seq that had 1 mismatches to BA.2
                        matched = 0
                        for line in in_file:
                            splitline = line.strip("\n\r").split("\t")
                            try:
                                splitline[2]
                            except:
                                pass
                            else:
                                if not splitline[1] == "Count":
                                    split_seq = splitline[0].split(' ')
                                    if Search_Omis == 1:
                                        if not amp == 'S1S2':
                                            for sub in Omis:
                                                mismatches = 0
                                                for PM in Omis[sub][amp]:
                                                    if 'not' in PM:
                                                        if PM.split(' ')[1] in splitline[0]:
                                                            mismatches += 1
                                                    elif not PM in splitline[0]:
                                                        mismatches += 1
                                                if mismatches < 3:
                                                    matched = 1
                                                    counts[sub][mismatches] += float(splitline[2])
                                                    # print(splitline[0] + "\t" + sub + "\t" + str(mismatches) + "\t" + splitline[2])
                                                    # print(counts[sub][mismatches])
                                    if search_ref == 1:
                                        # if float(splitline[2]) >= .01: # and not '/NY/' in subdir:
                                        if amp == 'S1S2' and '1841G(D614G)' == splitline[0]:
                                            ref_lines.append(line)
                                        elif 'Reference' == splitline[0]:
                                            ref_lines.append(line)
                    if ref_lines:
                        ref_fh.write(os.path.join(subdir, file)+"\n")
                        for line in ref_lines:
                            ref_fh.write(line)
                        ref_fh.write("\n")

                            # print(counts)
                        if matched == 1:
                            try:
                                Omi_matches[samp_name]
                            except:
                                Omi_matches[samp_name] = counts
                            else:
                                for subvar in Omi_matches[samp_name]:
                                    for i in range(0, 3):
                                        Omi_matches[samp_name][subvar][i] += counts[subvar][i]

                    in_file.close()

if search_ref == 1:
    ref_fh.close()

if multi_var:
    for variant in multivar_fhs:
        multivar_fhs[variant].close()
if NT_mult_outfiles:
    for variant in NT_mult_outfiles:
        NT_mult_outfiles[variant].close()
if NTcall_variants:
    for variant in NTcall_variants:
        NT_outfiles[variant].close()
if AA_variants:
    for variant in AA_variants:
        AA_outfiles[variant].close()
if NT_SRAs:
    for variant in NT_SRAs:
        print(variant + ' ' + str(len(NT_SRAs[variant])))
        # for SRA in NT_SRAs[variant]:
            # print(SRA)

if POS_Sample_dict:
    fh_POS_table = open(samps + "_RefNTtable.tsv", 'w')
    fh_POS_table.write(f"Position")
    for sample in POS_Sample_dict:
        fh_POS_table.write(f"\t{sample}")
    fh_POS_table.write(f"\n")
    for position in NT_positions:
        fh_POS_table.write(ref_NT_dict[position]+position)
        for sample in POS_Sample_dict:
            try:
                fh_POS_table.write(f"\t{POS_Sample_dict[sample][position]:04f}")
            except:
                fh_POS_table.write(f"\t")
        fh_POS_table.write(f"\n")

    fh_POS_table.close()

if NT_Sample_dict:
    i = 2
    for variant in NT_Sample_dict:
        fh_NT_table = open(samps + "_" + str(i) + "_NTtable.tsv", 'w')
        i += 1
        fh_NT_table.write(f"mut")
        for sample in NT_Sample_dict[variant]:
            fh_NT_table.write(f"\t{sample}")
        fh_NT_table.write(f"\n")
        for subvar in variant.split("and"):
            fh_NT_table.write(subvar)
            for sample in NT_Sample_dict[variant]:
                try:
                    fh_NT_table.write(f"\t{NT_Sample_dict[variant][sample][subvar]:04f}")
                except:
                    fh_NT_table.write(f"\t")
            fh_NT_table.write(f"\n")

        fh_NT_table.close()

if Ref_Sample_dict:
    i = 2
    for variant in Ref_Sample_dict:
        fh_Ref_table = open(samps + "_" + str(i) + "_Reftable.tsv", 'w')
        i += 1
        fh_Ref_table.write(f"mut")
        for sample in Ref_Sample_dict[variant]:
            fh_Ref_table.write(f"\t{sample}")
        fh_Ref_table.write(f"\n")
        for subvar in variant.split("and"):
            fh_Ref_table.write(subvar[:-1]+subvar[0])
            for sample in Ref_Sample_dict[variant]:
                try:
                    fh_Ref_table.write(f"\t{Ref_Sample_dict[variant][sample][subvar]:04f}")
                except:
                    fh_Ref_table.write(f"\t")
            fh_Ref_table.write(f"\n")

        fh_Ref_table.close()

if Omi_matches:
    Omi_out_fh = open(samps+"_Omis.tsv","w")
    sorted_samps = sorted(Omi_matches.keys())
    for subvar in Omis:
        for domain in Omis[subvar]:
            Omi_out_fh.write(f"BA.{subvar}\t{domain}\t{', '.join(Omis[subvar][domain])}")
            Omi_out_fh.write("\n")
    Omi_out_fh.write("\n")
    # Omi_out_fh.write(f"\t\t[Perfect match, 1 mismatch, 2 mismatch]")
    for key in sorted_samps:
        Omi_out_fh.write(key+ "\t\tPerfect match\t1 mismatch\t2 mismatch\n")
        for subvar in Omi_matches[key]:
            Omi_out_fh.write(f"\tBA.{subvar}")
            for val in Omi_matches[key][subvar]:
                Omi_out_fh.write(f"\t{val}")
            Omi_out_fh.write("\n")
        Omi_out_fh.write("\n")
    Omi_out_fh.close()


import sys

N = int(input())

min_value = sys.maxsize
min_index = 0

num_list = list(map(int,input().split()))
num_list.sort()

max_value = sys.maxsize
max_index = max(num_list)

check_list= []

left = 0
right = N

while left <= right:
    check = 0
    middle = (left+right)//2
    for i in num_list:
        check += abs(i-num_list[middle])

    if check <= max_value:
        max_value = check
        max_index = min(max_index,num_list[middle])
        right = middle-1
    else:
        left = middle+1
print(max_index)


# -*-coding:utf-8-*-
from selenium.webdriver.chrome.options import Options
from lianxi2 import BaseOperator
from selenium import webdriver
import time
from selenium.webdriver.common.action_chains import ActionChains

class lianxi:
    def __init__(self):
        chrome_options=Options()
        chrome_options.add_argument('--headless')
        chrome_options.add_argument('--no-sandbox')
        self.driver=webdriver.Chrome(chrome_options=chrome_options)
        self.driver.get("https://arcb.com/tools/rate-quote.html#/new")
        self.zentao=BaseOperator(self.driver)
        self.loc1=("xpath", "//div[4]/div/div[1]/abt-party/div/div[2]/div[1]/abt-city-coding-input//input")
        self.loc3=("xpath", "//ul[@role='listbox']/li")
        self.loc=""

    def open_file(self):
        f=open("Untitled-1.txt", "r")
        list_f=eval(str((f.readlines())).replace("\\n", ""))
        return list_f

    #
    # def for_list_f(self):
    #     for n in self.open_file():
    #         self.zentao.sendKeys(self.loc1, str(n))
    #         return len(self.zentao.findElements(self.loc3))

    def len_list_f(self):
        return self.zentao.get_att(self.loc1, "value")

    def test01(self):
        time.sleep(20)
        for n in self.open_file():
            print(n)
            self.zentao.sendKeys(self.loc1, str(n))
            time.sleep(2)
            if str.isdigit(self.zentao.get_att(self.loc1, "value")):
                for i in range(1, len(self.zentao.findElements(self.loc3)) + 1):
                    loc2=("xpath", '//ul[@role="listbox"]/li[{num}]'.format(num=i))
                    self.zentao.ActionChains_move(loc2)
                    with open("a.txt", "a") as f:
                        f.write(self.zentao.get_ele_text(loc2) + "\n")
                        f.close()
                    print(str(self.open_file().index(n) + 1))
                    print(str(self.open_file().index(n) + 1) + "---------" + self.zentao.get_ele_text(loc2))
                self.zentao.clear(self.loc1)
            else:
                with open("a.txt", "a") as f:
                    f.write(self.zentao.get_att(self.loc1, "value") + "\n")
                    f.close()
                    print(str(self.open_file().index(n) + 1))
                    print(str(self.open_file().index(n) + 1) + "---------" + self.zentao.get_att(self.loc1, "value"))
                    self.zentao.clear(self.loc1)
                    pass

if __name__ == '__main__':
    print(lianxi().test01())


import argparse
import sys

from post_timestamp_app_poc.commands.deploy import Deploy
from post_timestamp_app_poc.commands.destroy import Destroy
from post_timestamp_app_poc.commands.post import Post

class CLI:
    """Coordinating class to run the CLI
    """
    def __init__(self, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr):
        """Initialiser

        Keyword Args:
            stdin (file): file IO object to use for stdin when running commands. (Default sys.stdin)
            stdout (file): file IO object to use for stdout when running commands. (Default sys.stdout)
            stderr (file): file IO object to use for stderr when running commands. (Default sys.stderr)
        """
        self.stdin = stdin
        self.stdout = stdout
        self.stderr = stderr

    def run(self, args=sys.argv[1:]):
        """Execute the cli action

        Keyword Args:
            args (list): List of strings to parse for arguments (Default sys.argv[1:])

        Returns:
            None
        """
        parser = argparse.ArgumentParser(description="Timestamp POST proof of concept by Jonathan Harden")
        subparsers = parser.add_subparsers(dest="command_name", required=True)

        self.__setup_deploy_parser(subparsers)
        self.__setup_destroy_parser(subparsers)
        self.__setup_post_parser(subparsers)

        parsed_args = parser.parse_args(args)

        if parsed_args.command_name == "deploy":
            self.__deploy(parsed_args)
        elif parsed_args.command_name == "destroy":
            self.__destroy(parsed_args)
        elif parsed_args.command_name == "post":
            self.__post(parsed_args)

    def __setup_deploy_parser(self, subparsers):
        deploy_parser = subparsers.add_parser(
            "deploy", description="Deploy the solution into AWS. Will run terraform apply"
        )
        deploy_parser.add_argument(
            "-n", "--app-name",
            default="jfharden-poc",
            help="Name to use for most resources (for some it will be used as a prefix separated with a '-'",
        )
        deploy_parser.add_argument(
            "-r", "--resource-group-tag-name",
            default="project",
            help="Name of a tag (value will be APP_NAME) to add to all resources to allow for grouping",
        )
        deploy_parser.add_argument(
            "--region",
            default="eu-west-2",
            help="AWS region to deploy into (default eu-west-2).",
        )

    def __setup_destroy_parser(self, subparsers):
        destroy_parser = subparsers.add_parser(
            "destroy", description="Destroy the solution in AWS (will run terraform destroy)"
        )
        destroy_parser.add_argument(
            "--region",
            default="eu-west-2",
            help="AWS region to destroy in (default eu-west-2).",
        )

    def __setup_post_parser(self, subparsers):
        post_parser = subparsers.add_parser(
            "post", description="Perform a POST request to the deployed solution"
        )
        post_parser.add_argument(
            "-e", "--endpoint",
            dest="endpoint",
            help="Endpoint URL to POST to. If not provided will be read from the terraform state file",
        )

    def __deploy(self, parsed_args):
        deploy_command = Deploy(self.stdin, self.stdout, self.stderr)
        deploy_command.execute(parsed_args.app_name, parsed_args.resource_group_tag_name, parsed_args.region)

    def __destroy(self, parsed_args):
        destroy_command = Destroy(self.stdin, self.stdout, self.stderr)
        destroy_command.execute(parsed_args.region)

    def __post(self, parsed_args):
        post_command = Post(self.stdin, self.stdout, self.stderr)
        post_command.execute(parsed_args.endpoint)


#!/usr/bin/env python
# coding=UTF-8
import sys
import os
import time
import reportlab
import StringIO

from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfgen.canvas import Canvas

#import reportlab
from reportlab.pdfgen import canvas
##from pdfmetrics import standardEncodings
#
from reportlab.pdfbase import pdfmetrics

from reportlab.lib.pagesizes import letter
from reportlab.lib.pagesizes import A4

from datetime import datetime
from datetime import timedelta

class Invoice( object ):
    canvas = None
    invoice = None
    size = (0,0)
    col = 80
    row = 600
    default_font = ( 'Helvetica', 10 )

    def __init__( self, invoice, output, size=A4 ):
        self.canvas = canvas.Canvas(output, pagesize=size)
        self.invoice = invoice
        self.size = size

    def save( self ):
        self.getHeader()
        self.getBillingLines()
        self.getFooter()

        return self.canvas.save()

    def getBillingLines( self ):
        font, size = self.default_font
        self.canvas.setFont(font, size)
        cost, total = 0, 0

        self.setRow(365)

        for line in self.invoice.billing_introduction().splitlines():
            self.canvas.drawString(self.getCol(), self.getRow(), line );
            self.nextRow()

        self.nextRow()
        self.nextRow()

        for line in self.invoice.invoice_lines():
            #dot = unicode('•')
            total = total + line.amount
            self.canvas.drawString( 435, self.getRow(), "€%s" % str.rjust("%0.2f" % line.amount,17) )
            self.canvas.drawString( self.getCol(), self.getRow(), "%s" % line.name )
            self.nextRow()

        self.canvas.line(435,self.getRow(),505,self.getRow())
        self.canvas.drawString(self.getCol(), self.nextRow(), "Subtotaal")
        self.canvas.drawString(435, self.getRow(),
                                        "€%s" % str.rjust("%0.2f" % total,17) )

        self.canvas.drawString(self.getCol(), self.nextRow(),
                                        "%0.2f%% BTW" % (self.invoice.get_vat() * 100))
        self.canvas.drawString(435, self.getRow(),
                        "€%s" % str.rjust("%0.2f" % (total*self.invoice.get_vat()),17))

        total = total + (total*self.invoice.get_vat())

        self.nextRow(10)
        self.canvas.line(435,self.getRow(),505,self.getRow())
        self.nextRow(20)

        self.canvas.setFont( 'Helvetica-Bold', 10 )
        self.canvas.drawString(self.getCol(), self.getRow(), "Totaal" )
        self.canvas.drawString(435, self.getRow(),
                                            "€%s" % str.rjust("%0.2f" % total,17))

    def getHeader( self ):
        r,g,b = (0.4, 0.7, 0.3)
        width, height = self.size
        font, size = self.default_font

        if self.invoice.company.logo:
            image = canvas.ImageReader(StringIO.StringIO(self.invoice.company.logo))
            self.canvas.drawImage( image, 435, height-180, 130, 165 )

        self.canvas.setFont( '%s-Bold' % font, 16 )
        self.canvas.drawString( 435, height - 265, 'Factuur' )

        self.canvas.setFont( font, size )

        self.setCol(80)
        self.setRow(140)

        customer = self.invoice.customer

        self.canvas.drawString(self.getCol(), self.getRow(),
            "%s %s" % (customer.firstname, customer.surname) );

        self.nextRow()

        address = customer.address.splitlines()
        for line in address:
            self.canvas.drawString( self.getCol(), self.getRow(), line.strip() );
            self.nextRow()

        # plaats, datum
        self.setRow(260)

        self.canvas.setFillColorRGB(r,g,b);

        self.canvas.drawString( self.getCol(), self.getRow(), "plaats, datum" )
        self.canvas.drawString( self.getCol()+200, self.getRow(), "factuur nummer" )

        self.nextRow()
        self.canvas.setFillColorRGB(0,0,0);

        billed = datetime.now()

        if self.invoice.billed:
            billed = self.invoice.billed

        self.canvas.drawString( self.getCol(), self.getRow(),
            "%s, %s" % (self.invoice.company.city, billed.strftime('%e %B %Y')) )

        self.canvas.drawString( self.getCol()+200, self.getRow(), "%s" % self.invoice.billing_number() )

        self.nextRow()
        self.nextRow()
        self.canvas.setFillColorRGB(r,g,b);
        self.canvas.drawString( self.getCol(), self.getRow(), "betreft" )
        self.nextRow()
        self.canvas.setFillColorRGB(0,0,0);
        self.canvas.drawString( self.getCol(), self.getRow(), self.invoice.description )

        #
        #self.canvas.drawString(self.getCol(), self.getRow(),
        #        "%s, %s" % ( self.invoice.company.city, self.invoice.billing_date(format)) )
        #

    def getBillingDate(self, format="%e %B %Y"):
        self.canvas.drawString(self.getCol(), self.getRow(),
                "%s, %s" % ( self.invoice.company.city, self.invoice.billing_date(format)) )

        self.canvas.drawString(self.getCol(), self.getRow(),
                "F-%s" % "HOEPLA" )

        #self.canvas.drawString(self.getCol()+200, self.getRow(),
        #                    "F-%s" % self.invoice.billing_number() )

        self.nextRow()
        self.nextRow()

        self.canvas.setFillColorRGB(r,g,b);
        self.canvas.drawString(self.getCol(), self.getRow(), "betreft" )

        self.nextRow()
        self.canvas.setFillColorRGB(0,0,0);
        self.canvas.drawString(self.getCol(), self.getRow(), "Hosting" )

        self.nextRow(45)

    def getFooter( self ):
        #w, height = self.size
        self.canvas.setFont( 'Helvetica-Bold', 9 )
        self.setRow( 780 )
        self.setCol( 80 )

        lines = self.invoice.company.footer.splitlines() #str.split( self.invoice.footer, "\n")

        for line in lines:
            self.canvas.drawString( self.getCol(), self.getRow(), str.center( str(line), 100 ));
            self.nextRow()

    def getCol(self):
        return self.col

    def setCol(self,num):
        self.col = num
        return self.col

    def getRow(self):
        return self.row

    def setRow( self, num ):
        width, height = self.size

        self.row = height - num
        return self.row

    def nextRow(self, increase = 15 ):
        self.row = self.row - increase

        return self.row


"""Store global variables, in this modual by default"""

"""defaults for prodigal"""
from pathlib import Path

PRODIGAL_MODE_DFT = "meta"
PRODIGAL_MODE_CHOICES = ["train", "meta", "single"]
PRODIGAL_TRANS_TABLE_CHOICES = [str(i) for i in range(1, 26)]
PRODIGAL_TRANS_TABLE_DFT = 11

MIN_CONTIG_SIZE_DFT = 2500
BIT_SCORE_THRESHOLD_DFT = 60
RBH_BIT_SCORE_THRESHOLD_DFT = 350

GENOMES_PER_PRODUCT = 1000

# all piplines
DEFAULT_FORCE: bool = False
DEFAULT_OUTPUT_DIR: Path = Path(".")
FASTAS_CONF_TAG = "fastas"


#!/usr/bin/env python

import rospy, sys
import moveit_commander
from moveit_msgs.msg import RobotTrajectory
from trajectory_msgs.msg import JointTrajectoryPoint

from geometry_msgs.msg import PoseStamped, Pose
from tf.transformations import euler_from_quaternion, quaternion_from_euler
from hs_controller.arm_utils import scale_trajectory_speed

class MoveItDemo:
    def __init__(self):
        # Initialize the move_group API
        moveit_commander.roscpp_initialize(sys.argv)

        rospy.init_node('moveit_demo', anonymous=True)

        GRIPPER_OPEN = [0.30]
        GRIPPER_CLOSED = [0.003]
        GRIPPER_NEUTRAL = [0.1]

        # Initialize the move group for the right arm
        arm = moveit_commander.MoveGroupCommander('arm')

        # Connect to the gripper move group
        gripper = moveit_commander.MoveGroupCommander('gripper')

        # Get the name of the end-effector link
        end_effector_link = arm.get_end_effector_link()

        # Set the reference frame for pose targets
        reference_frame = 'base_link'

        # Set the right arm reference frame accordingly
        arm.set_pose_reference_frame(reference_frame)

        # Allow replanning to increase the odds of a solution
        arm.allow_replanning(True)

        # Allow some leeway in position (meters) and orientation (radians)
        arm.set_goal_position_tolerance(0.01)
        arm.set_goal_orientation_tolerance(0.05)
        gripper.set_goal_joint_tolerance(0.001)

        # Start the arm in the "resting" pose stored in the SRDF file
        arm.set_named_target('resting')
        arm.go()
        rospy.sleep(1)

        # Set the gripper target to neutal position using a joint value target
        gripper.set_joint_value_target(GRIPPER_NEUTRAL)

        # Plan and execute the gripper motion
        gripper.go()
        rospy.sleep(1)

        # Open the gripper as if letting something go
        gripper.set_joint_value_target(GRIPPER_OPEN)
        gripper.go()
        rospy.sleep(1)

        # Set the target pose.  This particular pose has the gripper oriented horizontally
        # 0.85 meters above the ground, 0.10 meters to the right and 0.20 meters ahead of
        # the center of the robot base.
        target_pose = PoseStamped()
        target_pose.header.frame_id = reference_frame
        target_pose.header.stamp = rospy.Time.now()
        target_pose.pose.position.x = 1.3
        target_pose.pose.position.y = 0.6
        target_pose.pose.position.z = 1.3
        target_pose.pose.orientation.x = 0.119641717163
        target_pose.pose.orientation.y = -0.791079259511
        target_pose.pose.orientation.z = -0.58825415617
        target_pose.pose.orientation.w = 0.117628705827

        # Set the start state to the current state
        arm.set_start_state_to_current_state()

        # Set the goal pose of the end effector to the stored pose
        arm.set_pose_target(target_pose, end_effector_link)

        # Plan the trajectory to the goal
        traj = arm.plan()

        # Execute the planned trajectory
        arm.execute(traj)

        # Pause for a second
        rospy.sleep(1)

        i = 1
        while (i <= 5):

          # Close the gripper as if picking something up
          gripper.set_joint_value_target(GRIPPER_CLOSED)
          gripper.go()
          rospy.sleep(5)

          # Open the gripper as if letting something go
          gripper.set_joint_value_target(GRIPPER_OPEN)
          gripper.go()
          rospy.sleep(1)

          # Shift the end-effector to the right 5cm
          arm.shift_pose_target(0, 0.20, end_effector_link)

          # Get back the planned trajectory
          traj = arm.plan()

          # Scale the trajectory speed by a factor of 0.25
          new_traj = scale_trajectory_speed(traj, 0.25)

          # Execute the new trajectory
          arm.execute(new_traj)
          rospy.sleep(1)

          i=i+1

        # Finish up in the resting position
        arm.set_named_target('resting')
        arm.go()
        rospy.sleep(1)

        # Open the gripper as if letting something go
        gripper.set_joint_value_target(GRIPPER_NEUTRAL)
        gripper.go()

        # Shut down MoveIt cleanly
        moveit_commander.roscpp_shutdown()

        # Exit MoveIt
        moveit_commander.os._exit(0)

if __name__ == "__main__":
    MoveItDemo()


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

import datetime
from typing import List

from discord.interactions import Interaction

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

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

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

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

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

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

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

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

class EmbedSections():

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


# -*- coding: utf-8 -*-
"""
Two alternatives for matching handshape symbols.
"""
import re
#from pysign.parse import translate

def find_handshape(string, handshape_base="",
                   handshape_diacritic="",
                   dom_nondom=""):
    """
    function for identifying handshape symbols
    """
    in_handshape = False
    handshapes = []
    nondominant = []
    rest = ''
    for char in string:
        if char in handshape_base:
            if in_handshape:
                handshapes[-1] += char # append to existing handshape
            else:
                in_handshape = True # switch on environment of handshape
                handshapes += [char] # append a new segment to the list
        elif char in handshape_diacritic:
            if in_handshape:
                handshapes[-1] += char
        elif char in dom_nondom: # to catch the nondominant handshapes
            if in_handshape:
                in_handshape = False # nondominant handshape should be new item in handshapes list
                nondominant += char
        else:
            in_handshape = False
            rest += char

    handshape_change = ''
    nondominant_hand = ''
    if "" in nondominant: # if true, we know that the second item is nondominant
        dominant_hand = handshapes[0]
        nondominant_hand = handshapes[1]
        handshape_change = handshapes[2:] # there may be multiple changes; typically 1 or 2 per morpheme
    elif len(handshapes) > 1:
        dominant_hand = handshapes[0]
        handshape_change = handshapes[1:]
    else:
        dominant_hand = handshapes[0]

    return {'handshapes' : handshapes,
            'dominant hand' : dominant_hand,
            'non-dominant hand' : nondominant_hand,
            'handshape change(s)' : handshape_change,
            "rest" : rest}

### Tests: see test_sign.py
# Example (1) most simple full sign transcription:
# one dominant hand, one orientation (must have two symbols), one location,
# one movement

{
"   ": # segmented into types
    {
    "symmetry": "",
    "dominant_hand": "", # hamfinger2, '\ue002'
    "nondominant_hand": "",
    "handshape_change": "",
    "dominant_orientation": "", # hamextfingeru,hampalmu
    "nondominant_orientation": "",
    "dominant_location": "", # hamchest
    "nondominant_location": "",
    "dominant_movement": "", # hammoveo
    "nondominant_movement": ""
    }
}

#1
find_handshape("   ")

#1 returns
{'handshapes': ['\ue002'],
 'dominant hand': '\ue002',
 'non-dominant hand': '',
 'handshape change(s)': '',
 'rest': ' \ue020\ue038 \ue052 \ue089'}

# Example (3) two-handed sign completely asymmetrical:
# one dominant hand, one nondominant hand; orientations, locations,
# and movements for each hand

{
 "               ":
     {
      "symmetry": "",
      "dominant_hand": "", # hamfinger2, \ue002
      "nondominant_hand": "", # hamflathand, \ue001
      "handshape_change": "",
      "dominant_orientation": "", # hamextfingeru,hampalml
      "nondominant_orientation": "", # hamextfingero,hampalmd
      "dominant_location": "", # hamshoulders,hamlrat (sequence matters!)
      "nondominant_location": "", # hamlrat,hamchest (sequence matters!)
      "dominant_movement": "", # hammovedo
      "nondominant_movement": "" # hamnomotion
      }
 }

#3
find_handshape("               ")

#3 returns
{'handshapes': ['\ue002', '\ue001'],
 'dominant hand': '\ue002',
 'non-dominant hand': '\ue001',
 'handshape change(s)': [],
 'rest': '\ue0e2  \ue0e3 \ue0e2 \ue020\ue03e  \ue029\ue03c \ue0e3\ue0e2 \ue051\ue059  \ue059\ue052 \ue0e3\ue0e2 \ue090  \ue0af \ue0e3'}

# Example (4) one-handed sign with handshape change:
# one dominant hand and handshape change; no orientation provided,
# two locations, and movement as handshape change

{
 "   ":
    {"symmetry": "",
      "dominant_hand": "", # \ue002\ue00d
      "nondominant_hand": "",
      "handshape_change": "", # \ue002\ue010\ue00d
      "dominant_orientation": "",
      "nondominant_orientation": "",
      "dominant_location": ["", ""], # beginning and ending locations
      "nondominant_location": "",
      "dominant_movement": "",
      "nondominant_movement": ""
    }
}

#4
find_handshape("   ")

#4 returns
{'handshapes': ['\ue002\ue00d', '\ue002\ue010\ue00d'],
 'dominant hand': '\ue002\ue00d',
 'non-dominant hand': '',
 'handshape change(s)': ['\ue002\ue010\ue00d'],
 'rest': ' \ue04a\ue0d0\ue067 \ue0aa \ue0d6\ue04a\ue0d1\ue067'}

# Example (5) two-handed sign with handshape change:
# one dominant hand, one nondominant, and handshape change; no orientation provided,
# two locations, and movement as handshape change

{
 "   ":
    {"symmetry": "",
      "dominant_hand": "", # \ue002\ue00d
      "nondominant_hand": "", # \ue005\ue00c
      "handshape_change": "", # \ue002\ue010\ue00d
      "dominant_orientation": "",
      "nondominant_orientation": "",
      "dominant_location": ["", ""], # beginning and ending locations
      "nondominant_location": "",
      "dominant_movement": "",
      "nondominant_movement": ""
    }
}

#5
find_handshape("   ")

#5 returns
{'handshapes': ['\ue002\ue00d', '\ue005\ue00c', '\ue002\ue010\ue00d'],
 'dominant hand': '\ue002\ue00d',
 'non-dominant hand': '\ue005\ue00c',
 'handshape change(s)': ['\ue002\ue010\ue00d'],
 'rest': ' \ue04a\ue0d0\ue067 \ue0aa \ue0d6\ue04a\ue0d1\ue067'}

def find_handshape_old(string, handshape_base="", handshape_diacritic=""): # updated function above
    """
    Alternative version without re.
    """
    in_handshape = False
    handshapes = []
    rest = ''
    for char in string:
        if char in handshape_base:
            if in_handshape:
                handshapes[-1] += char # append to existing handshape
            else:
                in_handshape = True # switch on environment of handshape
                handshapes += [char] # append a new segment to the list
        elif char in handshape_diacritic:
            if in_handshape:
                handshapes[-1] += char
        else:
            in_handshape = False
            rest += char
    return {'handshape': handshapes, "rest": rest}

# all handshapes in string
regex = r"[][]*"

# only dominant and non-dominant handshapes at start of sign
dom_nondom = r"(?<!)([][]*)"

# any handshape changes in sign
handshape_change = r"(?<=)([][]*)"

# see test_sign.py for target results
test_example_1 = "   "
test_example_2 = "    "
test_example_3 = "                 "
test_example_4 = "   "

matches_1 = re.finditer(regex, test_example_1)

for matchNum, match in enumerate(matches_1, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(
        matchNum = matchNum, start = match.start(), end = match.end(),
        match = match.group()))

for example in [test_example_1, test_example_2, test_example_3,
        test_example_4]:
    res = find_handshape(example)
    print('Found handshape at {0} / {1}'.format(
        res['handshape'],
        translate(res['handshape'])))


import numpy as np
import matplotlib.pyplot as plt

tempMDS      = np.load("MDS_temperature.npy")
grassmannMDS = np.load("MDS_Grassmann.npy")

plt.figure()
plt.title("MDS plot (from euclidean distances between T fields)")
plt.scatter(tempMDS[:,0],tempMDS[:,1], c = 'b', marker = 'o', s=30)
plt.show()

plt.figure()
plt.title("MDS plot (from Grassmann distances)")
plt.scatter(grassmannMDS[:,0],grassmannMDS[:,1], c = 'b', marker = 'o', s=30)
plt.show()


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
# leetcode 102
# 二叉树层次遍历

class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        stack = [root]
        result = []
        self.traversal(1, root, result)
        return result

    def traversal(self, level, root, result) -> List[List[int]]:
        if not root:
            return root
        # one list in each layer
        if level > len(result):
            result.append([])
        result[level - 1].append(root.val)
        self.traversal(level + 1, root.left, result)
        self.traversal(level + 1, root.right, result)


import bpy
import bmesh
import json

def clean():
    for o in bpy.data.objects:
        if o.type == 'MESH':
            o.select = True
        else:
            o.select = False

    # call the operator once
    bpy.ops.object.delete()

clean()

file_obj = r'C:\Users\Christian\Dropbox\Arbejde\DTU BYG\Livestock\livestock\tests\test_data\drainage_flow\drain_mesh.obj'

bpy.ops.import_scene.obj(filepath=file_obj, axis_forward='X', axis_up='Z', )
imported_mesh = bpy.context.selected_objects[-1]

me = imported_mesh.data
bm = bmesh.new()

# Get a BMesh representation
bm.from_mesh(me)

lowest_neighbour = []
for face in bm.faces:
    linked_faces = set(f
                       for v in face.verts
                       for f in v.link_faces)
    centers = [[linked_face.index, tuple(linked_face.calc_center_median())]
               for linked_face in linked_faces]

    sorted_centers = sorted(centers, key=lambda v: v[1][2])

    if face.calc_center_median().z <= sorted_centers[0][1][2]:
        lowest_neighbour.append(None)
    else:
        lowest_neighbour.append(sorted_centers[0])

#print(lowest_neighbour)

def get_curve_points(start_index, point_list):

    curve_points = []
    next_index = start_index
    while True:
        pt = point_list[next_index]

        if pt:
            next_index = pt[0]
            curve_points.append(pt[1])
        else:
            return curve_points

curves = []
for face_index in range(len(bm.faces)):
    curves.append(get_curve_points(face_index, lowest_neighbour))

outfile = r'C:\Users\Christian\Dropbox\Arbejde\DTU BYG\Livestock\livestock\tests\test_data\drainage_flow\result.json'

with open(outfile, 'w') as file:
    json.dump(curves, file)


#!/usr/bin/python

from tensorflow import keras

def create(learning_rate=1e-3):
    model = keras.Sequential([
        keras.layers.Conv2D(
            filters=32,
            kernel_size=5,
            input_shape=(120, 300, 3),
            activation='elu',
            strides=(2, 2),
            padding='same',
        ),
        keras.layers.Conv2D(
            filters=64,
            kernel_size=5,
            activation='elu',
            strides=(2, 2),
            padding='same',
        ),
        keras.layers.Conv2D(
            filters=128,
            kernel_size=3,
            activation='elu',
            strides=(1, 1),
            padding='same',
        ),
        keras.layers.Conv2D(
            filters=128,
            kernel_size=3,
            activation='relu',
            strides=(1, 1),
            padding='same',
        ),
        keras.layers.Flatten(),
        keras.layers.Dense(128, activation='elu'),
        keras.layers.Dropout(0.5),
        keras.layers.Dense(64, activation='elu'),
        keras.layers.Dropout(0.5),
        keras.layers.Dense(1)
    ])

    adam = keras.optimizers.Adam(learning_rate=learning_rate)
    model.compile(optimizer=adam, loss='mse')

    print('created model...')
    print(model.summary())

    return model


from typing import List, Optional, Set

from PyQt5 import QtCore, QtGui
from commandbar.api import cmdutils
from mainwindow.canvas import CanvasContentManager, Canvas, CanvasPainter
from mainwindow.painters.painter import CustomPainter
from mainwindow.painters import tools
from commandbar.utils import objreg

ANNOTATE_PAINTER = 'annotate-painter'
ANNOTATIONS = 'annotations'

@cmdutils.register(name='annotate', instance='canvas', scope='canvas')
def annotate(self: Canvas):
    if ANNOTATIONS not in self.registry:
        self.add_content_manager(ANNOTATIONS, AnnotationContentManager(self))
    painters = self.registry['painters']
    if ANNOTATE_PAINTER not in painters:
        painters[ANNOTATE_PAINTER] = AnnotatePainter(self.qpainter)
    self.set_painter(painters[ANNOTATE_PAINTER])

class AnnotationContentManager(CanvasContentManager):
    def __init__(self, canvas: Canvas) -> None:
        super().__init__(canvas)
        self.lines: List[QtCore.QLine] = list()

class AnnotatePainter(CanvasPainter):
    def __init__(self, painter: CustomPainter) -> None:
        super().__init__(painter)
        self.content: AnnotationContentManager = objreg.get(
            'annotations', scope='canvas', canvas='current'
        )
        self.last_point: Optional[QtCore.QPoint] = None
        self.pen, self.brush = tools.make_pen_and_brush('white')
        #tools.WHITE_PEN, tools.WHITE_BRUSH

    def on_mouse_press(self, e: QtGui.QMouseEvent):
        self.last_point = e.pos()

    def on_mouse_left_click_drag(self, e: QtGui.QMouseEvent):
        new_point = e.pos()
        self.painter.set(self.pen, self.brush)
        line = QtCore.QLine(self.last_point, new_point)
        self.painter.drawLine(self.last_point, new_point)
        self.content.lines.append(line)
        self.last_point = new_point

    @cmdutils.register(name='set-color', instance='annotate-painter', scope='canvas')
    def set_color(self, color: str):
        color = QtGui.QColor(color)
        self.pen = QtGui.QPen(color)
        self.brush = QtGui.QBrush(color, QtCore.Qt.SolidPattern)


# Author: Xinyi Wang
# Date: 2021/10/05

import cv2
from PIL import Image
import numpy as np
import pandas as pd
import os
import torch
import torch.nn.functional as F
import torchvision.models as models

import scipy.io as io

import sys
sys.path.append('..')
from utils import *
from cam.scorecam import *

def fsam(video_name, framerate):

    torch.cuda.empty_cache()
    # vgg score saliency map
    vgg = models.vgg16(pretrained=True).eval()
    vgg_model_dict = dict(type='vgg16', arch=vgg, layer_name='features_29', input_size=(224, 224))
    vgg_scorecam = ScoreCAM(vgg_model_dict)
    torch.cuda.empty_cache()

    # open the video
    cap = cv2.VideoCapture(video_name)  # Get the video object
    isOpened = cap.isOpened  # Determine if it is open
    # Video information acquisition
    fps = cap.get(cv2.CAP_PROP_FPS)
    torch.cuda.empty_cache()

    imageNum = 0
    sum = 0
    # timef = 30  # Save a picture every 30 frames
    print('framerate:', framerate)
    torch.cuda.empty_cache()

    sum_samp = 0
    while (isOpened):

        sum += 1
        (frameState, frame) = cap.read()  # Recording of each frame and acquisition status
        torch.cuda.empty_cache()
        if frameState == True and (sum % framerate == 0):
            torch.cuda.empty_cache()
            # Format transformation, BGRtoRGB
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            # Convert to Image
            frame = Image.fromarray(np.uint8(frame))
            frame = np.array(frame)
            # RGBtoBGR meets the opencv display format
            frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)

            torch.cuda.empty_cache()
            imageNum = imageNum + 1
            fileName = '../../tmp/video_image_temp/' + str(imageNum) + '.jpg'  # Temporary storage path
            cv2.imwrite(fileName, frame, [cv2.IMWRITE_JPEG_QUALITY, 100])
            # print(fileName + " successfully write in")  # Output storage status
            input_image = load_image(fileName)

            torch.cuda.empty_cache()
            # print(input_image)
            input_ = apply_transforms(input_image)
            if torch.cuda.is_available():
                input_ = input_.cuda()
            predicted_class = vgg(input_).max(1)[-1]

            torch.cuda.empty_cache()
            scorecam_map = vgg_scorecam(input_)
            # print(input_)
            t = scorecam_map.cpu()
            smap = t.numpy()  # tensor 2 numpy
            # print(scorecam_map)
            # print(smap)
            sum_samp += smap

            # Clear temp data
            os.remove(fileName)
            torch.cuda.empty_cache()

        elif frameState == False:
            break
    print('Complete the extraction of video frames!')
    torch.cuda.empty_cache()
    mean_samp = sum_samp / imageNum
    # print(mean_samp)
    mean_samp = np.squeeze(mean_samp)
    io.savemat('../../tmp/tempmat_path/samp.mat', {'mean_samp': mean_samp})

    torch.cuda.empty_cache()

    return mean_samp

if __name__ == "__main__":
    torch.cuda.empty_cache()
    video = "C://Users//um20242//OneDrive - University of Bristol//Documents//PycharmProjects//UoB//RVS-resize//tmp//temp_resize//tmp.avi"
    mean_samp = fsam(video, 24)
    print(mean_samp)


"""Session helper."""
import traceback
from functools import wraps

from ilswbot.db import get_session

def job_session_wrapper():
    """Create a session and handle exceptions for jobs."""
    def real_decorator(func):
        """Parametrized decorator closure."""
        @wraps(func)
        def wrapper(context):
            session = get_session()
            try:
                func(context, session)

                session.commit()
            except: # noqa
                traceback.print_exc()
            finally:
                session.close()
        return wrapper

    return real_decorator

def session_wrapper(send_message=True):
    """Allow specification whether a debug message should be sent to the user."""
    def real_decorator(func):
        """Create a database session and handle exceptions."""
        @wraps(func)
        def wrapper(update, context):
            session = get_session()
            if update.message is None:
                return
            try:
                func(context.bot, update, session)
                session.commit()
            except:
                if send_message:
                    context.bot.sendMessage(
                        chat_id=update.message.chat_id,
                        text='An unknown error occurred.',
                    )
                traceback.print_exc()
            finally:
                session.remove()
        return wrapper

    return real_decorator


import json
from flask import Blueprint, jsonify
from redis import Redis

redis_endpoint = Blueprint("redis_endpoint", __name__)
r = Redis(host="redis-container", port=6379)

# Endpoint
def ping_service():
    try:
        if r.ping():
            response = jsonify({'Connection': "OK"})
            response.status_code = 200
            return response
        else:
            response = jsonify({'Connection': "NOT OK"})
            response.status_code = 500
            return response
    except Exception as e:
        return jsonify({'message': str(e)}, 404)

def validatePush(data_object):
    if 'msg' in data_object and type(data_object["msg"]) == str:
        return True
    else:
        return False

# Endpoint
def push_service(data):
    try:
        if validatePush(data_object=data):
            push_redis(r, "Queue", data["msg"])
            response = jsonify({'status': 'ok'})
            response.status_code = 200
            return response
        else:
            response = jsonify({"message": "invalid message input"})
            response.status_code = 400
            return response
    except Exception as e:
        return jsonify({'message': str(e)}, 404)

def push_redis(redis: Redis, key, msg):
    return redis.lpush(key, msg)

# Endpoint
def pop_service():
    try:
        if count_redis(r, 'Queue') != 0:
            deleted = pop_redis(r, "Queue")
            response = jsonify({"message": deleted})
            response.status_code = 200
            return response
        else:
            response = jsonify({"message": "Queue is empty"})
            response.status_code = 400
            return response
    except Exception as e:
        return jsonify({'message': str(e)}, 404)

def pop_redis(redis: Redis, key):
    return redis.lpop(key).decode("utf-8")

# Endpoint
def count_service():
    try:
        response = jsonify({"status": "ok", "count": count_redis(r, "Queue")})
        response.status_code = 200
        return response
    except Exception as e:
        return jsonify({'message': str(e)}, 404)

def count_redis(redis: Redis, key):
    return redis.llen(key)


# This script creates TFRecord files for the testing data set.

import tensorflow as tf
import cv2
import glob2
import math

def _bytes_feature(value):
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

# Path to the directory containing test TIFF images.
image_paths = glob2.glob('../test-tif-v2/*')
temp = image_paths[0].split('/')
print(temp)

# Path for the directory to store TFRecord files for test data.
tfrecord_path_prefix = '../tfrecords/test/'

num_shards = 6
records_per_file = math.ceil(len(image_paths)/num_shards)

tfrecord_paths = [tfrecord_path_prefix+'planet-'+str(i*records_per_file)+'-'+str((i+1)*records_per_file)+'.tfrecord'
                  if i!=num_shards-1
                  else tfrecord_path_prefix+'planet-'+str(i*records_per_file)+'-'+str(len(image_paths))+'.tfrecord'
                  for i in range(num_shards)]

print(tfrecord_paths)

tfrecord_writer = None
num_processed = 0
for i in range(num_shards):
    tfrecord_writer = tf.io.TFRecordWriter(tfrecord_paths[i])
    image_paths_shard = image_paths[i*records_per_file: (i+1)*records_per_file] if i!=num_shards-1 \
                        else image_paths[i*records_per_file: len(image_paths)]
    for image_path in image_paths_shard:
        image = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)
        image = cv2.normalize(image, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)
        #encode
        image_string = image.tostring()
        feature_dict = {'image_string':_bytes_feature(image_string)}
        example = tf.train.Example(features=tf.train.Features(feature=feature_dict))
        tfrecord_writer.write(example.SerializeToString())
    num_processed = num_processed + len(image_paths_shard)
    print('Processed: '+str(num_processed)+ ' files.')

tfrecord_writer.close()


import ast
import linecache

pathToStudentData = r'studentData/'

def getStudentData(kerberosHash):
    fullPath = pathToStudentData + str(kerberosHash) + ".txt"
    try:
        f = open(fullPath, 'r')
    except:
        return {'kerberosHash':kerberosHash}

    ans = {'kerberosHash':kerberosHash}
    for line in f:
        if line[-1] == '\n':
            line = line[:len(line)-1]
        try:
            rep = ast.literal_eval(line)
        except SyntaxError:
            rep = None
        if rep != None and rep['kerberosHash'] == kerberosHash:
            ans = rep
            break
    f.close()
    return ans

def extractText(filename):
    f = open(filename, 'r')
    s = "".join(f.readlines())
    f.close()
    return s

def getStudentProblemData(kerberosHash, problemID):
    d = getStudentData(kerberosHash)
    return d.get(problemID, 'null')

def saveResponse(kerberosHash, problemID, data):
    fullPath = pathToStudentData + str(kerberosHash) + ".txt"
    try:
        f = open(fullPath, 'r')
        lines = f.readlines()
        f.close()
    except:
        lines = []
    rep = None
    for i in range(len(lines)):
        line = lines[i]
        if line[-1] == '\n':
            line = line[:len(line)-1]
        try:
            rep = ast.literal_eval(line)
        except:
            rep = None
        if rep != None and rep['kerberosHash'] == kerberosHash:
            lines.pop(i)
            break
    if rep == None or rep['kerberosHash'] != kerberosHash:
        rep = {'kerberosHash':kerberosHash}
    rep[problemID] = data
    lines.insert(0, str(rep) + '\n')
    f = open(fullPath, 'w')
    lines = "".join(lines)
    f.write(lines)
    f.close()


# E' = D
# T' = U
G = {
        "E" : { "TD" },
        "D" : { "+TD", "-TD", "" },
        "T" : { "FU" },
        "U" : { "*FU", "/FU", "" },
        "F" : { "f(A)", "(E)", "-F", "n" },
        "A" : { "EB", "" },
        "B" : { ",EB", "" }
    }

# G = {
#         "E" : { "E+T", "T" },
#         "T" : { "T*F", "F" },
#         "F" : { "(E)", "n" }
#     }

S = "E"

first  = { nt : set({}) for nt in G.keys() }
follow = { nt : set({}) for nt in G.keys() }
follow[S].update("$")

def first_of(a):
    if len(a) == 0:
        return { "" }
    elif not a[0].isupper():
        return { a[0] }
    res = first[a[0]]
    if "" in res:
        res = (res - { "" }).union(first_of(a[1:]))
    return res

def calc_ff():
    changed = True
    while (changed):
        changed = False
        for A, alphas in G.items():
            for a in alphas:
                if not (first_of(a).issubset(first[A])):
                    first[A].update(first_of(a))
                    changed = True
    changed = True
    while (changed):
        changed = False
        for A, alphas in G.items():
            for a in alphas:
                for i in range(len(a)):
                    if not a[i].isupper():
                        continue
                    beta = a[:i]
                    B = a[i]
                    gamma = a[i+1:]
                    upd = first_of(gamma)
                    if "" in upd:
                        upd = (upd - {""}).union(follow[A])
                    if not (upd.issubset(follow[B])):
                        changed = True
                        follow[B].update(upd)

calc_ff()

print("FIRST")
for A, firstA in first.items():
    print(A + ": " + str(sorted(firstA)))
print("FOLLOW")
for A, followA in follow.items():
    print(A + ": " + str(sorted(followA)))