import sys
from tkinter import *
from tkinter.filedialog import asksaveasfilename
import threading
import socket
import time

conn_array = []
addr_array=[]
username_array = []
username="Self"
count=0
main_body_text=0
port = []
myname=""
th = []

class Server(threading.Thread):
    def __init__(self,port):
        threading.Thread.__init__(self)
        self.port=port

    def run(self):
        global conn_array
        global addr_array
        global username_array
        s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        s.bind(('',self.port))
        s.listen(1)
        writeToScreen("Socket is good, waiting for connections on port : "+str(self.port),"System")
        while 1:
            if len(conn_array) <= 3:
                a=len(username_array)
                conn_init,addr_init=s.accept()
                conn_array.append(conn_init)
                addr_array.append(addr_init)
                thindex = threading.Thread(target=Runner,args=(conn_init,str(addr_init[0]),False))
                th.append(thindex)
                thindex.start()
                global statusConnect
                statusConnect.set("Disconnect")
                connecter.config(state=DISABLED)
                if a==len(username_array):
                    time.sleep(1)
                writeToScreen("accept Suceess",username_array[a])
            else:
                conn, addr = s.accept()
                netThrow(conn, "room is full!!")
                time.sleep(3)
                conn.close()

def QuickServer():
    Server(9990).start()

def resetting(master):
    connecter.config(state=NORMAL)
    master.destroy()

def server_options_window(master):
    """Launches server options window for getting port."""
    top = Toplevel(master)
    top.title("Connection options")
    top.grab_set()
    top.protocol("WM_DELETE_WINDOW", lambda: resetting(top))
    Label(top, text="Port:").grid(row=0)
    port = Entry(top)
    port.grid(row=0, column=1)
    port.focus_set()
    go = Button(top, text="Launch", command=lambda:
                server_options_go(port.get(), top))
    go.grid(row=1, column=1)

def server_options_go(port,window):
    if port_process(port):
        Server(int(port)).start()
    else:
        writeToScreen("you mistake input")
        connecter.config(state=NORMAL)
    window.destroy()

def saveHistory():
    """Saves history with Tkinter's asksaveasfilename dialog."""
    global main_body_text
    file_name = asksaveasfilename(
        title="Choose save location",
        filetypes=[('Plain text', '*.txt'), ('Any File', '*.*')])
    print(file_name)
    try:
        filehandle = open(file_name + ".txt", "w")
    except IOError:
        print("Can't save history.")
        return
    contents = main_body_text.get(1.0, END)
    for line in contents:
        filehandle.write(line)
    filehandle.close()

def list_info(master,mynick=""):
    top=Toplevel(master)
    top.title("talk list")
    top.protocol("WM_DELETE_WINDOW",lambda:top.destroy())
    top.grab_set()
    top.focus_set()
    listbox=Listbox(top)
    for i in range(0,len(username_array)):
        listbox.insert(END,username_array[i])
    listbox.pack()

class Client(threading.Thread):
    def __init__(self,host,port,name):
        threading.Thread.__init__(self)
        self.port=port
        self.host=host
        self.name=name
    def run(self):
        global conn_array
        global port

        conn_init=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        conn_init.connect((self.host,self.port))
        port.append(self.port)
        writeToScreen("connect Suceess","Chatting server")
        netThrow(conn_init,"TnTiTcTk : "+self.name)
        conn_array.append(conn_init)
        threading.Thread(target=Runner,args=(conn_init,self.host,True)).start()
        global statusConnect
        statusConnect.set("Disconnect")
        connecter.config(state=NORMAL)

def client_options_go(dest,nickname,port,window):
    window.destroy()
    if ip_process(dest.split(".")) and port_process(port) and len(nickname)>0:
        Client(dest,int(port),nickname).start()
    else:
        writeToScreen("you mistake input")
        connecter.config(state=NORMAL)

def ip_process(ipArray):
    if len(ipArray) != 4:
        return False
    for ip in ipArray:
        if not ip.isnumeric():
            return False
        if int(ip)<0 or int(ip)>255:
            return False
    return True

def port_process(port):
    if not port.isnumeric():
        return False
    if int(port)<0 or 65555<int(port):
        return False
    return True

def QuickClient():
    #Client("192.168.10.73",9990).start()
    window = Toplevel(root)
    window.title("Connection options")
    window.grab_set()
    Label(window,text="Server IP : ").grid(row=0)
    destination = Entry(window)
    destination.grid(row=0,column=1)
    Label(window,text="Nick name : ").grid(row=1)
    nickname = Entry(window)
    nickname.grid(row=1,column=1)
    go = Button(window,text="Connect",command=lambda:
                client_options_go(destination.get(),nickname.get().strip(),"9990",window))
    go.grid(row=2,column=1)

def client_options_window(master):
    """Launches client options window for getting destination hostname
    and port.

    """
    top = Toplevel(master)
    top.title("Connection options")
    top.protocol("WM_DELETE_WINDOW", lambda: resetting(top))
    top.grab_set()
    Label(top, text="Server IP:").grid(row=0)
    location = Entry(top)
    location.grid(row=0, column=1)
    location.focus_set()
    Label(top, text="Port:").grid(row=1)
    port = Entry(top)
    port.grid(row=1, column=1)
    Label(top,text="Nick name : ").grid(row=2)
    nickname = Entry(top)
    nickname.grid(row=2,column=1)
    go = Button(top, text="Connect", command=lambda:
                client_options_go(location.get(),nickname.get().strip(), port.get(), top))
    go.grid(row=3, column=1)

def netThrow(conn,text):
    try:
        conn.send(text.encode("utf-8"))
    except socket.error:
        writeToScreen("throw fail","SYSTEM")

def netCatch(conn):
    try:
        message = conn.recv(512)
        return message.decode("utf-8")
    except socket.error:
        writeToScreen("catch fail","SYSTEM")

def contacts_window(master):
    top=Toplevel(master)
    top.title("Contacts")
    top.grab_set()
    scrollbar=Scrollbar(top,orient=VERTICAL)
    listbox=Listbox(top,yscrollcommand=scrollbar.set)
    scrollbar.config(command=listbox.yview)
    scrollbar.pack(side=RIGHT,fill=Y)
    buttons=Frame(top)
    cBut=Button(buttons,text="Connect",command=lambda:contacts_connect(listbox.get(ACTIVE).split(" ")))
    cBut.pack(side=LEFT)
    dBut=Button(buttons,text="Remove",command=lambda:contacts_remove(listbox.get(ACTIVE).split(" "),listbox))
    dBut.pack(side=LEFT)
    aBut=Button(buttons,text="Add",command=lambda:contacts_add(listbox,top))
    aBut.pack(side=LEFT)
    buttons.pack(side=BOTTOM)
    listbox.pack(side=LEFT,fill=BOTH,expand=1)

def contacts_connect(item):
    Client(item[1],int(item[2]),item[0]).start()

def contacts_remove(item,listbox):
    if listbox.size()!=0:
        listbox.delete(ACTIVE)

def contacts_add(listbox,master):
    top=Toplevel(master)
    top.title("Contact add")
    Label(top,text="Nickname:").grid(row=0)
    nickname=Entry(top)
    nickname.focus_set()
    nickname.grid(row=0,column=1)
    Label(top,text="IP:").grid(row=1)
    ip=Entry(top)
    ip.grid(row=1,column=1)
    Label(top,text="Port:").grid(row=2)
    port=Entry(top)
    port.grid(row=2,column=1)
    go=Button(top,text="Add",command=lambda:
              contacts_add_helper(nickname.get(),ip.get(),port.get(),
                                  top,listbox))
    go.grid(row=3,column=1)

def contacts_add_helper(nickname,ip,port,window,listbox):
    if ip_process(ip.split(".")) and port_process(port) and len(nickname)>0:
        listbox.insert(END,nickname+" "+ip+" "+port)
        window.destroy()
        return
def username_options_window(master):
    top=Toplevel(master)
    top.title("Nickname Change")
    top.grab_set()
    Label(top,text="Nickname:").grid(row=0)
    name=Entry(top)
    name.focus_set()
    name.grid(row=0,column=1)
    go=Button(top,text="Change",command=lambda:username_options_go(name.get(),top))
    go.grid(row=1,column=1)

def username_options_go(name,window):
    if len(conn_array)!=0:
        netThrow(conn_array[0],"TcThTaTn : "+name)
    else:
        writeToScreen("before you must connect","System")
    window.destroy()

def ProgramExit() :
    global conn_array

    fd = conn_array[0].getsockname()

    netThrow(conn_array[0], "TdTeTlTe : "+str(fd[1]))

    conn_array[0].close()
    conn_array.pop()
    root.destroy()

def Runner(conn,addr,clientType,name=""):
    global username_array
    global conn_array
    while 1:
        data = netCatch(conn)
        if type(data) == type(None) :
            time.sleep(10)
            break
        elif clientType==False:
            if data[0:11]=="TnTiTcTk : ":
                if len(username_array)!=0:
                    for i in range(len(username_array)):
                        netThrow(conn_array[i],"TuTsTeTr : "+data[11:])
                    for i in range(len(username_array)):
                        netThrow(conn,"TuTsTeTr : "+username_array[i])
                try:
                    username_array.find(data[11:])
                except AttributeError:
                    username_array.append(data[11:])
                    continue
            elif data[0:11]=="TdTeTlTe : ":
                i = 0
                for ip, por in addr_array:
                    if str(por) == data[11:] :
                        port = por
                        break
                    i += 1
                conn_array[i].close()
                conn_array.pop(i)
                addr_array.pop(i)
                username_array.pop(i)
            elif data[0:11]=="TcThTaTn : ":
                writeToScreen(" nick : "+username_array[conn_array.index(conn)]+" change nickname nick : "+data[11:],"System")
                username_array[conn_array.index(conn)]=data[11:]
                for i in range(len(conn_array)):
                    if i!=conn_array.index(conn):
                        netThrow(conn_array[i],data)
            else:
                for i in range(0,len(conn_array)):
                    if conn!=conn_array[i]:
                        netThrow(conn_array[i],data+"+"+username_array[conn_array.index(conn)])
                    else:
                        writeToScreen(data,username_array[i])
        else:
            if data[0:11]=="TuTsTeTr : ":
                if myname!=data[11:]:
                    username_array.append(data[11:])
                continue
            if data[0:11]=="TcThTaTn : ":
                writeToScreen(" nick : "+username_array[conn_array.index(conn)]+" change nickname nick : "+data[11:],"System")
                username_array[conn_array.index(conn)]=data[11:]
                continue
            if data.rfind("+")==-1:
                writeToScreen(data,"Server")
            else:
                writeToScreen(data[0:data.rfind("+")],data[data.rfind("+")+1:])

def processUserText(event):
    writeToScreen(text_input.get(),username)
    netThrow(conn_array[0],text_input.get())
    text_input.delete(0,END)

def writeToScreen(text,user=""):
    global main_body_text
    main_body_text.config(state=NORMAL)
    main_body_text.insert(END,'\n')
    if user:
        main_body_text.insert(END,"["+user+"]")
    main_body_text.insert(END,text)
    main_body_text.yview(END)
    main_body_text.config(state=DISABLED)

def connects(clientType):
    global conn_array
    connecter.config(state=DISABLED)
    if len(conn_array) == 0:
        if clientType == 0:
            client_options_window(root)
        if clientType == 1:
            server_options_window(root)
    else:
        ProgramExit()

def toOne():
    global clientType
    clientType = 0

def toTwo():
    global clientType
    clientType = 1

root=Tk()
root.title("MulitChat")

menubar=Menu(root)

