'''
Created on May 21, 2012

@author: peter
'''

import wx, os, DataReader, HilbertVis
import threading
#from wx.lib.pubsub import Publisher
import time
from rpy2.robjects import r

def scale_bitmap(bitmap, width, height):
    image = wx.ImageFromBitmap(bitmap)
    image = image.Scale(width, height, wx.IMAGE_QUALITY_HIGH)
    image = image.Mirror(False)
    result = wx.BitmapFromImage(image)
    return result

class MyFrame(wx.Frame):
    '''

    '''
    x = 500
    y = 500
    start = True
    def __init__(self, parent, Id, title):

        self._hasDragged = False
        wx.Frame.__init__(self, parent, Id, title, wx.DefaultPosition, wx.Size(1000, 750))
        self.settings = Columns(None, -1,self)

        self.pnl1 = wx.Panel(self, -1, style = wx.SIMPLE_BORDER | wx.TAB_TRAVERSAL)
        self.pnl4 = wx.Panel(self, -1, style = wx.SIMPLE_BORDER |  wx.TAB_TRAVERSAL)
        self.pnl2 = wx.Panel(self, -1, style = wx.SIMPLE_BORDER |  wx.TAB_TRAVERSAL)
        self.pnl5 = wx.Panel(self, -1, style = wx.SIMPLE_BORDER |  wx.TAB_TRAVERSAL)
        self.pnl3 = wx.Panel(self, -1, style = wx.SIMPLE_BORDER | wx.TAB_TRAVERSAL)

        self.SetPosition((150,200))
        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        hbox2 = wx.BoxSizer(wx.HORIZONTAL)
        hbox3 = wx.BoxSizer(wx.HORIZONTAL)
        hbox4 = wx.BoxSizer(wx.HORIZONTAL)

        vbox1 = wx.BoxSizer(wx.VERTICAL)
        vbox2 = wx.BoxSizer(wx.VERTICAL)
        vbox3 = wx.BoxSizer(wx.VERTICAL)
        vbox4 = wx.BoxSizer(wx.VERTICAL)

        self.timer = wx.Timer(self)

        menubar = wx.MenuBar()
        file = wx.Menu()
        help = wx.Menu()
        submenu = wx.Menu()
        submenu.Append(201, 'Save &HTML\tCtrl+H', 'Save information and image to a HTML format')
        submenu.Append(202, 'Save Plain &Text\tCtrl+T', 'Save information to a plain text format')
        file.Append(101, '&Open\tCtrl+O', 'Open a new document')
        file.AppendMenu(102, '&Save', submenu,'Save Menu' )
        file.AppendSeparator()
        self.infomenu = help.Append(301, "&Information\tCtrl+I", 'Show data informnation')
        help.Append(302, "&About\tCtrl+A", 'Show application information')
        quit = wx.MenuItem(file, 105, '&Quit\tCtrl+Q', 'Quit the Application')
        file.AppendItem(quit)
        menubar.Append(file, '&File')
        menubar.Append(help, '&Help')
        self.SetMenuBar(menubar)

        wx.StaticText(self.pnl1,-1,"File:", pos = (5,5))
        self.pnl1filenamectrl = wx.TextCtrl(self.pnl1,-1,"", pos = (5,30),size = (450,-1))
        self.pnl1loadinginfo = wx.StaticText(self.pnl1,-1,"",pos = (5,60))

        #wx.Button(self.pnl1, 2, "show selected coulmuns", pos = (350,2))
        self.generate = wx.Button(self.pnl2,3,"Generate picture", pos = (5,40))
        self.picvalue = wx.ComboBox(self.pnl2, -1,choices = [],pos = (5,5),style = wx.CB_READONLY)
        self.btn = wx.Button(self.pnl2, 4,  "Zoom on", pos = (5,75))

        hbox1.Add(self.pnl1, 1, wx.EXPAND | wx.ALL, 1)
        vbox1.Add(hbox3, 1, wx.EXPAND | wx.ALL, 1)
        vbox1.Add(hbox4, 1, wx.EXPAND | wx.ALL, 1)

        hbox3.Add(self.pnl2, 1, wx.EXPAND | wx.ALL, 1)
        hbox4.Add(self.pnl3, 1, wx.EXPAND | wx.ALL, 1)
        vbox2.Add(self.pnl4, 1, wx.EXPAND | wx.ALL, 1)
        vbox3.Add(self.pnl5, 1, wx.EXPAND | wx.ALL, 1)

        hbox2.Add(vbox1, 2, wx.EXPAND | wx.ALL, 1)
        hbox2.Add(vbox2, 4, wx.EXPAND | wx.ALL, 1)
        hbox2.Add(vbox3, 1, wx.EXPAND | wx.ALL, 1)

        vbox4.Add(hbox1, 1, wx.EXPAND | wx.ALL, 1)
        vbox4.Add(hbox2, 5, wx.EXPAND | wx.ALL, 1)

        self.Bind(wx.EVT_MENU,self.OnQuit, id = 105)
        self.Bind(wx.EVT_MENU,self.OnOpen, id = 101)
        self.Bind(wx.EVT_TIMER, self.UpdateScreen, self.timer)
        self.Bind(wx.EVT_MENU, self.InfoDec, id = 301)
        self.Bind(wx.EVT_BUTTON,self.Columns, id = 1)
        self.Bind(wx.EVT_BUTTON,self.ShowColumns, id = 2)
        self.Bind(wx.EVT_BUTTON,self.Generate, id = 3)
        #self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.btn.Bind(wx.EVT_KEY_DOWN, self.zoom)

        self.infomenu.Enable(0)
        self.generate.Enable(0)
        self.btn.Enable(0)

        self.SetSizer(vbox4)
        vbox4.Fit(self)

        self.pnl1.SetBackgroundColour("light grey")
        self.pnl2.SetBackgroundColour("light grey")
        self.pnl3.SetBackgroundColour("light grey")
        self.pnl4.SetBackgroundColour("light grey")
        self.pnl5.SetBackgroundColour("light grey")
        self.CreateStatusBar()

        self.__infot = wx.StaticText(self.pnl5, -1, "",pos = (5,5))

# Getters and Setters

    def GetColumns(self):
        columns = ["CHROM","POS", "ID", "REF", "ALT", "QUAL", "FILTER", "INFO"]
        return columns

    def GetDir(self):
        return self.__dir

    def GetFile(self):
        return self.__file

    def SetDir(self,dir):
        self.__dir = dir

    def SetFile(self,file):
        self.__file = file

    def GetPath(self):
        return os.path.join(self.__dir,self.__file)

    def GetLoadInfo(self):
        return self.__loadinfo

    def SetLoadInfo(self,loadinfo):
        self.__loadinfo = loadinfo

#Functions

    def zoom(self,e):
        if e.GetKeyCode() == 388 or e.GetKeyCode() == 61:
            self.x += 50
            self.y += 50
            #if self.x > self.largeimagesize[0] or self.y > self.largeimagesize[1]:
            #    self.x = self.largeimagesize[0]
            #    self.y = self.largeimagesize[1]
            self.largeimagesize
            bitmap = scale_bitmap(self.bmp, self.x, self.y)
            self.sbmp.SetBitmap(bitmap)

        elif e.GetKeyCode() == 390 or e.GetKeyCode() == 45:
            self.x -= 50
            self.y -= 50
            #if self.x < self.smallimagesize[0] or self.y < self.smallimagesize[1]:
            #    self.x = self.smallimagesize[0]
            #    self.y = self.smallimagesize[1]
            bitmap = scale_bitmap(self.bmp, self.x, self.y)
            self.sbmp.SetBitmap(bitmap)

        elif e.GetKeyCode() == 316:
            self.sbmp.SetPosition((self.sbmp.GetPosition()[0]-10,self.sbmp.GetPosition()[1]))
            if self.sbmp.GetPosition()[0]+self.sbmp.GetSize()[0]<self.pnl2.GetSize()[0]-1:
                self.sbmp.SetPosition((self.pnl2.GetSize()[0]-self.sbmp.GetSize()[0],self.sbmp.GetPosition()[1]))

        elif e.GetKeyCode() == 314:
            self.sbmp.SetPosition((self.sbmp.GetPosition()[0]+(10),self.sbmp.GetPosition()[1]))
            if self.sbmp.GetPosition()[0]>0:
                self.sbmp.SetPosition((0, self.sbmp.GetPosition()[1]))

        elif e.GetKeyCode() == 315:
            self.sbmp.SetPosition((self.sbmp.GetPosition()[0],self.sbmp.GetPosition()[1]+(10)))
            if self.sbmp.GetPosition()[1]> 0:
                self.sbmp.SetPosition((self.sbmp.GetPosition()[0],10))

        elif e.GetKeyCode() == 317:
            self.sbmp.SetPosition((self.sbmp.GetPosition()[0],self.sbmp.GetPosition()[1]-10))
            if self.sbmp.GetPosition()[1] + self.sbmp.GetSize()[1]<self.pnl2.GetSize()[1]-1:
                self.sbmp.SetPosition((self.sbmp.GetPosition()[0],self.pnl2.GetSize()[1]-self.sbmp.GetSize()[1]))

        self.CalCoor()
        '''

        if event.GetKeyCode() == 388 or event.GetKeyCode() == 61:
            self.dc.Clear()
            self.dc2.Clear()
            W = float(self.img2.GetWidth())
            H = float(self.img2.GetHeight())
            self.img2 = self.img2.Scale(W+5*W/self.img1.GetWidth(),H+5*H/self.img1.GetHeight())
            self.img4 = wx.BitmapFromImage(self.img2)
            self.scaletup += 0.02*1.66
            self.dc2.DrawBitmapPoint( self.img4, (0,0))
            self.dc.DrawBitmapPoint( self.img3, (0,0))
            self.dc.SetPen(wx.Pen(wx.RED, 1))
            self.topline = (self.topline[0], self.topline[1], self.topline[2]-5, self.topline[3])
            self.bottomline = (self.bottomline[0], self.bottomline[1]-5, self.bottomline[2]-5, self.bottomline[3]-5)
            self.leftline = (self.leftline[0], self.leftline[1], self.leftline[2], self.leftline[3]-5)
            self.rightline = (self.rightline[0]-5, self.rightline[1], self.rightline[2]-5, self.rightline[3]-5)
            self.dc.DrawLine(self.topline[0],self.topline[1],self.topline[2],self.topline[3])
            self.dc.DrawLine(self.bottomline[0],self.bottomline[1],self.bottomline[2],self.bottomline[3])
            self.dc.DrawLine(self.leftline[0],self.leftline[1],self.leftline[2],self.leftline[3])
            self.dc.DrawLine(self.rightline[0],self.rightline[1],self.rightline[2],self.rightline[3])

        elif event.GetKeyCode() == 390 or event.GetKeyCode() == 45:
            W = self.img2.GetWidth()
            H = self.img2.GetHeight()
            self.img2 = self.img2.Scale(W-10,H-10)
            self.img4 = wx.BitmapFromImage(self.img2)
            self.dc.Clear()
            self.dc2.Clear()
            self.dc2.DrawBitmapPoint( self.img4, (0,0))
            self.dc.DrawBitmapPoint( self.img3, (0,0))
            self.dc.SetPen(wx.Pen(wx.RED, 1))
            self.topline = (self.topline[0], self.topline[1], self.topline[2]+5, self.topline[3])
            self.bottomline = (self.bottomline[0], self.bottomline[1]+5, self.bottomline[2]+5, self.bottomline[3]+5)
            self.leftline = (self.leftline[0], self.leftline[1], self.leftline[2], self.leftline[3]+5)
            self.rightline = (self.rightline[0]+5, self.rightline[1], self.rightline[2]+5, self.rightline[3]+5)
            self.dc.DrawLine(self.topline[0],self.topline[1],self.topline[2],self.topline[3])
            self.dc.DrawLine(self.bottomline[0],self.bottomline[1],self.bottomline[2],self.bottomline[3])
            self.dc.DrawLine(self.leftline[0],self.leftline[1],self.leftline[2],self.leftline[3])
            self.dc.DrawLine(self.rightline[0],self.rightline[1],self.rightline[2],self.rightline[3])

        elif event.GetKeyCode() == 314 or event.GetKeyCode() == 315 or event.GetKeyCode() == 316 or event.GetKeyCode() == 317:
            if event.GetKeyCode() == 316:
                if self.topline[2]+4 < self.imageCtrl.GetPosition()[0]+self.imageCtrl.GetSize()[0]:
                    self.dc2.Clear()
                    self.dc2.SetUserScale(self.scaletup,self.scaletup)
                    self.picturepos[0]-=10
                    self.dc2.DrawBitmapPoint( self.img4, (self.picturepos[0],self.picturepos[1]))
                    self.dc.Clear()
                    self.dc.DrawBitmapPoint( self.img3, (0,0))
                    self.dc.SetPen(wx.Pen(wx.RED, 1))
                    self.topline = (self.topline[0]+5, self.topline[1], self.topline[2]+5, self.topline[3])
                    self.bottomline = (self.bottomline[0]+5, self.bottomline[1], self.bottomline[2]+5, self.bottomline[3])
                    self.leftline = (self.leftline[0]+5, self.leftline[1], self.leftline[2]+5, self.leftline[3])
                    self.rightline = (self.rightline[0]+5, self.rightline[1], self.rightline[2]+5, self.rightline[3])
                    self.dc.DrawLine(self.topline[0],self.topline[1],self.topline[2],self.topline[3])
                    self.dc.DrawLine(self.bottomline[0],self.bottomline[1],self.bottomline[2],self.bottomline[3])
                    self.dc.DrawLine(self.leftline[0],self.leftline[1],self.leftline[2],self.leftline[3])
                    self.dc.DrawLine(self.rightline[0],self.rightline[1],self.rightline[2],self.rightline[3])

            elif event.GetKeyCode() == 314:
                if self.topline[0]-4 > self.imageCtrl.GetPosition()[0]:
                    self.dc.Clear()
                    self.dc2.Clear()
                    self.picturepos[0]+=10
                    self.dc2.DrawBitmapPoint( self.img4, (self.picturepos[0],self.picturepos[1]))
                    self.dc.DrawBitmapPoint( self.img3, (0,0))
                    self.dc.SetPen(wx.Pen(wx.RED, 1))
                    self.topline = (self.topline[0]-5, self.topline[1], self.topline[2]-5, self.topline[3])
                    self.bottomline = (self.bottomline[0]-5, self.bottomline[1], self.bottomline[2]-5, self.bottomline[3])
                    self.leftline = (self.leftline[0]-5, self.leftline[1], self.leftline[2]-5, self.leftline[3])
                    self.rightline = (self.rightline[0]-5, self.rightline[1], self.rightline[2]-5, self.rightline[3])
                    self.dc.DrawLine(self.topline[0],self.topline[1],self.topline[2],self.topline[3])
                    self.dc.DrawLine(self.bottomline[0],self.bottomline[1],self.bottomline[2],self.bottomline[3])
                    self.dc.DrawLine(self.leftline[0],self.leftline[1],self.leftline[2],self.leftline[3])
                    self.dc.DrawLine(self.rightline[0],self.rightline[1],self.rightline[2],self.rightline[3])
            elif event.GetKeyCode() == 315:
                if self.topline[1]> self.imageCtrl.GetPosition()[1]:
                    self.dc.Clear()
                    self.dc2.Clear()
                    self.picturepos[1]+=10
                    self.dc2.DrawBitmapPoint( self.img4, (self.picturepos[0],self.picturepos[1]))
                    self.dc.DrawBitmapMirrorPoint( self.img3, (0,0))
                    self.dc.SetPen(wx.Pen(wx.RED, 1))
                    self.topline = (self.topline[0], self.topline[1]-5, self.topline[2], self.topline[3]-5)
                    self.bottomline = (self.bottomline[0], self.bottomline[1]-5, self.bottomline[2], self.bottomline[3]-5)
                    self.leftline = (self.leftline[0], self.leftline[1]-5, self.leftline[2], self.leftline[3]-5)
                    self.rightline = (self.rightline[0], self.rightline[1]-5, self.rightline[2], self.rightline[3]-5)
                    self.dc.DrawLine(self.topline[0],self.topline[1],self.topline[2],self.topline[3])
                    self.dc.DrawLine(self.bottomline[0],self.bottomline[1],self.bottomline[2],self.bottomline[3])
                    self.dc.DrawLine(self.leftline[0],self.leftline[1],self.leftline[2],self.leftline[3])
                    self.dc.DrawLine(self.rightline[0],self.rightline[1],self.rightline[2],self.rightline[3])
            elif event.GetKeyCode() == 317:
                if self.bottomline[1] < self.imageCtrl.GetPosition()[1]+self.imageCtrl.GetSize()[1]:
                    self.dc2.Clear()
                    self.picturepos[1]-=10
                    self.dc2.DrawBitmapPoint( self.img4, (self.picturepos[0],self.picturepos[1]))
                    self.dc.Clear()
                    self.dc.DrawBitmapPoint( self.img3, (0,0))
                    self.dc.SetPen(wx.Pen(wx.RED, 1))
                    self.topline = (self.topline[0], self.topline[1]+5, self.topline[2], self.topline[3]+5)
                    self.bottomline = (self.bottomline[0], self.bottomline[1]+5, self.bottomline[2], self.bottomline[3]+5)
                    self.leftline = (self.leftline[0], self.leftline[1]+5, self.leftline[2], self.leftline[3]+5)
                    self.rightline = (self.rightline[0], self.rightline[1]+5, self.rightline[2], self.rightline[3]+5)
                    self.dc.DrawLine(self.topline[0],self.topline[1],self.topline[2],self.topline[3])
                    self.dc.DrawLine(self.bottomline[0],self.bottomline[1],self.bottomline[2],self.bottomline[3])
                    self.dc.DrawLine(self.leftline[0],self.leftline[1],self.leftline[2],self.leftline[3])
                    self.dc.DrawLine(self.rightline[0],self.rightline[1],self.rightline[2],self.rightline[3])

        '''
    def CalCoor(self):
        size = 2**self.__hil.GetSize()
        self.__coorx = []
        pxl = float(self.pnl2.GetSize()[0])/(float(self.pnl2.GetSize()[0])/float(self.sbmp.GetSize()[0])*float(size))
        n = 0
        m = 0
        k = pxl
        for i in range(self.sbmp.GetSize()[0]):
            self.__coorx.append(n)
            m+=1
            if m> k:
                k += pxl
                n+=1
        self.__coory = []
        pxl = float(self.pnl2.GetSize()[1])/(float(self.pnl2.GetSize()[1])/float(self.sbmp.GetSize()[1])*float(size))
        n = 0
        m = 0
        k = pxl
        for i in range(self.sbmp.GetSize()[0]):
            self.__coory.append(n)
            m+=1
            if m> k:
                k += pxl
                n+=1
    '''
    def Zoom(self, event):
        h = self.img2.GetHeight()
        w = self.img2.GetWidth()
        newWidth = int(round(float(w) * self.scale))
        newHeight = int(round(float(h) * self.scale))

        self.img2.Rescale(newWidth, newHeight)
        #self.manageScrollbars(newWidth, newHeight, scale)
        #self.SetScrollbars(10, 10, newWidth/10, newHeight/10)
        self.display2()
    '''
    def Zoom(self,e):
        coor = int(self.coor.GetValue())
        self.x = coor
        self.y = coor
        bitmap = scale_bitmap(self.bmp, coor, coor)
        self.sbmp.SetBitmap(bitmap)
        self.CalCoor()

    def MMove(self,e):
        if self.start:
            self.CalCoor()
            self.start = False
        text = r('''
        hMat[{0},{1}]
        '''.format(self.__coorx[e.GetX()]+1,self.__coory[e.GetY()]+1))
        text = str(text).replace("[1]", ""+":  ")
        self.__infot.SetLabel(str(text))

    '''
    def display2(self):
        if self.img2:
            dc = wx.ClientDC(self)
            self.PrepareDC(dc)
            self.bitmap = self.img2.ConvertToBitmap()
            dc.DrawBitmap(self.bitmap, 0,0)
    '''

    def grabpicture(self,event):
        try:
            self.x = event.GetX()+self.difx
            self.y = event.GetY()+self.dify
        except:
            self.x = event.GetX()
            self.y = event.GetY()

    def info(self,event):
        #self.infotext.SetLabel("X = " + str(event.GetX()) + "\n" + "Y = " + str(event.GetY()))
        text = r('''
        hMat[{0},{1}]
        '''.format())
        self.__infot.SetLabel(str(text))
        #    try:
        #        self.__infot.SetLabel(str(event.GetX()+self.difx)+" - "+str(event.GetY()+self.dify))
        #    except:
        #        self.__infot.SetLabel(str(event.GetX())+" - "+str(event.GetY()))
        if event.LeftIsDown():
            if self._hasDragged:
                self.dc2.Clear()
                self.dc2.DrawBitmapPoint(self.img4, (self.picturepos[0]-self.difx,self.picturepos[1]-self.dify))
            else:
                self._hasDragged= True
            self.difx = self.x-event.GetX()
            self.dify = self.y-event.GetY()

    def InfoDec(self,event):
        description = [[],[]]
        for i in self.__vcf.GetInfoValues():
            description[0].append(i[0])
            description[1].append(i[3])
        self.__helptext = ""
        for i in range(len(description[0])):
            self.__helptext += str(description[0][i]) + " : " + str(description[1][i]) + "\n"
        dlg = wx.MessageDialog(self, self.__helptext, 'Info', wx.OK|wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()

    def ShowColumns(self,event):
        try:
            for i in range(len(self.__infotext)):
                self.__infotext[i].Destroy()
        except:
            pass
        self.__infotext = []
        n = 5
        for i in self.settings.GetSelectedINFO():
            self.__infotext.append(wx.StaticText(self.pnl4,-1,i,pos = (5,n)))
            n += 30

    def Columns(self,event):
        self.settings.INFO(self.__vcf)
        self.settings.Show(1)

    def UpdateScreen(self,event):
        self.pnl1loadinginfo.SetLabel(self.GetLoadInfo())

    def OnQuit(self,event):
        dlg = wx.MessageBox( "Are you sure you want to quit", "Quit",wx.YES_NO | wx.CENTRE | wx.NO_DEFAULT)
        if dlg == wx.YES:
            self.Close()

    def OnOpen(self,event):
        wildcard = "VCF files (*.vcf)|*.vcf"
        dialog = wx.FileDialog(None, "Choose a file",
                               wildcard=wildcard,
                               style=wx.OPEN)
        if dialog.ShowModal() == wx.ID_OK:
            self.SetLoadInfo("VCF file is loading. Please Wait.....")
            path = dialog.GetPath()
            self.SetDir(os.path.dirname(path))
            self.SetFile(os.path.basename(path))
            self.pnl1filenamectrl.SetValue(self.GetFile())
        dialog.Destroy()
        self.__vcf = DataReader.DataReader()
        try:
            self.__vcf.SetPath(self.GetPath())
            self.timer.Start(500)
            LoadVCF(self.__vcf,self)
            self.columnbutton = wx.Button(self.pnl1, 1, "Select columns", pos = (300,60))
            self.columnbutton.Enable(0)
        except AttributeError:
            pass

    def SetupPics(self):
        bmp = wx.Bitmap("temp/HGui.png", wx.BITMAP_TYPE_ANY)
        self.largeimagesize = [bmp.GetHeight(),bmp.GetWidth()]
        self.smallimagesize = [self.largeimagesize[0]/2,self.largeimagesize[1]/2]
        bitmap = scale_bitmap(bmp,self.smallimagesize[0],self.smallimagesize[1])
        self.sbmp = wx.StaticBitmap(self.pnl4, -1, bmp)
        self.sbmp.SetBitmap(bitmap)
        self.sbmp.Bind(wx.EVT_MOTION, self.MMove)
        self.sbmp.Bind(wx.EVT_LEFT_DOWN, self.InfoPrint)
        self.bmp = bmp

    def InfoPrint(self,event):
        text = r('''
        hMat[{0},{1}]
        '''.format(self.__coorx[event.GetX()]+1,self.__coory[event.GetY()]+1))
        dlg = wx.MessageDialog(self, str(text), 'Info', wx.OK|wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()

    '''
    def OnPaint(self,event):
        self.scaletup = 1
        self.picturepos = [0,0]
        self.dc = wx.PaintDC(self.pnl3)
        self.dc2 = wx.PaintDC(self.pnl4)
        self.dc.SetBackground( wx.Brush("light grey"))
        self.dc2.SetBackground(wx.Brush("light grey"))
        self.dc.Clear()
        self.dc2.Clear()
        try:
            self.img4 = wx.BitmapFromImage(self.img2)
            self.img3 = wx.BitmapFromImage(self.img1)
            self.dc.DrawBitmapPoint( self.img3, (0,0))
            self.dc2.DrawBitmapPoint( self.img4, (0,0))
        except:
            pass
        try:
            self.dc.SetPen(wx.Pen(wx.RED, 4))
            self.dc.DrawLine(self.topline[0],self.topline[1],self.topline[2],self.topline[3])
            self.dc.DrawLine(self.bottomline[0],self.bottomline[1],self.bottomline[2],self.bottomline[3])
            self.dc.DrawLine(self.leftline[0],self.leftline[1],self.leftline[2],self.leftline[3])
            self.dc.DrawLine(self.rightline[0],self.rightline[1],self.rightline[2],self.rightline[3])
            self.drawline = 0
        except:
            pass
        event.Skip()
        '''

    def Generate(self,event):
        sel = self.picvalue.GetValue()
        data = []
        for i in self.__vcf.GetINFO():
            data.append(i[sel])
        self.__hil = HilbertVis.Hilbert(data)
        #
        #img = wx.Image("temp/HGui.png")
        #self.imageCtrl = wx.StaticBitmap(self.pnl3, wx.ID_ANY,
        #                                 wx.BitmapFromImage(img),pos = (0,0),size = (self.pnl3.GetSize()[0],self.pnl3.GetSize()[1]))
        #img2 = wx.Image("temp/HGui.png")
        #self.imageCtrl2 = wx.StaticBitmap(self.pnl4, wx.ID_ANY,
        #                                 wx.BitmapFromImage(img2))
        #self.imageCtrl2.Bind(wx.EVT_MOTION,self.info)
        #self.imageCtrl2.Bind(wx.EVT_LEFT_DOWN,self.grabpicture)

        self.SetupPics()
        #self.Refresh()
        self.btn.Enable(1)

class LoadVCF(threading.Thread):
    def __init__(self,vcf,frame):
        threading.Thread.__init__(self)
        super(LoadVCF, self).__init__()
        self.__stop = threading.Event()
        self.__vcf = vcf
        self.__frame = frame
        self.start()

    def run(self):
        self.__vcf.Parser()
        self.__frame.SetLoadInfo("VCF file loading is done!")
        self.__frame.columnbutton.Enable(1)
        self.__frame.infomenu.Enable(1)
        self.__frame.generate.Enable(1)
        time.sleep(1)
        self.__frame.timer.Stop()

class Columns(wx.Dialog):
    def __init__(self, parent,ID, maingui):
        wx.Dialog.__init__(self, parent, ID, "Column Select",size = (950,500),style = wx.CAPTION|wx.CLOSE_BOX|wx.SYSTEM_MENU)
        self.__maingui = maingui

        self.__checks = []
        n=5
        id = 1
        for i in maingui.GetColumns():
            self.__checks.append(wx.CheckBox(self,id,i,pos = (5,n)))
            n += 25
            id += 1
        self.__id = id -1

        wx.Button(self, 100, "Ok", pos = (700,450))

        self.Bind(wx.EVT_CHECKBOX, self.INFOshow, id = self.__id)
        self.Bind(wx.EVT_BUTTON, self.CloseColumns, id = 100)

    def INFO(self,vcf):
        self.__vcf = vcf

    def INFOshow(self,event):
        try:
            for i in range(len(self.__info)):
                self.__info[i].Destroy()
        except:
            pass
        try:
            self.__infotext2.Destroy()
        except:
            pass
        self.__info = []
        description = [[],[]]
        for i in self.__vcf.GetInfoValues():
            description[0].append(i[0])
            description[1].append(i[3])
        n= 35
        m=0
        self.__infotext = wx.StaticText(self,-1,"INFO:", pos = (100,5))
        self.__infolist = []
        for i in self.__vcf.GetINFONames():
            self.__info.append(wx.CheckBox(self,-1,i+":     "+description[1][m],pos = (100,n)))
            self.__infolist.append(i)
            n += 25
            m+=1

    def GetSelectedINFO(self):
        infolist = []
        for i in self.__checks:
            if i.GetValue() == True:
                infolist.append(i.GetLabel())
        try:
            for i in self.__info:
                if i.GetValue() == True:
                    infolist.append(i.GetLabel().split(":")[0])
        except:
            pass
        return infolist

    def CHROM(self,vcf):
        pass

    def CloseColumns(self,event):
        description = [[],[]]
        for i in self.__vcf.GetInfoValues():
            description[0].append(i[0])
            description[1].append(i[2])
        list = []
        for i in range(len(self.GetSelectedINFO())):
            list.append(self.GetSelectedINFO()[i])

            '''
            for m in range(len(description)):
                description[m]
            if self.__vcf.GetInfoType()[n][0] == i:
                if self.__vcf.GetInfoType()[n][2] == "Integer" or self.__vcf.GetInfoType()[n][2] == "Float":
                    list.append(i)
            '''
        self.__maingui.picvalue.SetItems(list)
        self.Show(0)

class MyApp(wx.App):
    '''
    Creates the frame
    :var frame: :class:`MyFrame()`
    '''
    def OnInit(self):
        frame = MyFrame(None, -1, "AMC Programm (Peter Admiraal)")
        frame.Show(True)
        return True

app = MyApp(0)
app.MainLoop()


from scripts.helpful_scripts import get_account, LOCAL_BLOCKCHAINS
from scripts.deploy import deploy_fund_me
from brownie import accounts, exceptions, network

import pytest

def test_can_fund_and_withdraw():

    account = get_account()
    fundMe = deploy_fund_me()
    entranceFee = fundMe.getEntranceFee() + 100

    tx1 = fundMe.fund({'from':account, 'value': entranceFee})
    tx1.wait(1)

    assert fundMe.addressToAmountFunded(account.address) == entranceFee

    tx2 = fundMe.withdraw({'from':account})
    tx2.wait(1)

    assert fundMe.addressToAmountFunded(account.address) == 0

def test_onlyOwner_can_withdraw():

    if(network.show_active() not in LOCAL_BLOCKCHAINS):
        pytest.skip('Only for local testing')

    fundMe = deploy_fund_me()
    badActor = accounts.add()

    with pytest.raises(exceptions.VirtualMachineError):
        fundMe.withdraw({'from':badActor})


"""stock_django URL Configuration

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

urlpatterns = [
    url(r'^$', view.index),
    url(r'^core$', view.core),
    url(r'^info/.*', view.info),
    url(r'^prophetparam', view.add_prophetparam),
    url(r'^setprophetparam', view.set_prophetparam),
    url(r'^xgbparam', view.add_xgbparam),
    url(r'^setxgbparam', view.set_xgbparam),
    url(r'^lstmparam', view.add_lstmparam),
    url(r'^setlstmparam', view.set_lstmparam),
    url(r'^update', view.update),
    url(r'^mark/.*', view.mark),
    url(r'^pe/.*', view.pe),
    url(r'^pb/.*', view.pb),
    url(r'^static/(?P<path>.*)$', static.serve,
      {'document_root': settings.STATIC_ROOT}, name='static'),
]

handler404 = 'stock_django.view.page_not_found'
handler500 = 'stock_django.view.page_error'


"""
사용 예시: python data_augmentation.py --image_dir="path/to/image/directory" --sharpen --gaussian_blur --box_blur
"""
import os
from pathlib import Path

import cv2
from absl import app
from absl import flags

from augmentators.kernel import sharpen, box_blur, guassian_blur
from augmentators.pixel_operator import contrast, brighten
from utils import glob_jpeg_alike

def save_augmented_img(agmt_method, img_path, out_dir, img):
  """
  path/to/img/dir/1/2021-04-29_21538497223.jpg 를
  augmented/1_sharpen/2021-04-29_21538497223_sharpen.jpg 처럼 바꿔서 저장.
  """
  # 해당 augmentation에 대한 폴더 없으면 만들어줌.
  agmt_out_dir = os.path.join(out_dir, img_path.parent.name + f"_{agmt_method}")
  Path(agmt_out_dir).mkdir(parents=True, exist_ok=True)

  new_filename = img_path.stem + f"_{agmt_method}" + img_path.suffix
  out_path = os.path.join(agmt_out_dir, new_filename)
  cv2.imwrite(out_path, img)

def main(_):
  image_dir = Path(flags.FLAGS.image_dir)
  if not image_dir.is_dir():
    print(f"No such directory {image_dir}")
    exit(1)

  out_dir = Path(flags.FLAGS.out_dir)
  out_dir.mkdir(parents=True, exist_ok=True)

  paths = glob_jpeg_alike(image_dir)

  for path in paths:
    img = cv2.imread(str(path))
    if flags.FLAGS.sharpen:
      sharpened_img = sharpen(img)
      save_augmented_img("sharpen", path, out_dir, sharpened_img)
    if flags.FLAGS.box_blur:
      blurred_img = box_blur(img)
      save_augmented_img("box_blurred", path, out_dir, blurred_img)
    if flags.FLAGS.gaussian_blur:
      blurred_img = guassian_blur(img)
      save_augmented_img("gaussian_blurred", path, out_dir, blurred_img)
    if flags.FLAGS.contrast:
      contrasted_img = contrast(img)
      save_augmented_img("contrasted", path, out_dir, contrasted_img)
    if flags.FLAGS.brighten:
      brightened_img = brighten(img)
      save_augmented_img("brightened", path, out_dir, brightened_img)

if __name__ == "__main__":
  flags.DEFINE_string("image_dir", None, "이미지 폴더 경로")
  flags.DEFINE_string("out_dir", "augmented", "이미지 출력 디렉토리")
  flags.DEFINE_boolean("sharpen", False, "sharped filter 적용")
  flags.DEFINE_boolean("box_blur", False, "box blur filter 적용")
  flags.DEFINE_boolean("gaussian_blur", False, "gaussian blur filter 적용")
  flags.DEFINE_boolean("contrast", False, "Contrast 적용")
  flags.DEFINE_boolean("brighten", False, "Brighten 적용")
  flags.mark_flag_as_required('image_dir')
  app.run(main)


import pywhatkit

# Example 1 : send schedule message to number and auto closed the window after 5 second of wait
# enter your mobile number with country code
number = "+92333123456789"
message = "Hello, are you there?"
# pywhatkit.sendwhatmsg(number, message, 23, 8, 30, True, 5)

# Example 2 : send message & image to the number
message = "Image is sending !!!!"
#pywhatkit.sendwhats_image(number, "C:\\Users\\PycharmProjects\\Practice\\hello.jpg", message)

# Example 3 : send schedule message to the group.
# Only Admin can send message to the group, find group link in the whatsapp
# go to invite member then you will find the link like below
#https://chat.whatsapp.com/DnmlBkz111xXRXJaoixjYsQBuX3Y

message = "Hello Guys, Bye"
pywhatkit.sendwhatmsg_to_group("DnmlBkz111xXRXJaoixjYsQBuX3Y", message, 23, 40, 30, True, 5)


from base.custom_requests import CustomRequest
from base.assertions import Assertions
from base.schemas import UsersList, UserSingle

class TestDelay:

    def test_get_delay(self):
        params = {
            'delay': 3
        }
        response = CustomRequest.get('/users', params=params)
        Assertions.assert_code_status(response, 200)
        Assertions.validate_response_body(response, UsersList)


from tkinter import *
import math, random
import os
from tkinter import messagebox
class Billing:
    def __init__(self, manish):
        self.manish = manish
        self.manish.title("Billing Software")
        self.manish.geometry("1355x710+50+30")
        self.manish.resizable(False, False)
        background ="red"
        title1 = Label(self.manish, text="Welcome To Manish Retail Billing", bd= 12, relief= GROOVE,font=("Arial", 30, "bold"),fg="white", bg=background)
        title1.place(x=3,relwidth=1)

        # creating variables call ==========================================================

        self.name = StringVar()
        self.phone = StringVar()
        self.bill = StringVar()
        m = random.randint(1000,9999)
        self.bill.set(str(m))
        self.search = StringVar()

        self.soup = IntVar()
        self.cream = IntVar()
        self.wash = IntVar()
        self.spray = IntVar()
        self.gell = IntVar()
        self.lotion = IntVar()

        self.rice = IntVar()
        self.oil = IntVar()
        self.daal = IntVar()
        self.wheat = IntVar()
        self.sugar = IntVar()
        self.tea = IntVar()

        self.coke = IntVar()
        self.slice = IntVar()
        self.sprite = IntVar()
        self.frooti= IntVar()
        self.maza= IntVar()
        self.litchi= IntVar()

        self.cosmetic = StringVar()
        self.grocery= StringVar()
        self.drinks = StringVar()

        self.cosmetic_tax = StringVar()
        self.grocery_tax = StringVar()
        self.drinks_tax = StringVar()

        # =================================================================*======================================

        f1 = LabelFrame(self.manish, text="Customer details", bd=7, relief= GROOVE, font=("Arial", 15, "bold"),fg="yellow", bg=background)
        f1.place(x=3, y=80,relwidth=1)

        c_name = Label(f1, text= "Customer Name", font=("Arial", 15, "bold",),bg= background, fg= "white")
        c_name.grid(row=0, column=0, padx=20, pady=2)
        e_name = Entry(f1, width= 16, textvariable=self.name, font=("Arial",14), bd=7, relief= RAISED).grid(row=0, column=1, padx= 10, pady=5)

        c_phone = Label(f1, text="Phone No.", font=("Arial", 15, "bold",), bg=background, fg="white")
        c_phone.grid(row=0, column=2, padx=20, pady=2)
        e_phone = Entry(f1, width=16, textvariable=self.phone, font=("Arial", 14), bd=7, relief=RAISED).grid(row=0, column=3, padx=10, pady=5)

        c_bill = Label(f1, text="Bill Number", font=("Arial", 15, "bold",), bg=background, fg="white")
        c_bill.grid(row=0, column=4, padx=20, pady=2)
        e_bill = Entry(f1, width=16, textvariable=self.search, font=("Arial", 14), bd=7, relief=RAISED).grid(row=0, column=5, padx=10, pady=5)

        btn_bill = Button(f1, text="Search", command= self.search_bill, font=("Arial", 10,"bold"),cursor= "hand2", width= 10, bd=7)
        btn_bill.grid(row=0, column= 6, padx=15, pady=8)

        # ============================================================================================================

        f2 = LabelFrame(self.manish, text="Cosmetics", bd=9, relief=GROOVE, font=("Arial", 15, "bold"), fg="yellow", bg=background)
        f2.place(x=3, y=170, width= 325, height= 345)

        name_soup = Label(f2, text= "Soup",font=("Arial", 15, "bold"), bg=background, fg="white")
        name_soup.grid(row=0, column= 0, padx= 10, pady= 10, sticky= "w")
        entry_soup = Entry(f2, width= 15, textvariable=self.soup,font=("Arial", 12, "bold"),bd= 4, relief= SUNKEN).grid(row=0, column=1, padx=10, pady=10)

        name_cream = Label(f2, text="Face Cream", font=("Arial", 15, "bold"), bg=background, fg="white")
        name_cream.grid(row=1, column=0, padx=10, pady=10, sticky="w")
        entry_cream = Entry(f2, width=15, textvariable=self.cream, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=1, column=1, padx=10, pady=10)

        name_wash = Label(f2, text="Face Wash", font=("Arial", 15, "bold"), bg=background, fg="white")
        name_wash.grid(row=2, column=0, padx=10, pady=10, sticky="w")
        entry_wash = Entry(f2, width=15, textvariable=self.wash, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=2, column=1, padx=10, pady=10)

        name_spray = Label(f2, text="Hair Spray", font=("Arial", 15, "bold"), bg=background, fg="white")
        name_spray.grid(row=3, column=0, padx=10, pady=10, sticky="w")
        e_spray = Entry(f2, width=15, textvariable=self.spray, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=3, column=1, padx=10, pady=10)

        name_gell = Label(f2, text="Hair Gell", font=("Arial", 15, "bold"), bg=background, fg="white")
        name_gell.grid(row=4, column=0, padx=10, pady=10, sticky="w")
        e_gell = Entry(f2, width=15, textvariable=self.gell, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=4, column=1, padx=10, pady=10)

        name_lotion = Label(f2, text="Body lotion", font=("Arial", 15, "bold"), bg=background, fg="white")
        name_lotion.grid(row=5, column=0, padx=10, pady=10, sticky="w")
        entry_lotion = Entry(f2, width=15, textvariable=self.lotion, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=5, column=1, padx=10, pady=10)

        # ============================================================================================================

        f3 = LabelFrame(self.manish, text="Grocery", bd=9, relief=GROOVE, font=("Arial", 15, "bold"), fg="yellow", bg=background)
        f3.place(x=333, y=170, width=325, height=345)

        name_rice = Label(f3, text="Rice", font=("Arial", 15, "bold"), bg=background, fg="white")
        name_rice.grid(row=0, column=0, padx=10, pady=10, sticky="w")
        entry_soup = Entry(f3, width=15, textvariable=self.rice, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=0, column=1, padx=10, pady=10)

        name_oil = Label(f3, text="Oil", font=("Arial", 15, "bold"), bg=background, fg="white")
        name_oil.grid(row=1, column=0, padx=10, pady=10, sticky="w")
        entry_oil = Entry(f3, width=15, textvariable=self.oil, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=1, column=1, padx=10, pady=10)

        name_daal = Label(f3, text="Daal", font=("Arial", 15, "bold"), bg=background, fg="white")
        name_daal.grid(row=2, column=0, padx=10, pady=10, sticky="w")
        entry_daal = Entry(f3, width=15, textvariable=self.daal, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=2, column=1, padx=10, pady=10)

        name_wheat = Label(f3, text="Wheat", font=("Arial", 15, "bold"), bg=background, fg="white")
        name_wheat.grid(row=3, column=0, padx=10, pady=10, sticky="w")
        e_wheat = Entry(f3, width=15, textvariable=self.wheat, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=3, column=1, padx=10, pady=10)

        name_sugar = Label(f3, text="Sugar", font=("Arial", 15, "bold"), bg=background, fg="white")
        name_sugar.grid(row=4, column=0, padx=10, pady=10, sticky="w")
        e_sugar = Entry(f3, width=15, textvariable=self.sugar, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=4, column=1, padx=10, pady=10)

        name_tea = Label(f3, text="Tea", font=("Arial", 15, "bold"), bg=background, fg="white")
        name_tea.grid(row=5, column=0, padx=10, pady=10, sticky="w")
        entry_tea = Entry(f3, width=15, textvariable=self.tea, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=5, column=1, padx=10, pady=10)

        # ============================================================================================================

        f4 = LabelFrame(self.manish, text="Cold Drinks", bd=9, relief=GROOVE, font=("Arial", 15, "bold"), fg="yellow", bg=background)
        f4.place(x=663, y=170, width=325, height=345)

        name_coke = Label(f4, text="Coke", font=("Arial", 15, "bold"), bg=background, fg="white")
        name_coke.grid(row=0, column=0, padx=10, pady=10, sticky="w")
        entry_coke = Entry(f4, width=15, textvariable=self.coke, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=0, column=1, padx=10, pady=10)

        name_slice = Label(f4, text="Slice", font=("Arial", 15, "bold"), bg=background, fg="white")
        name_slice.grid(row=1, column=0, padx=10, pady=10, sticky="w")
        entry_slice = Entry(f4, width=15, textvariable=self.slice, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=1, column=1, padx=10, pady=10)

        name_sprite = Label(f4, text="Sprite", font=("Arial", 15, "bold"), bg=background, fg="white")
        name_sprite.grid(row=2, column=0, padx=10, pady=10, sticky="w")
        entry_sprite = Entry(f4, width=15, textvariable=self.sprite, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=2, column=1, padx=10, pady=10)

        name_frooti = Label(f4, text="Frooti", font=("Arial", 15, "bold"), bg=background, fg="white")
        name_frooti.grid(row=3, column=0, padx=10, pady=10, sticky="w")
        e_frooti = Entry(f4, width=15, textvariable=self.frooti, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=3, column=1, padx=10, pady=10)

        name_maza = Label(f4, text="Maza", font=("Arial", 15, "bold"), bg=background, fg="white")
        name_maza.grid(row=4, column=0, padx=10, pady=10, sticky="w")
        entry_maza = Entry(f4, width=15, textvariable=self.maza, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=4, column=1, padx=10, pady=10)

        name_litchi = Label(f4, text="Lichi", font=("Arial", 15, "bold"), bg=background, fg="white")
        name_litchi.grid(row=5, column=0, padx=10, pady=10, sticky="w")
        entry_litchi = Entry(f4, width=15, textvariable=self.litchi, font=("Arial", 12, "bold"), bd=4, relief=SUNKEN).grid(row=5, column=1, padx=10,pady=10)

        # ===========================bill voucher======================================================================

        f5 = LabelFrame(self.manish, bd=9, relief=GROOVE,)
        f5.place(x=1000, y=170, width=345, height=345)
        title2 = Label(f5, text="Bill Voucher", bd=12, relief=GROOVE, font=("Arial", 15, "bold"))
        title2.pack(fill= X)
        scroll_bill = Scrollbar(f5,orient = VERTICAL)
        self.txtarea = Text(f5, yscrollcommand= scroll_bill.set)
        scroll_bill.pack(side= RIGHT, fill=Y)
        scroll_bill.configure(command= self.txtarea.yview)
        self.txtarea.pack(fill= BOTH, expand= 1)

        f6 = LabelFrame(self.manish, text="Bill Menu", bd=8, relief=GROOVE, font=("Arial", 15, "bold"), fg="yellow", bg=background)
        f6.place(x=3, y=520, relwidth=1, height= 180)

        a1_label= Label(f6, text= "Total Cosmetics Price", font=("Arial", 15, "bold"),bg= background,fg="white").grid(row=0,column=0,padx=20,pady=1,sticky="w")
        a1_entry= Entry(f6, width=18, textvariable=self.cosmetic, font=("Arial", 10, "bold"), bd=4, relief=SUNKEN).grid(row=0, column=1, padx=10, pady=1)

        a2_label = Label(f6, text="Total Grocery Price", font=("Arial", 15, "bold"), bg=background, fg="white").grid(row=1, column=0, padx=20, pady=1, sticky="w")
        a2_entry = Entry(f6, width=18, textvariable=self.grocery, font=("Arial", 10, "bold"), bd=4, relief=SUNKEN).grid(row=1, column=1, padx=10, pady=1)

        a3_label = Label(f6, text="Total Cold Drinks Price", font=("Arial", 15, "bold"), bg=background, fg="white").grid(row=2, column=0, padx=20, pady=1, sticky="w")
        a3_entry = Entry(f6, width=18, textvariable=self.drinks, font=("Arial", 10, "bold"), bd=4, relief=SUNKEN).grid(row=2, column=1, padx=10, pady=1)

        b1_label = Label(f6, text="Cosmetics Tax", font=("Arial", 15, "bold"), bg=background, fg="white").grid(row=0, column=2, padx=20, pady=1, sticky="w")
        b1_entry = Entry(f6, width=18, textvariable=self.cosmetic_tax, font=("Arial", 10, "bold"), bd=4, relief=SUNKEN).grid(row=0, column=3, padx=10,pady=1)

        b2_label = Label(f6, text="Grocery Tax", font=("Arial", 15, "bold"), bg=background, fg="white").grid(row=1, column=2, padx=20, pady=1, sticky="w")
        b2_entry = Entry(f6, width=18, textvariable=self.grocery_tax, font=("Arial", 10, "bold"), bd=4, relief=SUNKEN).grid(row=1, column=3, padx=10,pady=1)

        b3_label = Label(f6, text="Cold Drinks Tax", font=("Arial", 15, "bold"), bg=background,fg="white").grid(row=2, column=2, padx=20, pady=1, sticky="w")
        b3_entry = Entry(f6, width=18, textvariable=self.drinks_tax, font=("Arial", 10, "bold"), bd=4, relief=SUNKEN).grid(row=2, column=3, padx=10 ,pady=1)

        fin_frame = Frame(f6, bd=10, relief=GROOVE, )
        fin_frame.place(x=780, y=3, width=560, height=90)

        total_button = Button(fin_frame,text= "Total", command=self.total, bg = "maroon", fg= "white", bd= 5, pady= 5,font=("Arial", 15,"bold"), width=9).grid(row=0, column=0, padx=5, pady= 5)
        total_button = Button(fin_frame,text= "Print Bill", command= self.bill_print, bg = "maroon", fg= "white", bd= 5, pady= 5,font=("Arial", 15,"bold"), width=9).grid(row=0, column=1, padx=5, pady= 5)
        total_button = Button(fin_frame,text= "Clear", command=self.clear_function, bg = "maroon", fg= "white", bd= 5, pady= 5,font=("Arial", 15,"bold"), width=9).grid(row=0, column=2, padx=5, pady= 5)
        total_button = Button(fin_frame,text= "Exit",command=self.exit_system, bg = "maroon", fg= "white", bd= 5, pady= 5,font=("Arial", 15,"bold"), width=9).grid(row=0, column=3, padx=5, pady= 5)

        info = Label(f6, text="If you have any query, please kindly mail me on lawlishsinam03@gmail.com. Thank You!!",
                     bd=8, relief=GROOVE, font=("Arial", 15, "bold"), fg="yellow", bg=background)
        info.place(y=105, relwidth=1)
        self.bill_top()     # to print always, we called inside init function.

    def total(self):
        self.c_s_p = (self.soup.get()* 30)
        self.c_c_p = (self.cream.get()* 120)
        self.c_w_p = (self.wash.get()* 50)
        self.c_sp_p = (self.spray.get()* 200)
        self.c_g_p = (self.gell.get()* 120)
        self.c_l_p = (self.lotion.get()* 160)
        self.total_cosmetic = float (self.c_s_p +
                                self.c_c_p+
                                self.c_w_p+
                                self.c_sp_p+
                                self.c_g_p +
                                self.c_l_p)

        self.cosmetic.set("Rs. " + str(self.total_cosmetic))
        self.c_tax = round((self.total_cosmetic*0.05),2)
        self.cosmetic_tax.set("Rs. " + str(self.c_tax))

        self.g_r_p = (self.rice.get() * 75)
        self.g_o_p = (self.oil.get() * 180)
        self.g_d_p = (self.daal.get() * 60)
        self.g_w_p = (self.wheat.get() * 240)
        self.g_s_p = (self.sugar.get() * 75)
        self.g_t_p = (self.tea.get() * 150)

        self.total_grocery = float (self.g_r_p +
                                self.g_o_p+
                                self.g_d_p+
                                self.g_w_p+
                                self.g_s_p+
                                self.g_t_p)

        self.grocery.set("Rs. " + str(self.total_grocery))
        self.g_tax = round((self.total_grocery * 0.05),2)
        self.grocery_tax.set("Rs. " + str(self.g_tax))

        self.d_c_p = (self.coke.get() * 45)
        self.d_s_p = (self.slice.get() * 50)
        self.d_sp_p = (self.sprite.get() * 45)
        self.d_f_p = (self.frooti.get() * 25)
        self.d_m_p = (self.maza.get() * 60)
        self.d_l_p = (self.litchi.get() * 35)

        self.total_drinks = float (self.d_c_p +
                                self.d_s_p+
                                self.d_sp_p+
                                self.d_f_p+
                                self.d_m_p+
                                self.d_l_p)

        self.drinks.set("Rs. " + str(self.total_drinks))
        self.d_tax = round((self.total_drinks*0.05),2)     # this is done for generating total bill in bill print.
        self.drinks_tax.set("Rs. "+ str(self.d_tax))

        self.total_bill_amount = float( self.total_cosmetic +
                                        self.total_grocery +
                                        self.total_drinks +
                                        self.c_tax+
                                        self. g_tax +
                                        self.d_tax)

    def bill_top(self):
        self.txtarea.delete("1.0", END)
        self.txtarea.insert(END, "\tWelcome to Manish Retails\n")
        self.txtarea.insert(END, f"\nBill Number :{self.bill.get()} ")
        self.txtarea.insert(END, f"\nCustomer Name :{self.name.get()} ")
        self.txtarea.insert(END, f"\nPhone Number : {self.phone.get()}")
        self.txtarea.insert(END, f"\n======================================")
        self.txtarea.insert(END, f"\nProduct\t\tQuantity\t\tPrice")
        self.txtarea.insert(END, f"\n======================================")

    def bill_print(self):

        if self.name.get() =="" or self.phone.get() =="":
            messagebox.showerror("Error","Fill up Customer details")
        elif self.cosmetic.get()=="Rs. 0.0" and self.grocery.get()=="Rs. 0.0" and self.drinks.get()=="Rs. 0.0":
            messagebox.showerror("Error","Nothing is purchased.")
        else:
            # ************************** c ****************************************************************************
            self.bill_top()
            if self.soup.get()!=0:
                self.txtarea.insert(END, f"\nSoap\t\t{self.soup.get()}\t\t{self.c_s_p}")
            if self.cream.get()!=0:
                self.txtarea.insert(END, f"\nFace Cream\t\t{self.cream.get()}\t\t{self.c_c_p}")
            if self.wash.get()!=0:
                self.txtarea.insert(END, f"\nFace Wash\t\t{self.wash.get()}\t\t{self.c_w_p}")
            if self.spray.get()!=0:
                self.txtarea.insert(END, f"\nHair Spray\t\t{self.spray.get()}\t\t{self.c_sp_p}")
            if self.gell.get()!=0:
                self.txtarea.insert(END, f"\nHair Gell\t\t{self.gell.get()}\t\t{self.c_g_p}")
            if self.lotion.get()!=0:
                self.txtarea.insert(END, f"\nBody Lotion \t\t{self.lotion.get()}\t\t{self.c_l_p}")

            # ************************** c ****************************************************************************

            if self.rice.get() != 0:
                self.txtarea.insert(END, f"\nRice\t\t{self.rice.get()}\t\t{self.g_r_p}")
            if self.oil.get() != 0:
                self.txtarea.insert(END, f"\nOil\t\t{self.oil.get()}\t\t{self.g_o_p}")
            if self.daal.get() != 0:
                self.txtarea.insert(END, f"\nDaal\t\t{self.daal.get()}\t\t{self.g_d_p}")
            if self.wheat.get() != 0:
                self.txtarea.insert(END, f"\nWheat\t\t{self.wheat.get()}\t\t{self.g_w_p}")
            if self.sugar.get() != 0:
                self.txtarea.insert(END, f"\nSugar\t\t{self.sugar.get()}\t\t{self.g_s_p}")
            if self.tea.get() != 0:
                self.txtarea.insert(END, f"\nTea\t\t{self.tea.get()}\t\t{self.g_t_p}")

            # ************************** c ****************************************************************************

            if self.coke.get() != 0:
                self.txtarea.insert(END, f"\nCoke\t\t{self.coke.get()}\t\t{self.d_c_p}")
            if self.slice.get() != 0:
                self.txtarea.insert(END, f"\nSlice\t\t{self.slice.get()}\t\t{self.d_s_p}")
            if self.sprite.get() != 0:
                self.txtarea.insert(END, f"\nSprite\t\t{self.sprite.get()}\t\t{self.d_sp_p}")
            if self.frooti.get() != 0:
                self.txtarea.insert(END, f"\nFrooti\t\t{self.frooti.get()}\t\t{self.d_f_p}")
            if self.maza.get() != 0:
                self.txtarea.insert(END, f"\nMaza\t\t{self.maza.get()}\t\t{self.d_m_p}")
            if self.litchi.get() != 0:
                self.txtarea.insert(END, f"\nLitchi\t\t{self.litchi.get()}\t\t{self.d_l_p}")

            self.txtarea.insert(END, f"\n--------------------------------------")

            if self.cosmetic_tax.get()!="Rs. 0.0":
                self.txtarea.insert(END, f"\nCosmetic Tax\t\t\t{self.cosmetic_tax.get()}")
            if self.grocery_tax.get()!="Rs. 0.0":
                self.txtarea.insert(END, f"\nGrocery Tax\t\t\t{self.grocery_tax.get()}")
            if self.drinks_tax.get()!="Rs. 0.0":
                self.txtarea.insert(END, f"\nCold Drinks Tax\t\t\t{self.drinks_tax.get()}")
            self.txtarea.insert(END, f"\n--------------------------------------")
            self.txtarea.insert(END, f"\nTotal Amount: \t\t\tRs. {self.total_bill_amount}")   # final bill in scrollbar.
            self.txtarea.insert(END, f"\n--------------------------------------")
            self.bill_record()

    def bill_record(self):
        op = messagebox.askyesno("Save Bill","Do you want to save bill?")
        if op>0:
            self.bill_data = self.txtarea.get("1.0", END)              # data variable get all data of txtarea.
            ab = open("Bills/" + str(self.bill.get()) + ".txt","w")
            ab.write(self.bill_data)
            ab.close()
            messagebox.showinfo("Saved",f"Bill No. : {self.bill.get()} saved successfully.")
        else:
            return

    def search_bill(self):
        present = "no"
        for value in os.listdir("Bills/"):
            if value.split(".")[0] == self.search.get():
                ab = open(f"Bills/{value}", "r")
                self.txtarea.delete("1.0", END)
                for d in ab:
                    self.txtarea.insert(END, d)
                ab.close()
                present="yes"
        if present=="no":
            messagebox.showerror("Error","Invalid Bill No.")

    def clear_function(self):
        op = messagebox.askyesno("Clear", "Do you really want to clear?")
        if op > 0:
            self.name.set("")
            self.phone.set("")
            self.bill.set("")
            m = random.randint(1000, 9999)
            self.bill.set(str(m))
            self.search.set("")

            self.soup.set(0)
            self.cream.set(0)
            self.wash.set(0)
            self.spray.set(0)
            self.gell.set(0)
            self.lotion.set(0)

            self.rice.set(0)
            self.oil.set(0)
            self.daal.set(0)
            self.wheat.set(0)
            self.sugar.set(0)
            self.tea.set(0)

            self.coke.set(0)
            self.slice.set(0)
            self.sprite.set(0)
            self.frooti.set(0)
            self.maza.set(0)
            self.litchi.set(0)

            self.cosmetic.set("")
            self.grocery.set("")
            self.drinks.set("")

            self.cosmetic_tax.set("")
            self.grocery_tax.set("")
            self.drinks_tax.set("")
            self.bill_top()

    def exit_system(self):
        op = messagebox.askyesno("Exit","Do you really want to exit?")
        if op>0:
            self.manish.destroy()

manish = Tk()
obj = Billing(manish)
manish.mainloop()


import argparse
import torch
import random

def parse_args():
    parser = argparse.ArgumentParser(description="ViewAL")
    parser.add_argument('--backbone', type=str, default='mobilenet',
                        choices=['resnet', 'xception', 'drn', 'mobilenet'],
                        help='backbone name (default: mobilenet)')
    parser.add_argument('--out-stride', type=int, default=16,
                        help='network output stride (default: 16)')
    parser.add_argument('--dataset', type=str, default='scannet-sample',
                        choices=['scannet', 'scenenet-rgbd', 'matterport3d','scannet-sample'],
                        help='dataset name (default: scannet-sample)')
    parser.add_argument('--workers', type=int, default=4,
                        metavar='N', help='dataloader threads')
    parser.add_argument('--base-size', type=str, default="384,512",
                        help='base image size')
    parser.add_argument('--sync-bn', type=bool, default=False,
                        help='whether to use sync bn (default: False)')
    parser.add_argument('--loss-type', type=str, default='ce',
                        choices=['ce', 'focal'],
                        help='loss func type (default: ce)')

    # training hyper params
    parser.add_argument('--epochs', type=int, default=None, metavar='N',
                        help='number of epochs to train (default: auto)')
    parser.add_argument('--batch-size', type=int, default=None,
                        metavar='N', help='input batch size for \
                                training (default: auto)')
    parser.add_argument('--use-balanced-weights', action='store_true', default=False,
                        help='whether to use balanced weights (default: True)')
    # optimizer params
    parser.add_argument('--lr', type=float, default=0.001, metavar='LR',
                        help='learning rate (default: auto)')
    parser.add_argument('--lr-scheduler', type=str, default='step',
                        choices=['step'],
                        help='lr scheduler mode: (default: step)')
    parser.add_argument('--optimizer', type=str, default='SGD', choices=['SGD', 'Adam'])
    parser.add_argument('--step-size', type=str, default='35', help='step size for lr-step-scheduler')
    parser.add_argument('--use-lr-scheduler', default=False, help='use learning rate scheduler', action='store_true')
    parser.add_argument('--momentum', type=float, default=0.9,
                        metavar='M', help='momentum (default: 0.9)')
    parser.add_argument('--weight-decay', type=float, default=5e-4,
                        metavar='M', help='w-decay (default: 5e-4)')
    parser.add_argument('--nesterov', action='store_true', default=False,
                        help='whether use nesterov (default: False)')
    # cuda, seed and logging
    parser.add_argument('--no-cuda', action='store_true', default=False, help='disables CUDA training')
    parser.add_argument('--gpu-ids', type=str, default='0',
                        help='use which gpu to train, must be a \
                        comma-separated list of integers only (default=0)')
    parser.add_argument('--seed', type=int, default=-1, metavar='S',
                        help='random seed (default: -1)')
    # checking point
    parser.add_argument('--checkname', type=str, default=None,
                        help='set the checkpoint name')

    # evaluation option
    parser.add_argument('--eval-interval', type=int, default=5,
                        help='evaluation interval (default: 5) - record metrics every Nth iteration')
    parser.add_argument('--memory-hog', action='store_true', default=False, help='load the whole dataset in RAM if true')
    parser.add_argument('--no-overlap', action='store_true', default=False, help='No overlap check - should be False')
    parser.add_argument('--max-iterations', type=int, default=8, help='max active iterations')
    parser.add_argument('--active-selection-size', type=int, default=1750, help='active selection size')
    parser.add_argument('--region-size', type=int, default=65, help='window size for window region methods')
    parser.add_argument('--region-selection-mode', type=str, default='superpixel', help='use superpixels or windows as region selection mode')
    parser.add_argument('--view-entropy-mode', type=str, default='mc_dropout', choices=['soft', 'vote', 'mc_dropout'], help='probability estimate = softmax or vote or mcdropout')
    parser.add_argument('--active-selection-mode', type=str, default='random',
                        choices=['random', 'viewentropy_region', 'voteentropy_soft', 'voteentropy_region', 'softmax_entropy', 'softmax_confidence', 'softmax_margin', 'coreset', 'voteentropy_max_repr', 'viewmc_kldiv_region', 'ceal'])
    parser.add_argument('--view-prob-aggr', type=str, default='entropy')
    parser.add_argument('--superpixel-dir', type=str, default='superpixel', help='directory for supepixel maps inside the dataset raw root')
    parser.add_argument('--superpixel-coverage-dir', type=str, default='coverage_superpixel', help='directory for coverage maps inside the dataset raw root')
    parser.add_argument('--superpixel-overlap', type=float, default=0.25, help='superpixel overlap threshold')
    parser.add_argument('--start-entropy-threshold', type=float, default=0.005, help='ceal hyperparameter')
    parser.add_argument('--entropy-change-per-selection', type=float, default=0.00033, help='ceal hyperparameter')
    args = parser.parse_args()
    args.cuda = not args.no_cuda and torch.cuda.is_available()
    args.base_size = [int(s) for s in args.base_size.split(',')]
    # manual seeding
    if args.seed == -1:
        args.seed = int(random.random() * 2000)
    print('Using random seed = ', args.seed)
    print('ActiveSelector: ', args.active_selection_mode)
    return args


"""wirecard_python URL Configuration

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

urlpatterns = [

    url(r'^$', BasicApi, name='BasicApi'),
    url(r'^ApiPlus/', ApiPlus, name='ApiPlus'),
    url(r'^ProApi/', ProApi, name='ProApi'),
    url(r'^MarketPlaceDeactiveSubPartner/', MarketPlaceDeactiveSubPartner, name='MarketPlaceDeactiveSubPartner'),
    url(r'^SendInformationSmsService/', SendInformationSmsService, name='SendInformationSmsService'),
    url(r'^SelectSubscriber/', SelectSubscriber, name='SelectSubscriber'),
    url(r'^SelectSubscriberDetail/', SelectSubscriberDetail, name='SelectSubscriberDetail'),
    url(r'^MarketPlaceAddSubPartner/', MarketPlaceAddSubPartner, name='MarketPlaceAddSubPartner'),
    url(r'^MarketPlaceUpdateSubPartner/', MarketPlaceUpdateSubPartner, name='MarketPlaceUpdateSubPartner'),
    url(r'^DeactivateSubscriber/', DeactivateSubscriber, name='DeactivateSubscriber'),
    url(r'^MarketPlaceSale3DSec/', MarketPlaceSale3DSec, name='MarketPlaceSale3DSec'),
    url(r'^MarketPlaceMPSale/', MarketPlaceMPSale, name='MarketPlaceMPSale'),
    url(r'^MarketPlaceReleasePayment/', MarketPlaceReleasePayment, name='MarketPlaceReleasePayment'),
    url(r'^CCProxySale/', CCProxySale, name='CCProxySale'),
    url(r'^CCProxySale3D/', CCProxySale3D, name='CCProxySale3D'),
    url(r'^WDTicketSale3DURLProxy/', WDTicketSale3DURLProxy, name='WDTicketSale3DURLProxy'),
    url(r'^WDTicketSaleURLProxy/', WDTicketSaleURLProxy, name='WDTicketSaleURLProxy'),
    url(r'^TransactionQueryByOrderId/', TransactionQueryByOrderId, name='TransactionQueryByOrderId'),
    url(r'^TransactionQueryByMPAY/', TransactionQueryByMPAY, name='TransactionQueryByMPAY'),

    url(r'^success/', success, name='success'),
    url(r'^fail/', fail, name='fail'),

]


def bfs(x,y):
    que = [(x,y)]
    mp[x][y] = "0"
    while que:
        curx,cury = que.pop(0)
        for a,b in [(curx-1,cury),(curx,cury-1),(curx+1,cury),(curx,cury+1)]:
            if 0<=a<row and 0<=b<col and mp[a][b]=="1":
                mp[a][b]="0"
                que.append((a,b))

mp=[]
try:
    while True:
        mp.append(list(input()))
except EOFError:
    pass
row = len(mp)
col = len(mp[0])
sum = 0
for i in range(row):
    for j in range(col):
        if mp[i][j]=="1":
            bfs(i,j)
            sum+=1
print(sum)


def ju(x,b):
    while x>1:
        judge=0
        for i in range(0, len(b)):
            if x % b[i] == 0:
                x = x // b[i]
                judge=1
        if judge==0:
            break
    if x==1:
        return True
    else:
        return False
a=int(input())
bb=str(input()).split(",")
b=[]
for i in bb:
    b.append(int(i))
count=0
x=1
while not count==a:
    if ju(x,b):
        count=count+1
    x=x+1
print(x-1)


import os
from pathlib import Path

import click
from config_file import ConfigFile

def module_path(path: str) -> Path:
    """
    Finds the absolute path of a file relative to the stb package.

    Args:
        path: The path of the file you're looking for, starting from root.

    Returns:
        The absolute path of the file
    """
    return Path.joinpath(Path(__file__).parent, path).resolve()

STB_CONFIG_FILE_ENV_VAR = os.environ.get("STB_CONFIG_FILE_PATH")
STB_USER_CONFIG_FOLDER = Path("~/.stb/").expanduser()
STB_USER_CONFIG_FILE = Path("~/.stb/config.toml").expanduser()
STB_INTERNAL_CONFIG_FILE = module_path("config/config.original.toml")

def get_config_file() -> ConfigFile:
    """
    Retrieve the path to the configuration file.

    Retrieved in the following order:
      * The STB_CONFIG_FILE_PATH enviroment variable if it exists.
      * User configuration file at ~/.stb/config.toml if it exists.
      * The default configuration file in the stb module.

    Returns:
        A ConfigFile for that path that was found first in the search heirarchy.
    """
    search_hierarchy = [
        STB_CONFIG_FILE_ENV_VAR,
        STB_USER_CONFIG_FILE if STB_USER_CONFIG_FILE.exists() else None,
        STB_INTERNAL_CONFIG_FILE,
    ]

    for path in search_hierarchy:
        if path:
            return ConfigFile(path)

def exit_with_error_output(error):
    """
    Exits the program with an exit status of 1 and
    prints out the error message in a red color.

    :param error: The error that occurred. This could be
        a string or anything that can be converted to a string.
    """
    click.secho(str(error), fg="red")
    exit(1)


from PIL import Image
from sklearn.model_selection import train_test_split
import tensorflow as tf
import numpy as np
from keras.utils.vis_utils import plot_model
from matplotlib import image
from matplotlib import pyplot as plt
import os
import time
import tensorflow as tf
from tensorflow import keras
tf.config.run_functions_eagerly(True)

# The batch size we'll use for training
batch_size = 64

# Size of the image required to train our model
img_size = 120

# These many images will be used from the data archive
dataset_split = 2500

master_dir = 'data'
x = []
y = []
for image_file in os.listdir( master_dir )[ 0 : dataset_split ]:
    rgb_image = Image.open( os.path.join( master_dir , image_file ) ).resize( ( img_size , img_size ) )
    # Normalize the RGB image array
    rgb_img_array = (np.asarray( rgb_image ) ) / 255
    gray_image = rgb_image.convert( 'L' )
    # Normalize the grayscale image array
    gray_img_array = ( np.asarray( gray_image ).reshape( ( img_size , img_size , 1 ) ) ) / 255
    # Append both the image arrays
    x.append( gray_img_array )
    y.append( rgb_img_array )

# Train-test splitting
train_x, test_x, train_y, test_y = train_test_split( np.array(x) , np.array(y) , test_size=0.1 )

# Construct tf.data.Dataset object
dataset = tf.data.Dataset.from_tensor_slices( ( train_x , train_y ) )
dataset = dataset.batch( batch_size )

def get_generator_model():

    inputs = tf.keras.layers.Input( shape=( img_size , img_size , 1 ) )

    conv1 = tf.keras.layers.Conv2D( 16 , kernel_size=( 5 , 5 ) , strides=1 )( inputs )
    conv1 = tf.keras.layers.LeakyReLU()( conv1 )
    conv1 = tf.keras.layers.Conv2D( 32 , kernel_size=( 3 , 3 ) , strides=1)( conv1 )
    conv1 = tf.keras.layers.LeakyReLU()( conv1 )
    conv1 = tf.keras.layers.Conv2D( 32 , kernel_size=( 3 , 3 ) , strides=1)( conv1 )
    conv1 = tf.keras.layers.LeakyReLU()( conv1 )

    conv2 = tf.keras.layers.Conv2D( 32 , kernel_size=( 5 , 5 ) , strides=1)( conv1 )
    conv2 = tf.keras.layers.LeakyReLU()( conv2 )
    conv2 = tf.keras.layers.Conv2D( 64 , kernel_size=( 3 , 3 ) , strides=1 )( conv2 )
    conv2 = tf.keras.layers.LeakyReLU()( conv2 )
    conv2 = tf.keras.layers.Conv2D( 64 , kernel_size=( 3 , 3 ) , strides=1 )( conv2 )
    conv2 = tf.keras.layers.LeakyReLU()( conv2 )

    conv3 = tf.keras.layers.Conv2D( 64 , kernel_size=( 5 , 5 ) , strides=1 )( conv2 )
    conv3 = tf.keras.layers.LeakyReLU()( conv3 )
    conv3 = tf.keras.layers.Conv2D( 128 , kernel_size=( 3 , 3 ) , strides=1 )( conv3 )
    conv3 = tf.keras.layers.LeakyReLU()( conv3 )
    conv3 = tf.keras.layers.Conv2D( 128 , kernel_size=( 3 , 3 ) , strides=1 )( conv3 )
    conv3 = tf.keras.layers.LeakyReLU()( conv3 )

    bottleneck = tf.keras.layers.Conv2D( 128 , kernel_size=( 3 , 3 ) , strides=1 , activation='tanh' , padding='same' )( conv3 )

    concat_1 = tf.keras.layers.Concatenate()( [ bottleneck , conv3 ] )
    conv_up_3 = tf.keras.layers.Conv2DTranspose( 128 , kernel_size=( 3 , 3 ) , strides=1 , activation='relu' )( concat_1 )
    conv_up_3 = tf.keras.layers.Conv2DTranspose( 128 , kernel_size=( 3 , 3 ) , strides=1 , activation='relu' )( conv_up_3 )
    conv_up_3 = tf.keras.layers.Conv2DTranspose( 64 , kernel_size=( 5 , 5 ) , strides=1 , activation='relu' )( conv_up_3 )

    concat_2 = tf.keras.layers.Concatenate()( [ conv_up_3 , conv2 ] )
    conv_up_2 = tf.keras.layers.Conv2DTranspose( 64 , kernel_size=( 3 , 3 ) , strides=1 , activation='relu' )( concat_2 )
    conv_up_2 = tf.keras.layers.Conv2DTranspose( 64 , kernel_size=( 3 , 3 ) , strides=1 , activation='relu' )( conv_up_2 )
    conv_up_2 = tf.keras.layers.Conv2DTranspose( 32 , kernel_size=( 5 , 5 ) , strides=1 , activation='relu' )( conv_up_2 )

    concat_3 = tf.keras.layers.Concatenate()( [ conv_up_2 , conv1 ] )
    conv_up_1 = tf.keras.layers.Conv2DTranspose( 32 , kernel_size=( 3 , 3 ) , strides=1 , activation='relu')( concat_3 )
    conv_up_1 = tf.keras.layers.Conv2DTranspose( 32 , kernel_size=( 3 , 3 ) , strides=1 , activation='relu')( conv_up_1 )
    conv_up_1 = tf.keras.layers.Conv2DTranspose( 3 , kernel_size=( 5 , 5 ) , strides=1 , activation='relu')( conv_up_1 )

    model = tf.keras.models.Model( inputs , conv_up_1 )
    return model

def get_discriminator_model():
    layers = [
        tf.keras.layers.Conv2D( 32 , kernel_size=( 7 , 7 ) , strides=1 , activation='relu' , input_shape=( 120 , 120 , 3 ) ),
        tf.keras.layers.Conv2D( 32 , kernel_size=( 7, 7 ) , strides=1, activation='relu'  ),
        tf.keras.layers.MaxPooling2D(),
        tf.keras.layers.Conv2D( 64 , kernel_size=( 5 , 5 ) , strides=1, activation='relu'  ),
        tf.keras.layers.Conv2D( 64 , kernel_size=( 5 , 5 ) , strides=1, activation='relu'  ),
        tf.keras.layers.MaxPooling2D(),
        tf.keras.layers.Conv2D( 128 , kernel_size=( 3 , 3 ) , strides=1, activation='relu'  ),
        tf.keras.layers.Conv2D( 128 , kernel_size=( 3 , 3 ) , strides=1, activation='relu'  ),
        tf.keras.layers.MaxPooling2D(),
        tf.keras.layers.Conv2D( 256 , kernel_size=( 3 , 3 ) , strides=1, activation='relu'  ),
        tf.keras.layers.Conv2D( 256 , kernel_size=( 3 , 3 ) , strides=1, activation='relu'  ),
        tf.keras.layers.MaxPooling2D(),
        tf.keras.layers.Flatten(),
        tf.keras.layers.Dense( 512, activation='relu'  )  ,
        tf.keras.layers.Dense( 128 , activation='relu' ) ,
        tf.keras.layers.Dense( 16 , activation='relu' ) ,
        tf.keras.layers.Dense( 1 , activation='sigmoid' )
    ]
    model = tf.keras.models.Sequential( layers )
    return model

cross_entropy = tf.keras.losses.BinaryCrossentropy()
mse = tf.keras.losses.MeanSquaredError()

def discriminator_loss(real_output, fake_output):
    real_loss = cross_entropy(tf.ones_like(real_output) - tf.random.uniform( shape=real_output.shape , maxval=0.1 ) , real_output)
    fake_loss = cross_entropy(tf.zeros_like(fake_output) + tf.random.uniform( shape=fake_output.shape , maxval=0.1  ) , fake_output)
    total_loss = real_loss + fake_loss
    return total_loss

def generator_loss(fake_output , real_y):
    real_y = tf.cast( real_y , 'float32' )
    return mse( fake_output , real_y )

generator_optimizer = tf.keras.optimizers.Adam( 0.0005 )
discriminator_optimizer = tf.keras.optimizers.Adam( 0.0005 )

generator = get_generator_model()
discriminator = get_discriminator_model()

@tf.function
def train_step(input_x, real_y):
    with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
        # Generate an image -> G( x )
        generated_images = generator(input_x, training=True)
        # Probability that the given image is real -> D( x )
        real_output = discriminator(real_y, training=True)
        # Probability that the given image is the one generated -> D( G( x ) )
        generated_output = discriminator(generated_images, training=True)

        # L2 Loss -> || y - G(x) ||^2
        gen_loss = generator_loss(generated_images, real_y)
        # Log loss for the discriminator
        disc_loss = discriminator_loss(real_output, generated_output)

    # tf.keras.backend.print_tensor( tf.keras.backend.mean( gen_loss ) )
    # tf.keras.backend.print_tensor( gen_loss + disc_loss )

    # Compute the gradients
    gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables)
    gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables)

    # Optimize with Adam
    generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables))
    discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables))