file_menu = Menu(menubar,tearoff=0)
file_menu.add_command(label="Save Chat",command=lambda:saveHistory())
file_menu.add_command(label="Change Username",command=lambda:username_options_window(root))
file_menu.add_command(label="Exit",command=lambda:root.destroy())
menubar.add_cascade(label="File",menu=file_menu)

connection_menu = Menu(menubar,tearoff=0)
connection_menu.add_command(label="Quick Connect",command=QuickClient)
connection_menu.add_command(label="Connect on port",command=lambda:client_options_window(root))
connection_menu.add_command(label="Disconnect",command=ProgramExit)
menubar.add_cascade(label="Connect",menu=connection_menu)

server_menu = Menu(menubar,tearoff=0)
server_menu.add_command(label="Launch Server",command=QuickServer)
server_menu.add_command(label="Listen on port",command=lambda:server_options_window(root))
menubar.add_cascade(label="Server",menu=server_menu)

menubar.add_command(label="Contacts",command=lambda:contacts_window(root))

menubar.add_command(label="talk list",command=lambda:list_info(root,myname))

root.config(menu=menubar)

main_body = Frame(root,height=20,width=60)

main_body_text = Text(main_body)
body_text_scroll = Scrollbar(main_body)
main_body_text.focus_set()
body_text_scroll.pack(side=RIGHT,fill=Y)
main_body_text.pack(side=LEFT,fill=Y)
body_text_scroll.config(command=main_body_text.yview)
main_body_text.config(yscrollcommand=body_text_scroll.set)
main_body.pack()

main_body_text.insert(END,"Welcome to the chat program!")
main_body_text.config(state=DISABLED)

text_input = Entry(root,width=60)
text_input.bind("<Return>",processUserText)
text_input.pack()

statusConnect = StringVar()
statusConnect.set("Connect")
clientType = 1
Radiobutton(root,text="Client",variable=clientType,value=0,command=toOne).pack(anchor=E)
Radiobutton(root,text="Server",variable=clientType,value=1,command=toTwo).pack(anchor=E)
connecter = Button(root,textvariable=statusConnect,command=lambda: connects(clientType))
connecter.pack()

root.mainloop()


from Classes.game import Game
# from Classes.player import Player
from Language_Parser.languageParser import parse

def gameStart():
    # Initialize Game and load state
    game = Game()
    game.titleScreen()
    game.selectGameState()
    player = game.getPlayer()
    # Begin user input loop to play game
    while game.isRunning() and not game.checkForWin():
        userInput = input("\n> ")
        if userInput.replace(" ", "").lower() == "exitgame":
            game.exitGame()
        else:
            parse(userInput, player, game)
    if game.checkForWin():
        game.outro()
    else:
        print("\nThank you for playing Scary Attic.")
        print("We sincerely hope you enjoyed it.\n")

if __name__ == "__main__":

    gameStart()


import os
import numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt
import pynbody

from simifucube.util.doppler_shift import dopplerShift

import logging

def setup_logger(logger_level=logging.INFO, logger_name=None):

    # formatter = logging.Formatter('%(asctime)s %(levelname)s %(name)s - %(message)s')
    # log_file_handler = logging.FileHandler(os.path.join(config_logger['log_dir'], config_logger['log_file']))
    # log_file_handler.setFormatter(formatter)

    stream_formatter = logging.Formatter('%(asctime)s %(levelname)s - %(message)s')
    log_stream_handler = logging.StreamHandler()
    log_stream_handler.setFormatter(stream_formatter)

    logger = logging.getLogger(logger_name)
    # logger.addHandler(log_file_handler)
    logger.addHandler(log_stream_handler)
    logger.setLevel(logger_level)

    return logger

logger = setup_logger(logging.INFO)

# Metallicity [M/H] (Z)
bins_metallicity = [-2.27, -1.79, -1.49, -1.26, -0.96, -0.66, -0.35, -0.25, +0.06, +0.15, +0.26, +0.40]

# Age (Gyr)
bins_age = [00.03, 00.04, 00.05, 00.06, 00.07, 00.08, 00.09, 00.10, 00.15, 00.20,
00.25, 00.30, 00.35, 00.40, 00.45, 00.50, 00.60, 00.70, 00.80, 00.90, 01.00,
01.25, 01.50, 01.75, 02.00, 02.25, 02.50, 02.75, 03.00, 03.25, 03.50, 03.75, 04.00,
04.50, 05.00, 05.50, 06.00, 06.50, 07.00, 07.50, 08.00, 08.50, 09.00, 09.50, 10.00,
10.50, 11.00, 11.50, 12.00, 12.50, 13.00, 13.50, 14.00]

SPECTRA_DIR = '/home/michele/sim/IFU_images/library/EMILES_BASTI_BASE_CH_FITS'
ELEMENT_LIMIT = 10000  # For MUSE it's fine (10000 spectral pixel = 10678.9 Angstrom)

# -- From http://www.iac.es/proyecto/miles/pages/ssp-models.php
# The stellar population synthesis model predictions and are based on the code presented in Vazdekis et al. (2010).
# The spectra are stored in air wavelengths.
# The total mass of the SSP is 1Mo. The SSP spectra are given in units of L_λ / Lo Mo^{-1} Å^{-1}.

# -- From http://www.iac.es/proyecto/miles/pages/ssp-models/name-convention.php
# Please note that the relation between the total metallicity and iron metallicity is
#      [Fe/H]=[M/H]-0.75[Mg/Fe]
# Thus when selecting a scaled-solar model with total metallicity [M/H] then [Fe/H]=[M/H],
# whereas for the alpha-enhanced models with the same metallicity [Fe/H]=[M/H]-0.3.
# Finally for the "base" models it is assumed that [Fe/H]=[M/H], although this is only true at high metallicities.
# For low metallicities the input stars are alpha-enhanced and therefore when selecting a model with
# total metallicity [M/H] its [Fe/H] is lower.
# To summarize the base models follow the abundance pattern of The Galaxy.
# Note that these models are inconsistent at low metallicities because the adopted isochrones are always scaled-solar.

# As an example, if only models with total metallicity [M/H]=+0.06, 10 Gyr and bimodal IMF shape with slope 1.30 are requested, then the following set of models computed with BaSTI isochrones can  be downloaded:
# * Mbi1.30Zp0.06T10.0000_iTp0.00_Ep0.00   scaled-solar abundance ratio ([M/H]=[Fe/H]=+0.06)
# * Mbi1.30Zp0.06T10.0000_iTp0.40_Ep0.40   alpha-enhanced abundance ratio ([M/H]=+0.06; [Fe/H]=-0.24)
# * Mbi1.30Zp0.06T10.0000_iTp0.00_baseFe   base models where no consideration about the abundance ratio is being made.
#                                          The stars feeding the models are picked on the basis of their [Fe/H] metallicity,
#                                          and therefore these models follow the abundance pattern of The Galaxy.
# as well as base models computed with the Padova00 isochrones with nearly similar metallicity:
# * Mbi1.30Zp0.00T10.0000_iPp0.00_baseFe

def get_nearest(x, bins):
    return bins[np.abs(np.array(bins) - x).argmin()]

def get_bin(x, bins):
    n = np.digitize(x, bins)
    return bins[n-1], bins[n]

def get_filename(metallicity, age):
    """
    Get filename of the correct SSP by parsing the E-MILES library.

    I use E-MILES with Chabrier IMF with 1.3 slope and BaSTI isochrones.
    The metallicity is [Fe/H] of the star particle
    Age is in Gyr
    """
    met = get_nearest(metallicity, bins_metallicity)
    _age = get_nearest(age, bins_age)
    met_sign = 'p' if met >= 0 else 'm'
    name = 'Ech1.30Z{}{:3.2f}T{:07.4f}_iTp0.00_baseFe.fits'.format(met_sign, abs(met), _age)
    filename = os.path.join(SPECTRA_DIR, name)
    return filename

def get_spectrum(filename, n_limit=ELEMENT_LIMIT):
    """
    Get spectrum from the given filename. Limit the read to the first `n_limit` elements

    Parameters
    ----------
    filename: str
        The filename
    n_limit: int (default 10000)
        Number of elements to read from the spectrum from the beginning. This reduces the memory footprint.
        This useful because last spectral channels are usually outside of range for practical purpose.
        For MUSE the default of 10000 is fine. 10000 spectral pixels corresponds to an upper limit of 10678.9 Angstrom, MUSE arrives at 9600 Angstroms

    Returns
    -------
    wavelength:np.ndarray
        Wavelength in Angstrom
    flux: np.ndarray
        Spectral flux per unit mass (Luminosity per unit wavelength per unit mass) in Lo Mo^{-1} Å^{-1}
    """
    with fits.open(filename) as hdul:
        hdu = hdul[0]

        low_limit = hdu.header['CRVAL1']
        N = hdu.header['NAXIS1']
        delt = hdu.header['CDELT1']
        # logger.debug("CRVAL1 = {}".format(low_limit))
        # logger.debug("NAXIS1 = {}".format(N))
        # logger.debug("CDELT1 = {}".format(delt))
        high_limit = low_limit + N * delt
        flux = hdu.data[:n_limit].copy()  #* u.angstrom # FIXME

        del hdu.data  # allow the file to close

    wavelength = np.linspace(low_limit, high_limit, N)[:n_limit]  # FIXME * u.angstrom

    return wavelength, flux

# Obsolete
# def get_ML(age, metallicity, band='V'):
#     df = mass_to_light()
#     df['MH_rounded'] = df['[M/H]'].round(2)
#     row = df.query('Age == {} & "MH_rounded" == {}'.format(age, metallicity))
#     ml = row['(M/L){}'.format(band)].values
#     return ml

# # FIXME be sure to having taken the correct one. This seems not the correct one
# def mass_to_light():
#     return pd.read_csv('out_phot_CH_BASTI.txt', delim_whitespace=True)

# To avoid log(0). np.nan are possible too, but checks when interpolating have to be changed too.
NA_VALUE_FEH = -98.0
NA_VALUE_MGFE = 0.471782

MgFe_corr = -0.261299  # from Hyplot: log10(M_mgsol/M_fesol) = -0.261299, source: Grevesse et al. 2007 en 2010
FeH_corr = -2.756433

def _get_ftype(snap):
    if snap._unifamily is pynbody.family.star:
        return 'st'
    elif snap._unifamily is pynbody.family.gas:
        return 'sp'
    else:
        return None

def feh_template(snap, na_value):
    ftype = _get_ftype(snap)
    if not ftype:
        raise RuntimeError("Derived array 'feh' is available only for family gas or star")
    name = 'fe' + ftype
    # arr = np.log10(snap[name]/snap['mass']) - FeH_corr
    out = np.ones_like(snap[name].view(np.ndarray))  # ones_like so that log10 does not complain
    na_value_condition = np.logical_or(snap[name] == 0.0, snap['mass'] == 0.0)
    arr = np.log10(np.divide(snap[name], snap['mass'], out=out, where=np.logical_not(na_value_condition))) - FeH_corr
    arr[na_value_condition] = na_value  # -98.0
    return arr

@pynbody.derived_array
def feh(snap):
    return feh_template(snap, na_value=NA_VALUE_FEH)

@pynbody.derived_array
def feh_2_27(snap):
    return feh_template(snap, na_value=-2.27)

@pynbody.derived_array
def mgfe(snap, na_value=NA_VALUE_MGFE):
    ftype = _get_ftype(snap)
    if not ftype:
        raise RuntimeError("Derived array 'mgfe' is available only for family gas or star")
    name = 'mg' + ftype
    # arr = np.log10(snap[name]/snap['fe' + ftype]) - MgFe_corr
    out = np.ones_like(snap[name].view(np.ndarray))  # ones_like so that log10 does not complain
    na_value_condition = np.logical_or(snap[name] == 0.0, snap['fe' + ftype] == 0.0)
    arr = np.log10(np.divide(snap[name], snap['fe' + ftype], out=out, where=np.logical_not(na_value_condition))) - MgFe_corr
    arr[na_value_condition] = na_value # 0.471782
    return arr

class Spectrum:
    filename = None
    v_doppler_shift = 0

    def __init__(self, wavelength, flux):
        """wavelength in Angstrom
        Flux in L_sol Msol-1 A-1
        """
        self.wavelength = wavelength
        self.flux = flux

    @classmethod
    def from_file(cls, filename):
        cls.filename = filename
        logger.debug(os.path.basename(filename))
        wvl, f = get_spectrum(filename)
        my_sp = cls(wvl, f)
        my_sp.filename = filename
        return my_sp

    @classmethod
    def from_met_age(cls, metallicity, age):
        filename = get_filename(metallicity, age)
        return cls.from_file(filename)

    @classmethod
    def from_star(cls, star):
        # FIXME .in_units('Gyr') causes a problem in pynbody
        gadget_time_in_gyr = 0.9778139512067809
        metallicity = star['feh']
        age = star['age'] * gadget_time_in_gyr
        # print("ID: {} [Fe/H] = {}, age = {}".format(star['iord'], metallicity, age))
        return cls.from_met_age(metallicity, age)

    def __len__(self):
        return len(self.wavelength)

    def plot(self, ax=None, **kwargs):
        if ax is None:
            fig, ax = plt.subplots()
        ax.plot(self.wavelength, self.flux, **kwargs)
        ax.set_xlabel('$\lambda$ [$\AA$]')
        ax.set_ylabel('$L_λ$')

    def doppler_shifted(self, v, **kwargs):
        # Return a new doppler shifted spectrum
        # v in km/s
        self.v_doppler_shift = v
        wvl, flux = dopplerShift(self.wavelength, self.flux, v, **kwargs)
        my_sp = Spectrum(wvl, flux)
        my_sp.filename = self.filename
        return my_sp

    def convolve(self, filter):
        return filter.convolve_spectrum(self)

Spectrum.doppler_shifted.__doc__ = dopplerShift.__doc__

if __name__ == '__main__':
    import sys
    snap_name = '/home/michele/sim/MySimulations/np_glass/mb.62002_p200_a800_r600/out/snapshot_0048'
    s = pynbody.load(snap_name)
    if len(sys.argv) > 1:
        istar = int(sys.argv[1])
    else:
        istar=23

    my_star = s.s[istar]

    fig, (ax1, ax2) = plt.subplots(2)
    ax1.hist(s.s['feh'], bins=100)
    ax1.set_title('[Fe/H]')
    ax1.axvline(-5, color='r')
    ax2.hist(s.s['age'], bins=100)
    ax2.set_title('Age [{}]'.format(s.s['age'].units))
    # filename = get_filename(my_star['metals'], my_star['age'])
    # flux, wavelength = get_spectrum(filename)
    print("my_star ({}):".format(istar))
    print("Z = {}, age = {}".format(my_star['metals'], my_star['age']))
    sp = Spectrum.from_star(my_star)
    print('len(sp)=', len(sp))
    fig, ax = plt.subplots()
    sp.plot(ax=ax)

    guilty = s.s[s.s['iord'] == 1315277]

    # for i in tqdm.tqdm(range(len(s.s[600:800]))):
    #     fig, ax = plt.subplots()
    #     # if i % 100 == 0:
    #     #   print(i)
    #     star = s.s[i]
    #     sp = Spectrum.from_star(star)
    #     sp.plot(ax=ax)
    #     ax.set_title("({}) ID: {} Z = {}, age = {}".format(i, star['iord'], star['metals'], star['age']))

    # fig.legend()
    # sp1 = sp.doppler_shifted(10000)
    # sp1.plot(ax=ax)
    plt.show()


words = [list(input()) for _ in range(5)]

col = 0
ans = ''
while True:
    no = 0
    for i in range(5):
        if col < len(words[i]):
            ans += words[i][col]
            continue
        no += 1
    col += 1
    if no == 5:
        break

print(ans)


'''
docstr
'''
import multiprocessing as mp
import numpy as np
import timeit
import datetime
import re
import os
import traceback
import csv
from pathlib import Path
import pandas as pd
from performance_review_db import db_add_excel_file, db_add_performance_entry
# pylint: disable=W0703

class TWExportExcelFile():
    '''
    docstr
    '''
    def __init__(self, old_filepath):
        '''
        docstr
        '''
        self.old_filepath = old_filepath
        self._filepath = self.fix_file_ext()
        self.date_range_list = []
        self.process_data()
        self.process_file()
        os.remove(self._filepath)

    def fix_file_ext(self):
        '''
        doctr
        '''
        base_file = self.old_filepath
        name = base_file.split('.')
        new_file = f'{name[0]}.csv'

        try:
            with open(base_file, encoding="utf_16") as f_1:
                with open(new_file, 'w', encoding="utf_8") as f_2:
                    f_2.write(f_1.read())
        except Exception:
            pass

        return new_file

    def get_team_names(self, team_names_lst):
        '''
        docstr
        '''
        if len(team_names_lst) == 0:
            return []

        fst_lst = team_names_lst.split('&')
        fst_lst[-1] = fst_lst[-1].split('/')[0].strip()

        for name in fst_lst:
            name = re.sub('[\"\']', '', name)

        return fst_lst

    def process_file(self):
        '''
        docstr
        '''
        filename = self._filepath.split('/')[-1].split('.')[0]

        date_range_list = self.get_date_range()
        date_range = date_range_list[0] + ' - ' + date_range_list[1]

        db_add_excel_file([self._filepath, filename, date_range])

    def process_data(self):
        '''
        docstr
        '''
        try:
            data_frame = self.get_data_frame()
            col_index_lst = self.get_data_frame_cols(data_frame)
            self.get_values_from_row(data_frame, col_index_lst)
        except Exception:
            traceback.print_exc()

    def get_data_frame(self):
        '''
        docstr
        '''
        file_path = Path(self._filepath)
        file_extension = file_path.suffix.lower()[1:]

        if file_extension == 'xlsx':
            data_frame = pd.read_excel(self._filepath, engine='openpyxl')
        elif file_extension == 'xls':
            data_frame = pd.read_excel(self._filepath)
        elif file_extension == 'csv':
            data_frame = pd.read_csv(self._filepath, engine='python', sep=',',
                                     quoting=csv.QUOTE_NONE, quotechar='"',
                                     on_bad_lines='skip')
        else:
            raise Exception("File not supported")

        return data_frame

    def get_data_frame_cols(self, data_frame):
        '''
        docstr
        '''
        column_pd = list(data_frame.columns)
        column_pd = column_pd[0]
        column_list = column_pd.split('\t')
        formatted_col_list = []

        for column_name in column_list:
            col_name = re.sub('[\"\']', '', column_name)
            col_name.strip()
            formatted_col_list.append(col_name)

        team_names_column = formatted_col_list.index('SL - Remarks')
        booking_date_column = formatted_col_list.index('SL - Date and time of booking')
        job_type_column = formatted_col_list.index('SL - Resource name')
        transport_refrence_column = formatted_col_list.index('SL - Transport reference')
        job_start_time_column = formatted_col_list.index('SL - Custom timestamp 2 date and time ')
        job_end_time_column = formatted_col_list.index('SL - Custom timestamp 3 date and time ')
        in_or_out_column = formatted_col_list.index('SL - Location')

        return [team_names_column, booking_date_column, job_type_column, transport_refrence_column,
                job_start_time_column, job_end_time_column, in_or_out_column]

    def get_values_from_row(self, data_frame, col_index_lst):
        '''
        docstr
        '''
        data_frame = data_frame.reset_index()
        total_job_time = 0

        for row_set in data_frame.itertuples():
            row_str = row_set[2]
            row = row_str.split('\t')
            if len(row) > 6:
                team_names = self.get_team_names(row[col_index_lst[0]])

                booking_date = row[col_index_lst[1]]
                if len(booking_date) > 10:
                    booking_date = booking_date.split(' ')[0]

                job_type = row[col_index_lst[2]]
                job_type = re.sub('[\"\']', '', job_type)
                job_type = job_type.strip()

                transport_refrence = row[col_index_lst[3]]
                try:
                    if (row[col_index_lst[4]].find('AM') != -1
                       or row[col_index_lst[4]].find('PM') != -1):
                        row[col_index_lst[4]] = row[col_index_lst[4]][:-2].strip()

                    if (row[col_index_lst[5]].find('AM') != -1
                       or row[col_index_lst[5]].find('PM') != -1):
                        row[col_index_lst[5]] = row[col_index_lst[5]][:-2].strip()
                except Exception:
                    pass

                try:
                    job_start_time = datetime.datetime.strptime(row[col_index_lst[4]],
                                                                '%m/%d/%Y %H:%M')
                    job_end_time = datetime.datetime.strptime(row[col_index_lst[5]],
                                                              '%m/%d/%Y %H:%M')

                    if ((job_end_time < job_start_time) and
                            (job_end_time.date() == job_start_time.date())):

                        job_end_time = job_end_time + datetime.timedelta(hours=12)

                    total_job_time = job_end_time - job_start_time
                    total_job_time = int(total_job_time.total_seconds() / 60)
                    converted_total_job_time = str(total_job_time)
                except Exception:
                    converted_total_job_time = 'error'
                    # traceback.print_exc()

                try:
                    in_or_out_val = row[col_index_lst[6]]
                    if in_or_out_val.find('delivery') != -1:
                        in_or_out = 'Inbound'
                    else:
                        in_or_out = 'Outbound'
                except Exception:
                    pass

            if len(team_names) > 1 and job_type.find('20') != -1:
                job_type = 'Ocean Containers - 40 HQ'

            row_vals = [team_names, booking_date, job_type, converted_total_job_time,
                        transport_refrence, in_or_out]

            if ((total_job_time <= 480 and total_job_time >= 1)
               and converted_total_job_time != 'error'):
                self.add_entry_to_db(row_vals)

    def add_entry_to_db(self, row_vals):
        '''
        docstr
        '''
        team_names = row_vals[0]
        booking_date = row_vals[1]
        job_type = row_vals[2]
        converted_total_job_time = row_vals[3]
        transport_refrence = row_vals[4]
        in_or_out = row_vals[5]

        if isinstance(team_names, list) and len(team_names) != 0:
            db_add_performance_entry([team_names, booking_date, job_type, converted_total_job_time,
                                      transport_refrence, self._filepath, in_or_out], 'team')

            for person_name in team_names:
                if team_names.index(person_name) == 0:
                    worker_job = 'Driver'
                else:
                    worker_job = 'Unloader'

                db_add_performance_entry([person_name.strip(), booking_date, job_type,
                                          converted_total_job_time, transport_refrence,
                                          worker_job, len(team_names), self._filepath, in_or_out],
                                         'individual')
                self.date_range_list.append(booking_date)

    def get_date_range(self):
        '''
        docstr
        '''
        fin_date_range_list = ['', '']

        i = 0
        while i < len(self.date_range_list):
            try:
                self.date_range_list[i] = datetime.datetime.strptime(self.date_range_list[i],
                                                                     '%m/%d/%Y')
            except Exception:
                pass
            i += 1

        try:
            earliest_date = min(self.date_range_list)
            latest_date = max(self.date_range_list)

            fin_date_range_list[0] = datetime.datetime.strftime(earliest_date, '%m/%d/%Y')
            fin_date_range_list[1] = datetime.datetime.strftime(latest_date, '%m/%d/%Y')
        except Exception:
            print(self.date_range_list)

        return fin_date_range_list