generator.compile(
    optimizer=generator_optimizer,
    loss=generator_loss,
    metrics=['accuracy']
)

discriminator.compile(
    optimizer=discriminator_optimizer,
    loss=discriminator_loss,
    metrics=['accuracy']
)

def plot_loss(losses):
    """
    @losses.keys():
        0: loss
        1: accuracy
    """
    g_loss = []
    d_loss = []

    count = 0
    for i in losses['D']:
      count += 1
      if(count == 36):
        d_loss.append(i)
        count = 0

    count = 0
    for i in losses['G']:
      count += 1
      if(count == 36):
        g_loss.append(i)
        count = 0

    plt.figure(figsize=(10,8))
    plt.plot(d_loss, label="Discriminator loss")
    plt.plot(g_loss, label="Generator loss")
    plt.xlabel('Epochs')
    plt.ylabel('Loss')
    plt.legend()
    plt.show()

y = generator( test_x[0 : ] ).numpy()

for i in range(11, 33, 7):
  plt.figure(figsize=(10,10))
  or_image = plt.subplot(3,3,1)
  or_image.set_title('Grayscale Input', fontsize=16)
  plt.imshow( test_x[i].reshape((120,120)) , cmap='gray' )

  in_image = plt.subplot(3,3,2)
  image = Image.fromarray( ( y[i] * 255 ).astype( 'uint8' ) ).resize( ( 1024 , 1024 ) )
  image = np.asarray( image )
  in_image.set_title('Colorized Output', fontsize=16)
  plt.imshow( image )

  ou_image = plt.subplot(3,3,3)
  image = Image.fromarray( ( test_y[i] * 255 ).astype( 'uint8' ) ).resize( ( 1024 , 1024 ) )
  ou_image.set_title('Ground Truth', fontsize=16)
  plt.imshow( image )

  plt.show()