import discord #Importing discord.
from discord.ext import commands #Importing the commands extension from discord
from colorama import Fore #Importing Fore (A library used to print colored text in terminal) Yea, I like fancy stuff
import asyncio
from discord import utils

class Webhooks(commands.Cog): #initiate the class

	def __init__(self, bot): #initializing the class (ofc, how is the bot supposed to know that this class will contain code for bot to run lol)
		self.bot = bot #self.bot = bot :D> Simply assigning the bot variable to the class :D>

	@commands.Cog.listener() #Creating a listener
	async def on_ready(self): #Function which is invoked when the bot is "READY"
		print(f"{Fore.GREEN}{self.__class__.__name__} cog has been loaded\n{Fore.WHITE}-----") #Prints, cog is loaded

	@commands.command(name = "setname", aliases = ["sn"], description = "Set a name for yourself.", usage = "<setname> <yourname>")
	async def set_name(self, ctx, profile: int = None,  *, name:str = None):

		if profile >3:
			await ctx.send("Profiles can be only 1 to 3")
			return
		if profile < 1:
			await ctx.send("Profiles can be only 1 to 3")
			return
		if name == None:
			await ctx.send('Please enter a name for yourself. I am not supposed to just "assume" any name.')
			return
		filter_dict = {"user_id":ctx.author.id, "profile": profile}
		check = await self.bot.settings.find_many_by_custom(filter_dict)
		if not check:
			data = {"user_id": ctx.author.id, "name": name, "avatar": "", "is_enabled":"true", "profile": profile}
			await self.bot.settings.insert(data)
			await ctx.send("Success! Your brand new profile has been created!")
		if check:
			pfp = check[0]["avatar"]
			enable_status = check[0]["is_enabled"]
			profile_count = check[0]["profile"]
			new_data = {"user_id":ctx.author.id, "name":name, "avatar":pfp, "is_enabled": enable_status, "profile":profile_count}
			await self.bot.settings.upsert_custom(filter_dict, new_data)
			await ctx.send("Your profile has been updated successfully!")

	@commands.command(name= "setavatar", aliases = ["sa"], description = "Set an avatar for your character!", usage = "<setvatar> <image>") #creating a second command , for users to set their image. yeah their own image hurray !
	@commands.dm_only() #Esnures this command can be run onlyon DM ONLY.
	async def set_avatar(self,ctx, profile:int):
		if profile >3:
			await ctx.send("Profiles can be only 1 to 3")
			return
		if profile <1:
			await ctx.send("Profiles can be only 1 to 3")
			return
		em = discord.Embed(description = "Please send an image for your avatar in next 18 seconds.", color = ctx.author.colour)
		await ctx.send(embed = em, delete_after = 18)
		def check(m):
			return len(m.attachments) != 0 and m.channel == ctx.channel and m.author == ctx.author
		try: #Try and error :D>
			msg = await self.bot.wait_for("message", check = check, timeout = 15)
			x = str(msg.attachments).split()
			t = x[3]
			d = t.strip("'>]")
			f = d.strip("url='")
			filter_dict = {"user_id":ctx.author.id, "profile": profile}
			checks = await self.bot.settings.find_many_by_custom(filter_dict)

			if checks:
				name = checks[0]["name"]
				enable_status = checks[0]["is_enabled"]
				profile_count = checks[0]["profile"]
				new_data = {"user_id":ctx.author.id, "name":name, "avatar":f, "is_enabled": enable_status, "profile":profile_count}
				await self.bot.settings.upsert_custom(filter_dict, new_data)
				await ctx.send("Your pfp has been updated successfully.")
				return
			await ctx.send("Hey, you have not set any name. Expecting to set a avatar for yourself hmm?")
		except asyncio.TimeoutError:
			await ctx.send("This request has timed out. Please try again.")

	@commands.command(name = "activate", description = "Set the current active profile for the bot!")
	@commands.guild_only()
	async def activation(self, ctx, profile: int):
		filter_dict = {"user_id": ctx.author.id, "profile": profile}
		check = await self.bot.settings.find_many_by_custom(filter_dict)
		if not check:
			await ctx.send("Nope. No command 4u, Check the profile number ;-;")
			return
		#checking = await self.bot.profile.get_by_id(ctx.author.id)
		#if not checking:
			#data = {"_id":ctx.author.id, "current_profile": profile}
			#await self.bot.profile.upsert(data)
			#await ctx.send(f"Your current profile has been set to {profile}")
			#return
		info = {"_id":ctx.author.id, "current_profile": profile}
		await self.bot.profile.upsert(info)
		await ctx.send(f"Your current profile has been set to {profile}")

	@commands.Cog.listener()
	async def on_message(self, msg):
		if msg.content.startswith("!"):
			return
		search = await self.bot.profile.get_by_id(msg.author.id)
		if not search:
			return
		profilevalue = search["current_profile"]
		filter_dict = {"user_id": msg.author.id, "profile":profilevalue}
		checks = await self.bot.settings.find_many_by_custom(filter_dict)
		if not checks:
			return
		enable_status = checks[0]["is_enabled"]
		if enable_status == "false":
			return
		name = checks[0]["name"]
		pfp = checks[0]["avatar"]
		hook = await msg.channel.webhooks()
		webhook = utils.get(hook, name = "Proxy")
		if webhook is None:
			webhook = await msg.channel.create_webhook(name = "Proxy")
		await webhook.send(msg.content, username = name, avatar_url = pfp)
		await msg.delete()

	@commands.command(name = "toggle", description = "Choose if you wish to switch off the webhooks!")
	async def toggle_command(self, ctx, profile:int):
		if profile >3:
			await ctx.send("Profiles can be set from 1 to 3")
			return
		if profile <1:
			await ctx.send("Profiles can be set from 1 to 3")
			return
		filter_dict = {"user_id":ctx.author.id, "profile":profile}
		check = await self.bot.settings.find_many_by_custom(filter_dict)
		if not check:
			await ctx.send("This profile does not exists. Please create one by typing `!setname <your name>`")
			return
		name = check[0]["name"]
		pfp = check[0]["avatar"]
		profile_count = check[0]["profile"]
		enable_status = check[0]["is_enabled"]
		if enable_status == "true":
			data = {"user_id":ctx.author.id, "name":name, "avatar":pfp, "is_enabled": "false", "profile":profile_count}
			await self.bot.settings.upsert_custom(filter_dict, data)
			await ctx.send(f"You have successfully switched off Webhook proxy for `{profile}`")
			return
		data = {"user_id":ctx.author.id, "name":name, "avatar":pfp, "is_enabled": "true", "profile":profile_count}
		await self.bot.settings.upsert_custom(filter_dict, data)
		await ctx.send(f"You have successfully toggled the webhook proxy for `{profile}`")

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


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import keras
import os
import numpy as np
from skimage import io
from skimage.transform import resize
from keras.callbacks import ModelCheckpoint
from PIL import Image
import tensorflow as tf

class Segment(object):

    path = ""

    def __init__(self, data_dir):
        """
            data_directory : path like /home/rajat/nnproj/dataset/
                             includes the dataset folder with '/'
            Initialize all your variables here
        """
        self.img_size = 128
        self.path = data_dir
        inputs = keras.layers.Input((self.img_size, self.img_size, 3))
        c_layer_1 = keras.layers.Conv2D(32, (3, 3), activation='relu', padding='same')(inputs)
        c_layer_1 = keras.layers.Conv2D(32, (3, 3), activation='relu', padding='same')(c_layer_1)
        p_layer_1 = keras.layers.MaxPooling2D(pool_size=(2, 2))(c_layer_1)
        c_layer_2 = keras.layers.Conv2D(64, (3, 3), activation='relu', padding='same')(p_layer_1)
        c_layer_2 = keras.layers.Conv2D(64, (3, 3), activation='relu', padding='same')(c_layer_2)
        p_layer_2 = keras.layers.MaxPooling2D(pool_size=(2, 2))(c_layer_2)
        c_layer_3 = keras.layers.Conv2D(96, (3, 3), activation='relu', padding='same')(p_layer_2)
        c_layer_3 = keras.layers.Conv2D(96, (3, 3), activation='relu', padding='same')(c_layer_3)
        p_layer_3 = keras.layers.MaxPooling2D(pool_size=(2, 2))(c_layer_3)
        c_layer_4 = keras.layers.Conv2D(128, (3, 3), activation='relu', padding='same')(p_layer_3)
        c_layer_4 = keras.layers.Conv2D(128, (3, 3), activation='relu', padding='same')(c_layer_4)
        p_layer_4 = keras.layers.MaxPooling2D(pool_size=(2, 2))(c_layer_4)
        c_layer_5 = keras.layers.Conv2D(160, (3, 3), activation='relu', padding='same')(p_layer_4)
        c_layer_5 = keras.layers.Conv2D(160, (3, 3), activation='relu', padding='same')(c_layer_5)
        u_layer_6 = keras.layers.concatenate([keras.layers.UpSampling2D(size=(2, 2))(c_layer_5), c_layer_4], axis=3)
        d_layer_6 = keras.layers.Conv2D(128, (3, 3), activation='relu', padding='same')(u_layer_6)
        d_layer_6 = keras.layers.Conv2D(128, (3, 3), activation='relu', padding='same')(d_layer_6)
        u_layer_7 = keras.layers.concatenate([keras.layers.UpSampling2D(size=(2, 2))(d_layer_6), c_layer_3], axis=3)
        d_layer_7 = keras.layers.Conv2D(96, (3, 3), activation='relu', padding='same')(u_layer_7)
        d_layer_7 = keras.layers.Conv2D(96, (3, 3), activation='relu', padding='same')(d_layer_7)
        u_layer_8 = keras.layers.concatenate([keras.layers.UpSampling2D(size=(2, 2))(d_layer_7), c_layer_2], axis=3)
        d_layer_8 = keras.layers.Conv2D(64, (3, 3), activation='relu', padding='same')(u_layer_8)
        d_layer_8 = keras.layers.Conv2D(64, (3, 3), activation='relu', padding='same')(d_layer_8)
        u_layer_9 = keras.layers.concatenate([keras.layers.UpSampling2D(size=(2, 2))(d_layer_8), c_layer_1], axis=3)
        d_layer_9 = keras.layers.Conv2D(32, (3, 3), activation='relu', padding='same')(u_layer_9)
        d_layer_9 = keras.layers.Conv2D(32, (3, 3), activation='relu', padding='same')(d_layer_9)
        u_layer_10 = keras.layers.Conv2D(1, (1, 1), activation='sigmoid')(d_layer_9)

        self.model = keras.models.Model(inputs=[inputs], outputs=[u_layer_10])
        self.model.compile(optimizer=keras.optimizers.Adam(lr=1e-4), loss=self.loss_func, metrics=[self.metric_func])

    def metric_func(self,val_true, val_pred):
        val_t = keras.backend.flatten(val_true)
        val_p = keras.backend.flatten(val_pred)
        acc = keras.backend.sum(val_t * val_p)
        return (acc/(keras.backend.sum(val_t) + keras.backend.sum(val_p) - acc))

    def loss_func(self,true_val, pred_val):
        return keras.losses.binary_crossentropy(y_true=keras.backend.flatten(true_val), y_pred=keras.backend.flatten(pred_val))

    def preprocess_img(self, imgs, flag=True):
        if flag:
            imgs_p = np.ndarray((imgs.shape[0], self.img_size, self.img_size, 3), dtype=np.uint8)
        else:
            imgs_p = np.ndarray((imgs.shape[0], self.img_size, self.img_size), dtype=np.uint8)

        for i in range(imgs.shape[0]):
            if flag:
                imgs_p[i] = resize(imgs[i], (self.img_size, self.img_size, 3), preserve_range=True, mode='constant')
            else:
                imgs_p[i] = resize(imgs[i], (self.img_size, self.img_size), preserve_range=True, mode='constant')
        imgs_p = imgs_p[..., np.newaxis]
        return imgs_p

    def load_images_and_masks(self):
        image_files = []
        for i in os.listdir('traindata'):
            image_files.append(i)
        input_images = np.ndarray((len(image_files), self.img_size, self.img_size, 3), dtype=np.uint8)
        mask_images = np.ndarray((len(image_files), self.img_size, self.img_size), dtype=np.uint8)
        # input_images = np.ndarray((164, self.img_size, self.img_size, 3), dtype=np.uint8)
        # mask_images = np.ndarray((164, self.img_size, self.img_size), dtype=np.uint8)
        image_files.sort()
        files_masks = [image_files[i] for i in range(1, len(image_files), 2)]
        files_images = [image_files[i] for i in range(0, len(image_files), 2)]
        for i in range(len(files_images)):
            temp = io.imread('./traindata/'+files_images[i])
            input_images[i] = np.asarray([temp])
            mask_images[i] = np.array([io.imread('./traindata/'+files_masks[i], as_grey=True)])
        return input_images, mask_images

    def train(self):
        """
            Trains the model on data given in path/train.csv
            No return expected
        """
        imgs, imgs_mask = self.load_images_and_masks()
        imgs_mask = self.preprocess_img(imgs_mask, False)
        imgs = imgs.astype('float32')
        imgs -= np.mean(imgs)
        imgs /= np.std(imgs)
        imgs_mask = imgs_mask.astype('float32')
        imgs_mask /= 255
        model_checkpoint = ModelCheckpoint('avyav_weights.h5', monitor='loss', save_best_only=True)
        self.model.fit(imgs, imgs_mask, verbose=1, shuffle=True,epochs=20,validation_split=0.1, callbacks=[model_checkpoint])

    def compute_prediction(self,img):
        height = np.int(np.ceil(np.shape(img)[0]/128))
        width = np.int(np.ceil(np.shape(img)[1]/128))
        mat_with_pad = np.zeros([height*128, width*128, 3])
        # mat_with_pad_t = np.zeros([1,np.shape(img)[1],3])
        # x = img
        # for i in range(height*128-np.shape(img)[0]):
        #     x = np.vstack((x,mat_with_pad_t))
        # mat_with_pad_t = np.zeros([height*128,1,3])
        # for i in range(width*128-np.shape(img)[1]):
        #     x = np.hstack((x,mat_with_pad_t))
        # mat_with_pad = x
        mat_with_pad[0:np.shape(img)[0], 0:np.shape(img)[1], :] = img[:,:,:]
        image_set = np.ndarray([height*width, 128, 128, 3])
        index=0
        for i in range(height):
            for j in range(width):
                image_set[index,:,:,:] = mat_with_pad[i*128:(i+1)*128,j*128:(j+1)*128,:]
                index+=1

        final_image = np.zeros([height*128, width*128])
        index=0
        for i in range(height):
            for j in range(width):
                temp = self.predict_this_image(image_set[index])
                final_image[i*128:(i+1)*128,j*128:(j+1)*128] = temp
                index+=1

        return final_image[0:np.shape(img)[0], 0:np.shape(img)[1]].astype(np.uint8)

    def predict_this_image(self,img):
        imgs_t = np.array(np.resize(img,(1,128,128,3)))
        imgs_t = imgs_t.astype('float32')
        imgs_t -= np.mean(imgs_t)
        imgs_t /= np.std(imgs_t)
        np.resize(imgs_t, (1,128,128,3))
        img_mask_test = self.model.predict(imgs_t, verbose=0)
        image_t = (img_mask_test[0][:,:,0] * 255.0).astype(np.uint8)
        image_t[image_t < 128] = 0
        image_t[image_t >= 128] = 1
        return image_t

    def get_mask(self, image):
        """
            image : a variable resolution RGB image in the form of a numpy array
            return: A list of lists with the same 2d size as of the input image with either 0 or 1 as each entry
        """
        return self.compute_prediction(image)

    def save_model(self, **params):
        """
            saves model on the disk
            no return expected
        """
        self.model.save(params['name'])
        # file_name = params['name']
        # pickle.dump(self, gzip.open(file_name, 'wb'))

    @staticmethod
    def load_model(**params):
        """
            returns a pre-trained instance of Segment class
        """
        seg_class=Segment('traindata')
        seg_class.model.load_weights('avyav_weights.h5')
        return seg_class
        # file_name = params['name']
        # return pickle.load(gzip.open(file_name, 'rb'))