#!/usr/bin/env python3

from load_data import Data
from vae import VAE

import torch
import json
import argparse
import os
from tqdm import tqdm
import torch.optim as optim
import matplotlib.pyplot as plt

def get_args():
    ''' Parse arguments from CLI '''
    parser = argparse.ArgumentParser(
        description='Multi-label Variational Auto-encoder for the set of 14x14 even numbers from MNIST')
    parser.add_argument('-p', '--params', type=str, default='./files/param.json',
                        help='Path to .json file containing hyperparameters')
    parser.add_argument('-d', '--data', type=str, default='../Problem/even_mnist.csv',
                        help='Path to .csv file containing the 14x14 dataset')
    parser.add_argument('-r', '--results', default='./results',
                        help='Directory where loss plot & output images should be saved')
    parser.add_argument('-v', '--verbose', type=bool, default=False,
                        help='Boolean flag for high verbosity output')
    parser.add_argument('-c', '--cuda', type=bool, default=False,
                        help='Boolean flag indicating whether or not to use CUDA GPU')
    parser.add_argument('-n', '--num_images', type=int, default=100,
                        help='Number of "handwritten" images to generate upon completion')

    return parser.parse_args()

def main():
    args = get_args()
    with open(args.params) as p:
        params = json.load(p)
    test_size = int(params['test_size'])

    # CUDA usage
    use_cuda = torch.cuda.is_available() and args.cuda
    device = torch.device('cuda' if use_cuda else 'cpu')

    # Initialize network and get data from .csv file
    model = VAE().to(device)
    data = Data(data_file=args.data, test_size=test_size)
    model.init_data(data, device)

    # Define Adam optimizer
    optimizer = optim.Adam(model.parameters(), lr=params['learning_rate'])

    ## Training and evaluation cycle
    # Initialize lists
    obj_vals = []
    cross_vals = []
    epochs = int(params['num_epochs'])
    batch_size = int(params['batch_size'])

    print('Training over {} epochs:'.format(epochs))
    with tqdm(total=epochs, dynamic_ncols=True) as pbar:
        for epoch in range(1, epochs+1):
            # Training
            train_val = model.backprop(batch_size, optimizer)
            obj_vals.append(train_val)

            # Cross-validation evaluation
            test_val = model.test(min(test_size, batch_size))
            cross_vals.append(test_val)

            # Update progress bar
            pbar.update()

            # High verbosity report
            if args.verbose:
                if not ((epoch) % params['display_epochs']):
                    print('\nEpoch [{}/{}]'.format(epoch, epochs)
                          + '\tTraining Loss: {:.4f}'.format(train_val)
                          + '\tTest Loss: {:.4f}'.format(test_val))

    # Final loss report
    print('Final training loss: {:.4f}'.format(obj_vals[-1]))
    print('Final test loss: {:.4f}'.format(cross_vals[-1]))

    # Plot loss and save results
    plt.plot(range(1, epochs+1), obj_vals, label='Training loss', color='blue')
    plt.plot(range(1, epochs+1), cross_vals, label='Test loss', color='green')
    plt.title('BCE + KLD Loss over %i Training Epochs' % epochs)
    plt.ylabel('Loss')
    plt.xlabel('Training Epochs')
    plt.legend()
    if args.results:
        if not os.path.exists(args.results):
            os.mkdir(args.results)
        plt.savefig(os.path.join(args.results, 'loss_report.png'), dpi=600)
    plt.show()

    model.final_reconstruction(args.num_images, args.results, device)