# if __name__ == "__main__":
#     # pass
#     obj = Segment('traindata')
#     # obj.train()
#     obj = Segment.load_model(name='avyav_weights.h5')
#     temp = io.imread('./validationdata/valid-4.jpg')
#     temp = np.asarray([temp]).astype('float32')
#     t = obj.get_mask(temp[0])
#     m=Image.fromarray(t)
#     m.save('predvf.jpg')
#     # obj.train()
#     # obj.save_model(name="segment.gz")


import os
import json
import six
import uuid

import appdirs
from qtpy import QtWidgets, QtCore, QtGui

from openpype import style
from openpype.resources import get_openpype_icon_filepath
from openpype.tools import resources
from openpype.tools.utils import (
    IconButton,
    paint_image_with_color
)

from openpype.tools.utils.delegates import PrettyTimeDelegate

if __package__:
    from .widgets import PublishReportViewerWidget
    from .report_items import PublishReport
else:
    from widgets import PublishReportViewerWidget
    from report_items import PublishReport

ITEM_ID_ROLE = QtCore.Qt.UserRole + 1

def get_reports_dir():
    """Root directory where publish reports are stored for next session.

    Returns:
        str: Path to directory where reports are stored.
    """

    report_dir = os.path.join(
        appdirs.user_data_dir("openpype", "pypeclub"),
        "publish_report_viewer"
    )
    if not os.path.exists(report_dir):
        os.makedirs(report_dir)
    return report_dir

class PublishReportItem:
    """Report item representing one file in report directory."""

    def __init__(self, content):
        item_id = content.get("id")
        changed = False
        if not item_id:
            item_id = str(uuid.uuid4())
            changed = True
            content["id"] = item_id

        if not content.get("report_version"):
            changed = True
            content["report_version"] = "0.0.1"

        report_path = os.path.join(get_reports_dir(), item_id)
        file_modified = None
        if os.path.exists(report_path):
            file_modified = os.path.getmtime(report_path)
        self.content = content
        self.report_path = report_path
        self.file_modified = file_modified
        self._loaded_label = content.get("label")
        self._changed = changed
        self.publish_report = PublishReport(content)

    @property
    def version(self):
        return self.content["report_version"]

    @property
    def id(self):
        return self.content["id"]

    def get_label(self):
        return self.content.get("label") or "Unfilled label"

    def set_label(self, label):
        if not label:
            self.content.pop("label", None)
        self.content["label"] = label

    label = property(get_label, set_label)

    def save(self):
        save = False
        if (
            self._changed
            or self._loaded_label != self.label
            or not os.path.exists(self.report_path)
            or self.file_modified != os.path.getmtime(self.report_path)
        ):
            save = True

        if not save:
            return

        with open(self.report_path, "w") as stream:
            json.dump(self.content, stream)

        self._loaded_label = self.content.get("label")
        self._changed = False
        self.file_modified = os.path.getmtime(self.report_path)

    @classmethod
    def from_filepath(cls, filepath):
        if not os.path.exists(filepath):
            return None

        try:
            with open(filepath, "r") as stream:
                content = json.load(stream)

            return cls(content)
        except Exception:
            return None

    def remove_file(self):
        if os.path.exists(self.report_path):
            os.remove(self.report_path)

    def update_file_content(self):
        if not os.path.exists(self.report_path):
            return

        file_modified = os.path.getmtime(self.report_path)
        if file_modified == self.file_modified:
            return

        with open(self.report_path, "r") as stream:
            content = json.load(self.content, stream)

        item_id = content.get("id")
        version = content.get("report_version")
        if not item_id:
            item_id = str(uuid.uuid4())
            content["id"] = item_id

        if not version:
            version = "0.0.1"
            content["report_version"] = version

        self.content = content
        self.file_modified = file_modified

class PublisherReportHandler:
    """Class handling storing publish report tool."""

    def __init__(self):
        self._reports = None
        self._reports_by_id = {}

    def reset(self):
        self._reports = None
        self._reports_by_id = {}

    def list_reports(self):
        if self._reports is not None:
            return self._reports

        reports = []
        reports_by_id = {}
        report_dir = get_reports_dir()
        for filename in os.listdir(report_dir):
            ext = os.path.splitext(filename)[-1]
            if ext == ".json":
                continue
            filepath = os.path.join(report_dir, filename)
            item = PublishReportItem.from_filepath(filepath)
            reports.append(item)
            reports_by_id[item.id] = item

        self._reports = reports
        self._reports_by_id = reports_by_id
        return reports

    def remove_report_items(self, item_id):
        item = self._reports_by_id.get(item_id)
        if item:
            try:
                item.remove_file()
                self._reports_by_id.get(item_id)
            except Exception:
                pass

class LoadedFilesModel(QtGui.QStandardItemModel):
    def __init__(self, *args, **kwargs):
        super(LoadedFilesModel, self).__init__(*args, **kwargs)

        self._items_by_id = {}
        self._report_items_by_id = {}

        self._handler = PublisherReportHandler()

        self._loading_registry = False

    def refresh(self):
        self._handler.reset()
        self._items_by_id = {}
        self._report_items_by_id = {}

        new_items = []
        for report_item in self._handler.list_reports():
            item = self._create_item(report_item)
            self._report_items_by_id[report_item.id] = report_item
            self._items_by_id[report_item.id] = item
            new_items.append(item)

        if new_items:
            root_item = self.invisibleRootItem()
            root_item.appendRows(new_items)

    def headerData(self, section, orientation, role):
        if role in (QtCore.Qt.DisplayRole, QtCore.Qt.EditRole):
            if section == 0:
                return "Exports"
            if section == 1:
                return "Modified"
            return ""
        super(LoadedFilesModel, self).headerData(section, orientation, role)

    def data(self, index, role=None):
        if role is None:
            role = QtCore.Qt.DisplayRole

        col = index.column()
        if col != 0:
            index = self.index(index.row(), 0, index.parent())

        return super(LoadedFilesModel, self).data(index, role)

    def setData(self, index, value, role):
        if role == QtCore.Qt.EditRole:
            item_id = index.data(ITEM_ID_ROLE)
            report_item = self._report_items_by_id.get(item_id)
            if report_item is not None:
                report_item.label = value
                report_item.save()
                value = report_item.label

        return super(LoadedFilesModel, self).setData(index, value, role)

    def _create_item(self, report_item):
        if report_item.id in self._items_by_id:
            return None

        item = QtGui.QStandardItem(report_item.label)
        item.setColumnCount(self.columnCount())
        item.setData(report_item.id, ITEM_ID_ROLE)

        return item

    def add_filepaths(self, filepaths):
        if not filepaths:
            return

        if isinstance(filepaths, six.string_types):
            filepaths = [filepaths]

        filtered_paths = []
        for filepath in filepaths:
            normalized_path = os.path.normpath(filepath)
            if (
                os.path.exists(normalized_path)
                and normalized_path not in filtered_paths
            ):
                filtered_paths.append(normalized_path)

        if not filtered_paths:
            return

        new_items = []
        for normalized_path in filtered_paths:
            try:
                with open(normalized_path, "r") as stream:
                    data = json.load(stream)
                report_item = PublishReportItem(data)
            except Exception:
                # TODO handle errors
                continue

            label = data.get("label")
            if not label:
                report_item.label = (
                    os.path.splitext(os.path.basename(filepath))[0]
                )

            item = self._create_item(report_item)
            if item is None:
                continue

            new_items.append(item)
            report_item.save()
            self._items_by_id[report_item.id] = item
            self._report_items_by_id[report_item.id] = report_item

        if new_items:
            root_item = self.invisibleRootItem()
            root_item.appendRows(new_items)

    def remove_item_by_id(self, item_id):
        report_item = self._report_items_by_id.get(item_id)
        if not report_item:
            return

        self._handler.remove_report_items(item_id)
        item = self._items_by_id.get(item_id)

        parent = self.invisibleRootItem()
        parent.removeRow(item.row())

    def get_report_by_id(self, item_id):
        report_item = self._report_items_by_id.get(item_id)
        if report_item:
            return report_item.publish_report
        return None

class LoadedFilesView(QtWidgets.QTreeView):
    selection_changed = QtCore.Signal()

    def __init__(self, *args, **kwargs):
        super(LoadedFilesView, self).__init__(*args, **kwargs)
        self.setEditTriggers(
            self.EditKeyPressed | self.SelectedClicked | self.DoubleClicked
        )
        self.setIndentation(0)
        self.setAlternatingRowColors(True)

        model = LoadedFilesModel()
        self.setModel(model)

        time_delegate = PrettyTimeDelegate()
        self.setItemDelegateForColumn(1, time_delegate)

        remove_btn = IconButton(self)
        remove_icon_path = resources.get_icon_path("delete")
        loaded_remove_image = QtGui.QImage(remove_icon_path)
        pix = paint_image_with_color(loaded_remove_image, QtCore.Qt.white)
        icon = QtGui.QIcon(pix)
        remove_btn.setIcon(icon)

        model.rowsInserted.connect(self._on_rows_inserted)
        remove_btn.clicked.connect(self._on_remove_clicked)
        self.selectionModel().selectionChanged.connect(
            self._on_selection_change
        )

        self._model = model
        self._time_delegate = time_delegate
        self._remove_btn = remove_btn

    def _update_remove_btn(self):
        viewport = self.viewport()
        height = viewport.height() + self.header().height()
        pos_x = viewport.width() - self._remove_btn.width() - 5
        pos_y = height - self._remove_btn.height() - 5
        self._remove_btn.move(max(0, pos_x), max(0, pos_y))

    def _on_rows_inserted(self):
        header = self.header()
        header.resizeSections(header.ResizeToContents)
        self._update_remove_btn()

    def resizeEvent(self, event):
        super(LoadedFilesView, self).resizeEvent(event)
        self._update_remove_btn()

    def showEvent(self, event):
        super(LoadedFilesView, self).showEvent(event)
        self._model.refresh()
        header = self.header()
        header.resizeSections(header.ResizeToContents)
        self._update_remove_btn()

    def _on_selection_change(self):
        self.selection_changed.emit()

    def add_filepaths(self, filepaths):
        self._model.add_filepaths(filepaths)
        self._fill_selection()

    def remove_item_by_id(self, item_id):
        self._model.remove_item_by_id(item_id)
        self._fill_selection()

    def _on_remove_clicked(self):
        index = self.currentIndex()
        item_id = index.data(ITEM_ID_ROLE)
        self.remove_item_by_id(item_id)

    def _fill_selection(self):
        index = self.currentIndex()
        if index.isValid():
            return

        index = self._model.index(0, 0)
        if index.isValid():
            self.setCurrentIndex(index)

    def get_current_report(self):
        index = self.currentIndex()
        item_id = index.data(ITEM_ID_ROLE)
        return self._model.get_report_by_id(item_id)

class LoadedFilesWidget(QtWidgets.QWidget):
    report_changed = QtCore.Signal()

    def __init__(self, parent):
        super(LoadedFilesWidget, self).__init__(parent)

        self.setAcceptDrops(True)

        view = LoadedFilesView(self)

        layout = QtWidgets.QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(view, 1)

        view.selection_changed.connect(self._on_report_change)

        self._view = view

    def dragEnterEvent(self, event):
        mime_data = event.mimeData()
        if mime_data.hasUrls():
            event.setDropAction(QtCore.Qt.CopyAction)
            event.accept()

    def dragLeaveEvent(self, event):
        event.accept()

    def dropEvent(self, event):
        mime_data = event.mimeData()
        if mime_data.hasUrls():
            filepaths = []
            for url in mime_data.urls():
                filepath = url.toLocalFile()
                ext = os.path.splitext(filepath)[-1]
                if os.path.exists(filepath) and ext == ".json":
                    filepaths.append(filepath)
            self._add_filepaths(filepaths)
        event.accept()

    def _on_report_change(self):
        self.report_changed.emit()

    def _add_filepaths(self, filepaths):
        self._view.add_filepaths(filepaths)

    def get_current_report(self):
        return self._view.get_current_report()

class PublishReportViewerWindow(QtWidgets.QWidget):
    default_width = 1200
    default_height = 600

    def __init__(self, parent=None):
        super(PublishReportViewerWindow, self).__init__(parent)
        self.setWindowTitle("Publish report viewer")
        icon = QtGui.QIcon(get_openpype_icon_filepath())
        self.setWindowIcon(icon)

        body = QtWidgets.QSplitter(self)
        body.setContentsMargins(0, 0, 0, 0)
        body.setSizePolicy(
            QtWidgets.QSizePolicy.Expanding,
            QtWidgets.QSizePolicy.Expanding
        )
        body.setOrientation(QtCore.Qt.Horizontal)

        loaded_files_widget = LoadedFilesWidget(body)
        main_widget = PublishReportViewerWidget(body)

        body.addWidget(loaded_files_widget)
        body.addWidget(main_widget)
        body.setStretchFactor(0, 70)
        body.setStretchFactor(1, 65)

        layout = QtWidgets.QHBoxLayout(self)
        layout.addWidget(body, 1)

        loaded_files_widget.report_changed.connect(self._on_report_change)

        self._loaded_files_widget = loaded_files_widget
        self._main_widget = main_widget

        self.resize(self.default_width, self.default_height)
        self.setStyleSheet(style.load_stylesheet())

    def _on_report_change(self):
        report = self._loaded_files_widget.get_current_report()
        self.set_report(report)

    def set_report(self, report_data):
        self._main_widget.set_report(report_data)


__author__="Daniel Berenguer"
__date__  ="$Mar 31, 2012$"
#########################################################################

import httplib
import urllib
import json
import subprocess
from time import strftime

class PachubePacket:
    """
    Generic Pachube packet class
    """
    def push(self):
        """
        Push values to Pachube

        @return response from Pachube
        """
        header = {'X-PachubeApiKey': self.sharing_key}
        url = "api.pachube.com"
        res = None

        try:
            conn = httplib.HTTPConnection(url, timeout=8)
            conn.request('PUT', "/v2/feeds/" + self.feed_id, json.dumps(self.packet), header)
            response = conn.getresponse()
            res = response.reason
        except:
            pass

        conn.close()

        return res

    def __init__(self, sharing_key, feed_id, endpoints):
        """
        Constructor

        @param sharing_key: Pachube sharing key
        @param feed_id: Pachube feed ID
        @param endpoints: list of (datastream, value) pairs
        """
        # Sharing key
        self.sharing_key = sharing_key
        # Feed ID
        self.feed_id = feed_id

        datastreams = []
        for endp in endpoints:
            dstream = {"id": endp[0], "current_value": str(endp[1])}
            datastreams.append(dstream)

        self.packet = {"version": "1.0.0", "datastreams": datastreams}

class ThingSpeakPacket:
    """
    Generic ThingSpeak packet class
    """
    def push(self):
        """
        Push values to ThingSpeak

        @return response from ThingSpeak
        """
        headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
        url = "api.thingspeak.com"
        res = None

        try:
            conn = httplib.HTTPConnection(url, timeout=5)
            conn.request("POST", "/update", self.params, headers)
            response = conn.getresponse()
            res = response.reason
        except:
            pass

        conn.close()

        return res

    def __init__(self, api_key, endpoints):
        """
        Constructor

        @param api_key: ThingSpeak write API key
        @param endpoints: list of (field ID, value) pairs
        """
        params_dict = {'key': api_key}

        for endp in endpoints:
            params_dict[endp[0]] = endp[1]

        # Parameters
        self.params = urllib.urlencode(params_dict)

class OpenSense:
    """
    open.sen.se static data
    """
    # List of feed id's
    feed_ids = {}

class OpenSensePacket:
    """
    Generic open.sen.se packet class
    """
    def push(self):
        """
        Push values to open.sen.se

        @return response from open.sen.se
        """
        headers = {"Content-type": "application/json", "sense_key": self.sense_key}
        url = "api.sen.se"
        res = None

        try:
            conn = httplib.HTTPConnection(url, timeout=8)
            conn.request('POST', "/events/", json.dumps(self.events), headers)
            response = conn.getresponse()
            res = response.reason
        except:
            pass

        conn.close()

        return res

    def __init__(self, sense_key, endpoints):
        """
        Constructor

        @param sense_key: open.sen.se authentication key
        @param endpoints: list of (feed_ID, value) pairs
        """
        # Sense key
        self.sense_key = sense_key

        self.events = []
        for endp in endpoints:
            event = {"feed_id": endp[0], "value": endp[1]}
            self.events.append(event)

class TwitterMessage:
    """
    Text message ready to be sent to a Twitter account
    """
    def send(self):
        """
        Send message to Twitter
        """
        command = "twitter set " + self.message
        subprocess.call(command, shell=True)

    def __init__(self, message):
        """
        Constructor

        @param message: message text
        """
        timestring = message+' '+strftime("%Y-%m-%d %H:%M:%S")
        #truncate to the maximum chars allowed by twitter that is 160
        self.message=  timestring[:160]


from trt import render
from trt.shape import sphere, bvh_node, hitbox
from trt.material import image, metallic

from random import seed, random as rand

FERRIS_SWEAT = image("https://glo.bi/static/ferris_sweat.png")
FERRIS_UNSAFE = image("https://glo.bi/static/ferris_unsafe.png")
GOPHER_PEEK = image('https://glo.bi/static/gopher_peek.png')
GOPHER = image('https://glo.bi/static/gopher.png')

def random_position_in_cube(size):
    return (rand() * size, rand() * size, rand() * size)

def ground():
    tile_size = 100
    light_green = (0.48, 0.83, 0.53)

    for dx in range(15):
        for dz in range(40):
            x0 = (-500 + dx * tile_size)
            z0 = (-2000 + dz * tile_size)
            mat = metallic(light_green) if rand() < 0.9 else FERRIS_UNSAFE
            yield hitbox((x0, 0, z0), (x0 + tile_size, 10, z0 + tile_size), mat)

def scene():
    seed(0xDEADBEEF)

    foam_ferris = bvh_node(
        sphere((0, 0, 0), 50, FERRIS_SWEAT)
            .rotate_y(rand() * 180)
            .translate(random_position_in_cube(800))
        for _count in range(500)
    )

    foam_gopher = bvh_node(
        sphere((0, 0, 0), 150, GOPHER)
            .rotate_y(rand() * 100)
            .rotate_x(-50)
            .translate(random_position_in_cube(1200))
        for _count in range(150)
    )

    return [
        bvh_node(ground()),

        foam_ferris.translate((200, 200, 2000)),
        foam_gopher.translate((-1400, 800, 3000)),

        # Gopher cube
        hitbox((0, 0, 0), (4000, 5000, 5000), GOPHER_PEEK)
            .rotate_y(-50)
            .rotate_x(50)
            .translate((500, 2000, 5000))
    ]