if __name__ == '__main__':
    main()


from django.urls import path
from .views import *
from rest_framework_simplejwt import views as jwt_views

urlpatterns = [
    path('create_country',CountryCreateApi.as_view()),
    path('events_list',EventsApi.as_view()),
    path('update_athlete/<int:pk>',AthleteUpdateApi.as_view()),
    path('delete_comment/<int:pk>',CommentDeleteApi.as_view()),
    path('api/token/',
         jwt_views.TokenObtainPairView.as_view(),
         name ='token_obtain_pair'),
    path('api/token/refresh/',
         jwt_views.TokenRefreshView.as_view(),
         name ='token_refresh'),

]


subnum,time = map(int,input().split())
strs = input().split(' ')
lists = [int(i) for i in strs]
lists.sort();
adder = 0
for i in range(subnum):
    adder = time*lists[i] +adder
    time-=1
    if time<=0:time=1
print(adder)


#!/usr/bin/env python
from napalm import get_network_driver

def open_napalm_connection(my_device):
    device_type = my_device.pop("device_type")
    driver = get_network_driver(device_type)
    device = driver(**my_device)
    print(f"opening connection to {my_device['hostname']}")
    device.open()
    return device

def create_backup(napalm_conn_obj):
    my_running_config = napalm_conn_obj.get_config()['running']
    my_filename = napalm_conn_obj.get_facts()['hostname'] + ".cfg"
    f = open(my_filename, "w")
    f.write(my_running_config)
    f.close()

def create_checkpoint(napalm_conn_obj):
    my_checkpoint = napalm_conn_obj._get_checkpoint_file()
    my_filename = napalm_conn_obj.get_facts()['hostname'] + "_checkpoint.cfg"
    f = open(my_filename, "w")
    f.write(my_checkpoint)
    f.close()


import socket

host = '0.0.0.0'
port = 10101
BUFF_SIZE = 128

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = (host, port)
sock.bind(server_address)

while True:
    print("\nwaiting for request...")
    message, client_address = sock.recvfrom(BUFF_SIZE)
    print("echo request from {} port {}".format(client_address[0],client_address[1]))
    print("echo message : {}".format(message.decode()))

    data = message.decode()
    try:
        num = int(data)
        if num % 2:
            answer = "Odd number"
        else:
            answer = "Even number"
    except valueError:
        answer = "Not number"
    sock.sendto(answer.encode(), client_address)

sock.close()

sock.close()


# -*- coding:utf-8 -*-
"""
    Excel文件读写
        获取excel文件
        获取sheet页
        获取单元格内容
"""
import json
import openpyxl
from common.web_key import Key
from common.loggerController import log

# 读取excel的数据
def read_excel(path):
    # 获取excel文件
    excel = openpyxl.load_workbook(path)
    # 获取所有的sheet页的名称，列表的形式存放：sheets
    sheets = excel.sheetnames
    # 将所有的sheet页名称的列表转化为字典格式
    sh_key = dict.fromkeys(sheets)
    # 循环每个sheet页
    for name in sheets:
        # 获取所有sheet页的名称  sheet
        sheet = excel[name]
        # 将每个sheet页的操作步骤放入列表中，列表中每一项以字典格式保存数据（参数步骤数据），
        dict_key = []
        # print("*******{}*******".format(name))
        # 遍历读取excel中的每个sheet页面内的数据
        for values in sheet.values:  # values:excel的每一行数据
            # print(values)
            if type(values[0]) is int:
                # 将所有关键字添加到列表 key_li 中
                # key_li.append(values[1])
                data_sheet = {
                    "name": values[2],
                    "value": values[3],
                    "txt": values[4]
                }
                # 将参数中为None值全部去掉
                for keyvalue in list(data_sheet.keys()):
                    if data_sheet[keyvalue] is None:
                        del data_sheet[keyvalue]
                # 将所有关键字以及对应的参数数据,步骤描述   以字典（li_c）的格式存放在dict_key列表中：
                li_c = {"describe": values[5], values[1]: data_sheet}
                dict_key.append(li_c)
                # 将每个sheet页的数据列表赋值到sheet页字典的value中
                sh_key[name] = dict_key
    data = json.dumps(sh_key)
    log.info("json数据格式data:{}".format(data))

    return data