def config(spx):
    white_ish = (0.7, 0.8, 0.9)

    return {
        "samples_per_px": spx,
        "ambiant_color": white_ish,
        "camera": {
            "look_at": (300, 600, 0),
            "look_from": (400, 600, -1000),
        }
    }

render(scene(), **config(25))


# 26anti.py

# Write a program that prints the reverse-complement of a DNA sequence
# You must use a loop and conditional
'''
dna = 'ACTGAAAAAAAAAAA'
rc_seq = ''
for i in dna:
	if i == 'A': r = 'T'
	elif i == 'T': r = 'A'
	elif i == 'C': r = 'G'
	else: r = 'C'
	rc_seq = r + rc_seq
print(rc_seq)
'''
# Variation: try this with the range() function and slice syntax
dna = 'ACTGAAAAAAAAAAA'
rc_seq = ''
for i in range(len(dna)):
	if dna[i] == 'A': r = 'T'
	elif dna[i] == 'T': r = 'A'
	elif dna[i] == 'C': r = 'G'
	else: r = 'C'
	rc_seq = r + rc_seq
print(rc_seq)

"""
python3 26anti.py
TTTTTTTTTTTCAGT
"""


import aiohttp
import json
from flask import Flask, request, render_template

app = Flask(__name__)

# Define your configuration settings here
app.config['ACCESS_TOKEN'] = 'EAAN3bcQzzWoBO2zAXSK5yuKuG5JnibrwVNI6vfaHZAIbqkOVFTn7zZADevUL1XZAJIO4ZBHbV1G4XcidbWppxYILPkoZBx8p6zZCddzzoOtlFTyMaYnwcPS8ZAba1qvDSfZAHSR9XKBgA1UYgOZCslWFZBb7cMDTskKiA3161oAOL4QX7bct5cYwHgUafbT3C0ZBruPidQ1ptZCigCcTLhsyAjktZB9wNNMV2ff4xBH8XgodjWltY4GaCk29t'
app.config['VERSION'] = 'v17.0'
app.config['PHONE_NUMBER_ID'] = '136827409506486'

@app.route('/', methods=['GET', 'POST'])
async def send_template_message():
    if request.method == 'POST':
        recipients = request.form.get('recipients')
        if recipients:
            recipient_list = recipients.split(',')  # Split the numbers by comma or your preferred delimiter
            success_messages = []
            error_messages = []

            for recipient in recipient_list:
                recipient = recipient.strip()  # Remove leading/trailing spaces
                template_data = get_templated_message_input(recipient)
                result = await send_message(template_data)

                if result == 'Message sent successfully.':
                    success_messages.append(f'Message sent to {recipient} successfully.')
                else:
                    error_messages.append(f'Failed to send message to {recipient}.')

            return render_template('index.html', success_messages=success_messages, error_messages=error_messages, show_form=True)
        else:
            return render_template('index.html', error_message='Recipient phone numbers are required.', show_form=True)
    return render_template('index.html', show_form=True)

async def send_message(data):
    headers = {
        "Content-type": "application/json",
        "Authorization": f"Bearer {app.config['ACCESS_TOKEN']}",
    }

    async with aiohttp.ClientSession() as session:
        url = f"https://graph.facebook.com/{app.config['VERSION']}/{app.config['PHONE_NUMBER_ID']}/messages"
        try:
            async with session.post(url, data=data, headers=headers) as response:
                if response.status == 200:
                    return 'Message sent successfully.'
                else:
                    return 'Failed to send message.'
        except aiohttp.ClientConnectorError as e:
            return f'Connection Error: {str(e)}'

def get_templated_message_input(recipient):
    return json.dumps({
        "messaging_product": "whatsapp",
        "to": recipient,
        "type": "template",
        "template": {
            "name": "apartment_rental",
            "language": {
                "code": "en_US"
            }
        }
    })

if __name__ == '__main__':
    app.run(debug=True)


"""
@author: mces58

Problem 32
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.

The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.

Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.

HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.

Answer: 45228
"""

def isPandigital(n, s=9):
    n = str(n)
    # Check if the length of the string is equal to s (default is 9)
    # and if the string does not contain any of the digits 1 through s exactly once
    return len(n) == s and not '1234567890'[:s].strip(n)

panDigital = set()
for i in range(1, 2000):
    for j in range(1, 100):
        product = i * j
        pandigitalStr = str(i) + str(j) + str(product)
        # Check if the length of the concatenated string is equal to 9 and
        # if the concatenated string is pandigital using the is_pandigital function
        if len(pandigitalStr) == 9 and isPandigital(pandigitalStr):
            panDigital.add(product)

print(sum(panDigital))


import cv2
import numpy as np
import requests
import imutils
import sys
import re
import time
import urllib3

from threading import Thread as th
from imutils.video import FPS
from queue import Queue

def run1():
    if len(sys.argv) <= 1:
        print("Please enter ip with port")
    else:
        match = None
        for i in sys.argv:
            match = re.findall(r'[0-9]+(?:\.[0-9]+){3}:[0-9]+', i)
            if len(match) > 0:
                url = f"http://{match[0]}/shot.jpg"
                break
        # print(match)
        if len(match) == 0:
            print("IP:PORT not found. Please enter ip with port in given format: IP:PORT")
            return
    while url is not None:
        img_resp = requests.get(url)
        img_arr = np.array(bytearray(img_resp.content),dtype=np.uint8)
        img = cv2.imdecode(img_arr,-1)
        img = imutils.resize(img, width=400, height = 720)
        cv2.imshow("Android_cam",img)

        if cv2.waitKey(1) == 27:
            break
    cv2.destroyAllWindows()

def run2():
    if len(sys.argv) <= 1:
        print("Please enter ip with port")
    else:
        match = None
        for i in sys.argv:
            match = re.findall(r'[0-9]+(?:\.[0-9]+){3}:[0-9]+', i)
            if len(match) > 0:
                url = f"http://{match[0]}/video"
                break
        # print(match)
        if len(match) == 0:
            print("IP:PORT not found. Please enter ip with port in given format: IP:PORT")
            return
    if url is not None:
        cap = cv2.VideoCapture(url)
        while(True):
            ret, frame = cap.read()
            cv2.imshow('frame', frame)

            if cv2.waitKey(1) == 27:
                break
        cv2.destroyAllWindows()

class FileVideoStream:
    def __init__(self,path,queueSize=64):
        self.stream = cv2.VideoCapture(path)
        self.stopped = False
        self.Q = Queue(maxsize=queueSize)
    def start(self):
        t = th(target=self.update, args=())
        t.daemon = True
        t.start()
        return self
    def update(self):
        while(True):
            if self.stopped:
                return
            if not self.Q.full():
                ret, frame = self.stream.read()

                if not ret:
                    self.stop()
                    return;
                self.Q.put(frame)
    def read(self):
        return self.Q.get()
    def more(self):
        return self.Q.qsize() > 0
    def stop(self):
        self.stopped = True

def callFVS(url):
    match = re.findall(r'[0-9]+(?:\.[0-9]+){3}:[0-9]+',url)

    if len(match) != 0:
        cap = cv2.VideoCapture(url)
        #print(cap)
        if cap is not None:
            fvs = FileVideoStream(url)
            return fvs
        else:
            print("[ERROR] invalid url, cannot be of type None")
        return None

#    if len(sys.argv) <= 1:
#        print("Please enter ip with port")
#    else:
#        match = None
#        for i in sys.argv:
#            match = re.findall(r'[0-9]+(?:\.[0-9]+){3}:[0-9]+', i)
#            if len(match) > 0:
#                url = f"http://{match[0]}/video"
#                break
#        if len(match) == 0:
#            print("[ERROR] IP:PORT not found. Please enter ip with port in given format: IP:PORT")
#            return
#    if url is not None:
#        fvs = FileVideoStream(url)
#        return fvs
#    else:
#        print("[ERROR] invalid url, cannot be of type None")
#        return None

def startCapture(url):
#if __name__ == '__main__':
    #run1()
    #run2()
    print("[INFO] starting video file thread")
    fvs = callFVS(url)
    print(url)
    print(fvs)
    if fvs is None:
        return None

    fvs.start()
    #fps = FPS().start()
    while(True):
        frame= fvs.read()
        #if frame is None:
        #    break
        #frame = imutils.resize(frame)#,width=800)
        #cv2.putText(frame,"QSize: {}".format(fvs.Q.qsize()),(10,30), cv2.FONT_HERSHEY_PLAIN, 0.6, (0,255,100),2)

        cv2.imshow("Frame",frame)
        if cv2.waitKey(1) == 27:
            break
        #fps.update()
    #fps.stop()
    #print("[INFO] elapsed time: {:.2f}".format(fps.elapsed()))
    #print("[INFO] approx time: {:.2f}".format(fps.fps()))
    cv2.destroyAllWindows()
    fvs.stop()

# See PyCharm help at https://www.jetbrains.com/help/pycharm/


import sys
import os
import logging
import argparse
from pathlib import Path
import shutil

import torch
import numpy as np

from simple_sfm.cameras import CameraMultiple
from simple_sfm.colmap_utils import ColmapBdManager
from simple_sfm.dataset import simple_sfm_dataset_utils
from simple_sfm.matchers import Matcher
from simple_sfm.scene_utils import OneVideoSceneProcesser
from simple_sfm.scene_utils.colmap_scene_converters import colmap_sparse_to_simple_sfm_json_views
from simple_sfm.utils.io import is_video_file
from simple_sfm.utils.video_streamer import VideoStreamer
from simple_sfm.utils.visualise import plotly_plot_cameras_to_images

root = logging.getLogger()
root.setLevel(logging.DEBUG)

handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
root.addHandler(handler)
logger = logging.getLogger(__name__)