# 具体执行excel测试用例
def implement_case(data):
    data = json.loads(data)
    log.info("excel用例数据:{}".format(data))
    # 遍历每个sheet页面数据
    for key in data:
        # print(key)     # key:sheet页的名字
        # print(data[key])        # data[key]:列表格式的用例执行步骤  --- [{步骤一数据},{步骤二数据}]   ---步骤数据的格式：{key:{参数},describe:描述}
        log.info("正在执行WebUi:{}".format(key))
        # 遍历每个步骤
        for sheet_key in data[key]:
            # sheet_key:步骤数据:dict      cel_value:步骤数据的key
            # 将步骤描述赋值给describe
            describe = sheet_key["describe"]
            del sheet_key["describe"]
            # 遍历每个步骤参数字典里的key
            for cel_value in sheet_key:  # sheet_key[cel_value]:步骤参数:dict
                sheet_value = sheet_key[cel_value]
                if cel_value == "open_browser":
                    # 当读取到open_browser时需要实例化
                    key_value = Key(**sheet_value)
                else:
                    try:
                        getattr(key_value, cel_value)(**sheet_value)
                        log.info("Message:执行 {}--SUCCESS--数据{}".format(describe, sheet_value))
                    except Exception as e:
                        log.critical("Message:执行 {}--FAIL".format(describe))
                        log.critical("报错:{}".format(e))

'''
# 获取excel文件
excel = openpyxl.load_workbook("../data/Excel/webui_data_demo1.xlsx")
# 获取sheet页信息
# sheet = excel['Sheet1']
# 获取指定单元格内容
# cell = sheet['A2'].value
# 获取所有的sheet页
sheets = excel.sheetnames
# 循环赋值sheet的名称
for name in sheets:
    sheet = excel[name]
    print("*******{}*******".format(name))
    # 获取整个sheet页的内容
    for values in sheet.values:
        # 进入测试用例正文
        if type(values[0]) is int:
            """
                提取内容：
                    操作行为
                    对应参数
            """
            data = {
                "name": values[2],
                "value": values[3],
                "txt": values[4]
                }
            # 将参数中为None值全部去掉
            for keyvalue in list(data.keys()):
                if data[keyvalue] is None:
                    del data[keyvalue]
            print(data)
            # 基于关键字行为进行测试内容的执行
            if values[1] == "open_browser":
                # 当读取到open_browser时需要实例化
                key = Key(**data)
            else:
                getattr(key, values[1])(**data)

'''


import numpy as np
import pandas as pd
import flask
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
data = pd.read_csv("main_data.csv")
app = flask.Flask(__name__)
def create_similarity():
    data = pd.read_csv("main_data.csv")
    cv = CountVectorizer()
    count_matrix = cv.fit_transform(data['combination'])
    similarity = cosine_similarity(count_matrix)
    return data,similarity
def rcmd(m):
    m.lower()
    data, similarity = create_similarity()
    if m not in data['movie_title'].unique():
        return('Sorry! The movie you requested is not in our database. Please check the spelling or try with some other movies')
    else:
        i = data.loc[data['movie_title']==m].index[0]
        lst = list(enumerate(similarity[i]))
        lst = sorted(lst, key = lambda x:x[1] ,reverse=True)
        lst = lst[1:11] # excluding first item since it is the requested movie itself
        l = []
        for i in range(len(lst)):
            a = lst[i][0]
            l.append(data['movie_title'][a])
        return l
def get_suggestions():
    data = pd.read_csv("main_data.csv")
    return list(data['movie_title'].str.capitalize())
@app.route('/', methods=['GET', 'POST'])
def main():
    if flask.request.method == 'GET':
        suggestions = get_suggestions()
        return(flask.render_template('index.html',suggestions=suggestions))

    if flask.request.method == 'POST':
        m_name = flask.request.form['movie_name'].lower()
        result_final = rcmd(m_name.lower())
        print(m_name,result_final)
        if result_final == 'Sorry! The movie you requested is not in our database. Please check the spelling or try with some other movies':
            return(flask.render_template('negative.html',name=m_name))
        else:
            return flask.render_template('positive.html',movie_names=result_final,search_name=m_name)

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


import os
import time
from random import randint

import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "database.settings")
django.setup()

from database.model.models import StructuredData
from execution.exchanges.binance.margin._trading import BinanceMarginTrader
from execution.tests.setup.test_data.binance_api_responses import trading_fees, isolated_account_info

class BinanceMockMarginTrader(BinanceMarginTrader):

    def __init__(
        self,
        margin_level=3,
    ):
        BinanceMarginTrader.__init__(
            self,
            margin_level=margin_level,
            paper_trading=True
        )

    def _init_session(self):
        pass

    def ping(self):
        pass

    def get_isolated_margin_account(self):
        return isolated_account_info

    def create_margin_loan(self, asset, amount, isIsolated, symbol):
        return {"tranId": 100000001}

    def get_trade_fee(self, symbol):
        return trading_fees

    def get_max_margin_loan(self, asset, isolatedSymbol):
        return {"amount": "1.69248805", "borrowLimit": "60"}

    def repay_margin_loan(self, asset, amount, isIsolated, symbol):
        return {"tranId": 100000001}

    def create_margin_order(
        self,
        symbol,
        side,
        type,
        newOrderRespType,
        isIsolated,
        sideEffectType,
        quantity=None,
        quoteOrderQty=None,
        **kwargs
    ):
        transact_time = int(time.time() * 1000)

        price = StructuredData.objects.last().close

        quantity = quantity if quantity else quoteOrderQty

        return {
            "symbol": symbol,
            "orderId": randint(1, 1E9),
            "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
            "transactTime": transact_time,
            "price": str(price),
            "origQty": str(quantity),
            "executedQty": str(quantity),
            "cummulativeQuoteQty": str(quantity),
            "status": "FILLED",
            "timeInForce": "GTC",
            "type": "MARKET",
            "side": side,
            "isIsolated": True,  # if isolated margin
            "fills": [
                {
                    "price": str(price),
                    "qty": str(quantity),
                    "commission": str(0.001 * price),
                    "commissionAsset": "USDT",
                },
            ],
        }