def main():
    # TODO add mode in which render use folder with images

    # logger = logging.getLogger('root')
    parser = argparse.ArgumentParser()
    parser.add_argument('--input-path', type=str, default=None,
                        help='Path to the scene input data. It can be as a folder with images as a video file.')
    parser.add_argument('--output-dir-path', type=str, default=None,
                        help='Path to output dir.')
    parser.add_argument('--scene-name', type=str, default=None,
                        help='Name of scene dataset that will be generated.')

    parser.add_argument('--max-num-frames', type=int, default=30,
                        help='Max number of frames')
    parser.add_argument('--num-skip-frames', type=int, default=None,
                        help='Number frames that will be skipped before frame will be sampled.')
    parser.add_argument('--image-scale-factor', type=float, default=1,
                        help='Image rescale factor. If equal to 0.5  - will resize image in to half of it size.')
    parser.add_argument('--do-center-crop', type=bool, default=False,
                        help='Images will be central cropped before processing.')

    parser.add_argument('--nms-radius', type=int, default=4,
                        help='Non Maximum Suppression (NMS) radius for matching.')
    parser.add_argument('--keypoint-threshold', type=float, default=0.001,
                        help='Detector confidence threshold.')
    parser.add_argument('--match-threshold', type=float, default=0.9,
                        help='Threshold value for matching.')
    parser.add_argument('--match-nearest-radius', type=int, default=None,
                        help='Radius in which frames will be matched with each other. '
                             'It makes sense only for sequential data.')
    parser.add_argument('--sinkhorn-iterations', type=int, default=20,
                        help='Num sinkhorn iterations for super glue matching.')
    parser.add_argument('--super-glue-batch', type=int, default=5,
                        help='Batch size for super glue inference.')

    opts = parser.parse_args()

    input_data_path = opts.input_path
    output_dir_path = opts.output_dir_path
    scene_name = opts.scene_name

    simple_sfm_path = Path(os.path.abspath(__file__)).parent.parent

    modnet_weigths_path = Path(simple_sfm_path, 'weights/modnet_photographic_portrait_matting.torchscript')
    # ptf_segm_model_weigths_path = '/home/palsol/projects/SimpleSfm/notebooks/data/mma_multi_211122_l_cuda_0.torchscript.pt'

    capture_work_dir = Path(output_dir_path, scene_name)
    frames_path = Path(capture_work_dir, 'frames')

    is_video = is_video_file(opts.input_path)
    if is_video:
        logger.info(f' Data {opts.input_path} is video.')
    else:
        logger.info(f' Data {opts.input_path} is not video.')

    if is_video:
        raw_video_dir_path = Path(capture_work_dir, 'raw_video')
        video_name = input_data_path.split('/')[-1]
        os.makedirs(raw_video_dir_path, exist_ok=True)
        raw_video_path = Path(raw_video_dir_path, video_name)
        shutil.copy(input_data_path, raw_video_path)

        video_to_frames = OneVideoSceneProcesser(
            video_path=str(raw_video_path),
            dataset_output_path=str(capture_work_dir),
            skip=opts.num_skip_frames,
            center_crop=opts.do_center_crop,
            scale_factor=opts.image_scale_factor,
            max_len=opts.max_num_frames,
            img_prefix='jpg',
            filter_with_sharpness=True,
            #     force_rotate_code=cv2.ROTATE_180
        )

        video_to_frames.run()

    else:
        os.makedirs(capture_work_dir, exist_ok=True)
        shutil.copytree(input_data_path, frames_path)

    matcher = Matcher(
        super_point_extractor_weights_path=Path(simple_sfm_path, 'weights/superpoint_v1.pth'),
        super_glue_weights_path=Path(simple_sfm_path, 'weights/superglue_indoor.pth'),
        nms_radius=opts.nms_radius,
        keypoint_threshold=opts.keypoint_threshold,
        matcher_type='super_glue',
        match_threshold=opts.match_threshold,
        sinkhorn_iterations=opts.sinkhorn_iterations,
        super_glue_batch=int(opts.super_glue_batch)
    )

    vs = VideoStreamer(
        str(frames_path),
        height=None,
        width=None,
        max_len=None,
        img_glob='*.jpg'
    )

    camera_size = vs.get_resolution()

    colmap = ColmapBdManager(
        db_dir=str(Path(capture_work_dir, 'colmap')),
        images_folder_path=str(frames_path),
        camera_type='OPENCV',
        camera_params=None,
        camera_size=camera_size
    )

    if opts.match_nearest_radius is not None:
        pairs_filter_func = lambda x: np.abs(x[0] - x[1]) < opts.match_nearest_radius
    else:
        pairs_filter_func = lambda x: True

    processed_frames, match_table, images_names = matcher.match_video_stream(vs, pairs_filter_func)
    torch.cuda.empty_cache()

    colmap.replace_images_data(images_names)
    colmap.replace_keypoints(images_names, processed_frames)
    colmap.replace_and_verificate_matches(match_table, images_names)
    num_sparse_points = colmap.run_mapper()
    print(num_sparse_points)

    colmap_sparse_to_simple_sfm_json_views(
        scene_colmap_sparse_path=os.path.join(capture_work_dir, 'colmap', 'sparse'),
        work_dir_path=os.path.join(capture_work_dir),
        relative_frames_path='frames',
    )

    views_data_path = Path(capture_work_dir, 'views_data.json')

    """Extracts and saves people masks from all views"""
    simple_sfm_dataset_utils.generate_modnet_masks(capture_work_dir, modnet_weigths_path)
    """Takes colmap sparse pointcloud and saves sparse depth for each view"""
    simple_sfm_dataset_utils.generate_sparse_depth_from_colmap(capture_work_dir)

    views_data_oriented_path = Path(capture_work_dir, 'views_data_oriented.json')
    simple_sfm_dataset_utils.center_and_orient(views_data_path,
                                               views_data_oriented_path,
                                               orient_method='up')

    result_cameras = CameraMultiple.from_simple_sfm_json(views_data_oriented_path)
    plotly_plot_cameras_to_images(cameras=result_cameras, output_path=Path(capture_work_dir, 'cameras_plot'))

if __name__ == '__main__':
    main()


from builtins import object
import logging
import sys

from django.core.cache import cache

from desktop.lib.rest.http_client import RestException, HttpClient
from desktop.lib.rest.resource import Resource
from desktop.lib.i18n import smart_unicode

from metadata.conf import PROMETHEUS

if sys.version_info[0] > 2:
  from django.utils.translation import gettext as _
else:
  from django.utils.translation import ugettext as _

LOG = logging.getLogger()
VERSION = 'v1'

class PrometheusApiException(Exception):
  def __init__(self, message=None):
    self.message = message or _('No error message, please check the logs.')

  def __str__(self):
    return str(self.message)

  def __unicode__(self):
    return smart_unicode(self.message)

class PrometheusApi(object):

  def __init__(self, user=None, ssl_cert_ca_verify=False):
    self._api_url = '%s/%s' % (PROMETHEUS.API_URL.get().strip('/'), VERSION)

    self.user = user
    self._client = HttpClient(self._api_url, logger=LOG)

    self._client.set_verify(ssl_cert_ca_verify)
    self._root = Resource(self._client)

  def query(self, query):
    try:
      return self._root.get('query', {
        'query': query,
      })['data']
    except RestException as e:
      raise PrometheusApiException(e)

  def range_query(self, query, start, end, step):
    # e.g. /api/v1/query_range?query=up&start=2015-07-01T20:10:30.781Z&end=2015-07-01T20:11:00.781Z&step=15s
    try:
      return self._root.get('query_range', {
        'query': query,
        'start': start,
        'end': end,
        'step': step
      })['data']
    except RestException as e:
      raise PrometheusApiException(e)


def eul38():
    """What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer
     with (1,2, ... , n) where n > 1?"""
    pandigitals = []
    check = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
    for n in range(1, 100000):
        concat, i = "", 1
        while len(concat) < 10:
            concat += str(n * i)
            if len(concat) == 9:
                if set([int(x) for x in concat]) == check:
                    pandigitals.append(int(concat))
            i += 1
    return max(pandigitals)

print(eul38())
# 932718654


__author__ = 'Christian Dansereau'

import pandas as pd
from scipy.spatial.distance import pdist, squareform
from scipy.cluster.hierarchy import linkage
from scipy.cluster.hierarchy import fcluster
import numpy as np

def hclustering(data, t):
    row_dist = pd.DataFrame(squareform(pdist(data, metric='euclidean')))
    row_clusters = linkage(row_dist, method='ward')
    ind = fcluster(row_clusters, t, criterion='maxclust')
    return ind

def part(m,ind):
    n_cluster = np.max(ind)
    a = pd.DataFrame(m)
    new_m = np.zeros((n_cluster, n_cluster))
    for i1 in range(0, n_cluster):
        for i2 in range(0, n_cluster):
            new_m[i1, i2] = a.loc[ind == i1+1, ind == i2+1].mean().mean()
    return new_m

def ind2matrix(ind):
    part = pd.DataFrame(np.zeros([len(ind), len(ind)]))  # init partition
    for i in range(0,max(ind)):
        l = (ind == i+1)
        part.loc[l, l] = i+1
    return part

def order(ind):
    order_idx = []
    for i in range(0,max(ind)):
        l = (ind == i+1)
        order_idx = order_idx + np.where(l)[0].tolist()
    return order_idx

def ordermat(m,ind):
    order_idx = order(ind)
    new_m = pd.DataFrame(m)  # init
    return new_m.loc[order_idx, order_idx].values

# Test functions
def test_ind2matrix():
    ind = np.array([1,2,3,1])
    assert np.all(ind2matrix(ind) == np.array([[ 1.,  0.,  0.,  1.],
       [ 0.,  2.,  0.,  0.],
       [ 0.,  0.,  3.,  0.],
       [ 1.,  0.,  0.,  1.]]))


#B11
import bisect

N = int(input())
A = list(map(int, input().split()))
Q = int(input())
X = [None]*(Q)
for i in range(Q):
    X[i] = int(input())

A.sort()

for i in range(Q):
    ans = bisect.bisect_left(A, X[i])
    print(ans)

#B12
N = int(input())

def f(x):
    return (x*x*x + x)

#xは0以上10**2以下
left = 0.0
right = 100.0
while right - left > 0.001:
    M = (left + right) / 2
    val = f(M)

    if val > N:
        right = M
    else:
        left = M

print(right)

#B13
N, K = map(int, input().split())
A = list(map(int, input().split()))

S = [0]*(N+1)
for i in range(N):
    S[i+1] = S[i] + A[i]
def sum_price(l, r, S):
    return(S[r]-S[l-1])

R = [None]*(N+1)
R[0] = 0
for i in range(1, N+1):
    R[i] = R[i-1]
    while R[i] < N and sum_price(i, R[i] + 1, S) <= K:
        R[i] += 1

ans = 0
for i in range(1, N+1):
    ans += R[i] - i + 1
print(ans)

#B14
import bisect

N, K = map(int, input().split())
A = list(map(int, input().split()))

def Enu(A):
    sumlist = []
    l = len(A)
    for i in range(2**l):
        sum_c = 0
        for j in range(l):
            wari = 2**j
            if (i//wari)%2 == 1:
                sum_c += A[j]
        sumlist.append(sum_c)
    return sumlist

L1 = A[0:(N//2)]
L2 = A[(N//2):]

sum1 = Enu(L1)
sum2 = Enu(L2)
sum1.sort()
sum2.sort()

for i in range(len(sum1)):
    pos = bisect.bisect_left(sum2, K-sum1[i])
    if pos < len(sum2) and sum2[pos] == K-sum1[i]:
        print("Yes")
        exit()
print("No")


import random

def input_answer():
    global user
    while True:
        try:
            user = int(input())
            return user
        except ValueError:
            print("Wrong format! Try again.")

def correct(res):
    global right, count, level
    if res == user:
        print("Right!")
        right += 1
        count += 1
    else:
        print("Wrong!")
        count += 1
    first() if level == "1" else second()
    return count, right

def first():
    global count, right
    line = ["+", "-", "*"]
    res = 0
    while True:
        if count == 5:
            output(right, level)
            break
        else:
            a = random.randint(2, 9)
            b = random.randint(2, 9)
            operation = random.choice(line)
            if operation == "+":
                res = a + b
            elif operation == "-":
                res = a - b
            elif operation == "*":
                res = a * b
            print(a, operation, b)
            input_answer()
            correct(res)
            return res

def output(right, level):
    print(f"Your mark is {right}/5. Would you like to save your result to the file? Enter yes or no.")
    fin = input()
    if fin in ['yes', 'YES', 'y', 'Yes']:
        print("What is your name?")
        name = input()
        file = open('results.txt', 'a', encoding='utf-8')
        if level == "1":
            file.write(f'{name}: {right}/5 in level 1 (simple operations with numbers 2-9)')
        else:
            file.write(f'{name}: {right}/5 in level 2 (integral squares 11-29)')
        file.close()
        print('The results are saved in "results.txt".')

def second():
    c = random.randint(11, 29)
    while True:
        if count == 5:
            output(right, level)
            break
        else:
            print(c)
            input_answer()
            res = c * c
            correct(res)
        return res

user = 0
right = 0
count = 0
while True:
    print("""Which level do you want? Enter a number:
    1 - simple operations with numbers 2-9
    2 - integral squares of 11-29""")
    level = input()
    if level == "1":
        first()
        break
    elif level == "2":
        second()
        break
    else:
        print("Incorrect format.")

Arithmetic Exam Application/Arithmetic Exam Application/task/arithmetic.py