예제 #1
0
파일: bingo.py 프로젝트: rgeos/bingo
    def __init__(self):

        # layed out in a grid with odd rows a different color for
        # visual separation
        #lucky = Grid(9,10, CellPadding=25, CellSpacing=1, BorderWidth=1)
        lucky = Grid()
        lucky.resize(9,10)
        lucky.setBorderWidth(1)
        lucky.setCellPadding(25)
        lucky.setCellSpacing(1)
        val = 0
        for x in range(0,9):
            for y in range(0,10):
                val += 1
                lucky.setText(x,y,val)

        grid = Grid(1,3,CellPadding=20,CellSpacing=0)
        rf = grid.getRowFormatter()
        rf.setStyleName(0, 'oddrow')

        # popup timer buttons
        ptb = PopupTimerButton(1)
        grid.setWidget(0, 0, CaptionPanel('Start the Lucky Number Countdown', ptb, StyleName='left'))
        grid.setWidget(0, 1, CaptionPanel('Current Lucky Number',ptb.box))
        grid.setWidget(0, 2, lucky)

        # add it all to the root panel
        RootPanel().add(grid, lucky)
예제 #2
0
파일: GridTest.py 프로젝트: wkornewald/pyjs
class GridWidget(AbsolutePanel):

    def __init__(self):
        AbsolutePanel.__init__(self)

        self.page=0
        self.min_page=1
        self.max_page=10
        
        self.addb=Button("Next >", self)
        self.subb=Button("< Prev", self)
        self.clearb=Button("Clear", self)
        
        self.g=Grid()
        self.g.resize(5, 5)
        self.g.setWidget(0, 0, HTML("<b>Grid Test</b>"))
        self.g.setBorderWidth(2)
        self.g.setCellPadding(4)
        self.g.setCellSpacing(1)
        
        self.updatePageDisplay()

        self.add(self.subb)
        self.add(self.addb)
        self.add(self.clearb)
        self.add(self.g)

    def onClick(self, sender):
        if sender == self.clearb:
            print "clear"
            self.g.clear()
            return
        elif sender==self.addb:
            self.page+=1
        elif sender==self.subb:
            self.page-=1
        self.updatePageDisplay()
        

    def updatePageDisplay(self):
        if self.page<self.min_page: self.page=self.min_page
        elif self.page>self.max_page: self.page=self.max_page
        total_pages=(self.max_page-self.min_page) + 1
        
        self.g.setHTML(0, 4, "<b>page %d of %d</b>" % (self.page, total_pages))
        
        if self.page>=self.max_page:
            self.addb.setEnabled(False)
        else:
            self.addb.setEnabled(True)
            
        if self.page<=self.min_page:
            self.subb.setEnabled(False)
        else:
            self.subb.setEnabled(True)

        for y in range(1, 5):
            for x in range(5):
                self.g.setText(y, x, "%d (%d,%d)" % (self.page, x, y))
예제 #3
0
class AccountListSink(VerticalPanel):
    def __init__(self, hendler = None):
        VerticalPanel.__init__(self,
                               #HorizontalAlignment=HasAlignment.ALIGN_CENTER,
                               #VerticalAlignment=HasAlignment.ALIGN_MIDDLE,
                               Width="100%",
                               #Height="100%",
                               Spacing=5)
                               
        self.remote = DataService(['getaccounts'])        
                               
        self.grid = Grid(1, 3,
                    BorderWidth=1,
                    CellPadding=4,
                    CellSpacing=1,
                    StyleName="grid")
        self.grid.setText(0, 0, u"Number")
        self.grid.setText(0, 1, u"Type")
        self.grid.setText(0, 2, u"Balance")
        
        formatter = self.grid.getRowFormatter()
        formatter.setStyleName(0, "grid-header")
        
        self.add(Label(u"Accounts"))
        
        self.add(self.grid)
        
    def updateGrid(self, accounts):         
        rows = len(accounts)
        if rows > 0:
            self.grid.resize(rows+1, 3)
            for row in range(rows):
                link = PseudoLink(accounts[row]['number'],
                                  self.onClick,
                                  ID=accounts[row]['number'])
                self.grid.setWidget(row+1, 0, link)
                self.grid.setText(row+1, 1, accounts[row]['type'])
                self.grid.setText(row+1, 2, accounts[row]['balance'])
                
    def onShow(self):
        self.remote.getaccounts(self)
        
    def onClick(self, sender):
        Window.alert(sender.getID())
         
                 
    def onRemoteResponse(self, response, request_info):
        '''
        Called when a response is received from a RPC.
        '''
        if request_info.method == 'getaccounts':
            #TODO
            self.updateGrid(response)
        else:
            Window.alert('Unrecognized JSONRPC method.')
            
    def onRemoteError(self, code, message, request_info):
        Window.alert(message)
예제 #4
0
파일: grid.py 프로젝트: minghuascode/pyj
    def __init__(self):
        SimplePanel.__init__(self)

        grid = Grid(5, 5, BorderWidth=2, CellPadding=4, CellSpacing=1)
        grid.setHTML(0, 0, '<b>Hello, World!</b>')

        for row in range(1, 5):
            for col in range(1, 5):
                grid.setText(
                    row, col,
                    str(row) + "*" + str(col) + " = " + str(row * col))

        self.add(grid)
예제 #5
0
파일: grid.py 프로젝트: Afey/pyjs
    def __init__(self):
        SimplePanel.__init__(self)

        grid = Grid(5, 5,
                    BorderWidth=2,
                    CellPadding=4,
                    CellSpacing=1)
        grid.setHTML(0, 0, '<b>Hello, World!</b>')

        for row in range(1, 5):
            for col in range(1, 5):
                grid.setText(row, col, str(row) + "*" + str(col) + " = " + str(row*col))

        self.add(grid)
예제 #6
0
    def drawGrid(self, month, year):
        # draw the grid in the middle of the calendar

        daysInMonth = self.getDaysInMonth(month, year)
        # first day of the month & year
        secs = time.mktime((year, month, 1, 0, 0, 0, 0, 0, -1))
        struct = time.localtime(secs)
        # 0 - sunday for our needs instead 0 = monday in tm_wday
        startPos = (struct.tm_wday + 1) % 7
        slots = startPos + daysInMonth - 1
        rows = int(slots / 7) + 1
        grid = Grid(rows + 1, 7)  # extra row for the days in the week
        grid.setWidth("100%")
        grid.addTableListener(self)
        self.middlePanel.setWidget(grid)
        #
        # put some content into the grid cells
        #
        for i in range(7):
            grid.setText(0, i, self.getDaysOfWeek()[i])
            grid.cellFormatter.addStyleName(0, i, "calendar-header")
        #
        # draw cells which are empty first
        #
        day = 0
        pos = 0
        while pos < startPos:
            grid.setText(1, pos, " ")
            grid.cellFormatter.setStyleAttr(1, pos, "background", "#f3f3f3")
            grid.cellFormatter.addStyleName(1, pos, "calendar-blank-cell")
            pos += 1
        # now for days of the month
        row = 1
        day = 1
        col = startPos
        while day <= daysInMonth:
            if pos % 7 == 0 and day <> 1:
                row += 1
            col = pos % 7
            grid.setText(row, col, str(day))
            if self.currentYear == self.todayYear and \
               self.currentMonth == self.todayMonth and day == self.todayDay:
                grid.cellFormatter.addStyleName(row, col,
                                                "calendar-cell-today")
            else:
                grid.cellFormatter.addStyleName(row, col, "calendar-day-cell")
            day += 1
            pos += 1
        #
        # now blank lines on the last row
        #
        col += 1
        while col < 7:
            grid.setText(row, col, " ")
            grid.cellFormatter.setStyleAttr(row, col, "background", "#f3f3f3")
            grid.cellFormatter.addStyleName(row, col, "calendar-blank-cell")
            col += 1

        return grid
예제 #7
0
파일: Calendar.py 프로젝트: jwashin/pyjs
    def drawGrid(self, month, year):
        # draw the grid in the middle of the calendar

        daysInMonth = self.getDaysInMonth(month, year)
        # first day of the month & year
        secs = time.mktime((year, month, 1, 0, 0, 0, 0, 0, -1))
        struct = time.localtime(secs)
        # 0 - sunday for our needs instead 0 = monday in tm_wday
        startPos = (struct.tm_wday + 1) % 7
        slots = startPos + daysInMonth - 1
        rows = int(slots/7) + 1
        grid = Grid(rows+1, 7) # extra row for the days in the week
        grid.setWidth("100%")
        grid.addTableListener(self)
        self.middlePanel.setWidget(grid)
        #
        # put some content into the grid cells
        #
        for i in range(7):
            grid.setText(0, i, self.getDaysOfWeek()[i])
            grid.cellFormatter.addStyleName(0, i, "calendar-header")
        #
        # draw cells which are empty first
        #
        day =0
        pos = 0
        while pos < startPos:
            grid.setText(1, pos , " ")
            grid.cellFormatter.setStyleAttr(1, pos, "background", "#f3f3f3")
            grid.cellFormatter.addStyleName(1, pos, "calendar-blank-cell")
            pos += 1
        # now for days of the month
        row = 1
        day = 1
        col = startPos
        while day <= daysInMonth:
            if pos % 7 == 0 and day <> 1:
                row += 1
            col = pos % 7
            grid.setText(row, col, str(day))
            if self.currentYear == self.todayYear and \
               self.currentMonth == self.todayMonth and day == self.todayDay:
                grid.cellFormatter.addStyleName(row, col, "calendar-cell-today")
            else:
                grid.cellFormatter.addStyleName(row, col, "calendar-day-cell")
            day += 1
            pos += 1
        #
        # now blank lines on the last row
        #
        col += 1
        while col < 7:
            grid.setText(row, col, " ")
            grid.cellFormatter.setStyleAttr(row, col, "background", "#f3f3f3")
            grid.cellFormatter.addStyleName(row, col, "calendar-blank-cell")
            col += 1

        return grid
예제 #8
0
class DynaTableWidget(Composite):
    def __init__(self, provider, columns, columnStyles, rowCount):
        Composite.__init__(self)

        self.acceptor = RowDataAcceptorImpl(self)
        self.outer = DockPanel()
        self.startRow = 0
        self.grid = Grid()
        self.navbar = NavBar(self)

        self.provider = provider
        self.initWidget(self.outer)
        self.grid.setStyleName("table")
        self.outer.add(self.navbar, DockPanel.NORTH)
        self.outer.add(self.grid, DockPanel.CENTER)
        self.initTable(columns, columnStyles, rowCount)
        self.setStyleName("DynaTable-DynaTableWidget")

    def initTable(self, columns, columnStyles, rowCount):
        self.grid.resize(rowCount + 1, len(columns))
        for i in range(len(columns)):
            self.grid.setText(0, i, columns[i])
            if columnStyles:
                self.grid.cellFormatter.setStyleName(
                    0, i, columnStyles[i] + "header")

    def setStatusText(self, text):
        self.navbar.status.setText(text)

    def clearStatusText(self, text):
        self.navbar.status.setHTML("&nbsp;")

    def refresh(self):
        self.navbar.gotoFirst.setEnabled(False)
        self.navbar.gotoPrev.setEnabled(False)
        self.navbar.gotoNext.setEnabled(False)

        self.setStatusText("Please wait...")
        self.provider.updateRowData(self.startRow,
                                    self.grid.getRowCount() - 1, self.acceptor)

    def setRowCount(self, rows):
        self.grid.resizeRows(rows)

    def getDataRowCount(self):
        return self.grid.getRowCount() - 1
예제 #9
0
class DynaTableWidget(Composite):

    def __init__(self, provider, columns, columnStyles, rowCount):
        Composite.__init__(self)

        self.acceptor = RowDataAcceptorImpl(self)
        self.outer = DockPanel()
        self.startRow = 0
        self.grid = Grid()
        self.navbar = NavBar(self)

        self.provider = provider
        self.initWidget(self.outer)
        self.grid.setStyleName("table")
        self.outer.add(self.navbar, DockPanel.NORTH)
        self.outer.add(self.grid, DockPanel.CENTER)
        self.initTable(columns, columnStyles, rowCount)
        self.setStyleName("DynaTable-DynaTableWidget")

    def initTable(self, columns, columnStyles, rowCount):
        self.grid.resize(rowCount + 1, len(columns))
        for i in range(len(columns)):
            self.grid.setText(0, i, columns[i])
            if columnStyles:
                self.grid.cellFormatter.setStyleName(0, i, columnStyles[i] + "header")

    def setStatusText(self, text):
        self.navbar.status.setText(text)

    def clearStatusText(self, text):
        self.navbar.status.setHTML("&nbsp;")

    def refresh(self):
        self.navbar.gotoFirst.setEnabled(False)
        self.navbar.gotoPrev.setEnabled(False)
        self.navbar.gotoNext.setEnabled(False)

        self.setStatusText("Please wait...")
        self.provider.updateRowData(self.startRow, self.grid.getRowCount() - 1, self.acceptor)

    def setRowCount(self, rows):
        self.grid.resizeRows(rows)

    def getDataRowCount(self):
        return self.grid.getRowCount() - 1
예제 #10
0
파일: Tables.py 프로젝트: wangxiaodong/pyjs
    def __init__(self):
        Sink.__init__(self)
        inner = Grid(10, 5, Width="100%", BorderWidth="1")
        outer = FlexTable(Width="100%", BorderWidth="1")

        outer.setWidget(0, 0, Image(self.baseURL() + "rembrandt/LaMarcheNocturne.jpg"))
        outer.getFlexCellFormatter().setColSpan(0, 0, 2)
        outer.getFlexCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER)

        outer.setHTML(1, 0, "Look to the right...<br>That's a nested table component ->")
        outer.setWidget(1, 1, inner)
        outer.getCellFormatter().setColSpan(1, 1, 2)

        for i in range(10):
            for j in range(5):
                inner.setText(i, j, "%d" % i + ",%d" % j)

        self.initWidget(outer)
예제 #11
0
    def __init__(self):
        Sink.__init__(self)
        inner = Grid(10, 5, Width="100%", BorderWidth="1")
        outer = FlexTable(Width="100%", BorderWidth="1")

        outer.setWidget(0, 0, Image(self.baseURL() + "rembrandt/LaMarcheNocturne.jpg"))
        outer.getFlexCellFormatter().setColSpan(0, 0, 2)
        outer.getFlexCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER)

        outer.setHTML(1, 0, "Look to the right...<br>That's a nested table component ->")
        outer.setWidget(1, 1, inner)
        outer.getCellFormatter().setColSpan(1, 1, 2)
        
        for i in range(10):
            for j in range(5):
                inner.setText(i, j, "%d" % i + ",%d" % j)

        self.initWidget(outer)
예제 #12
0
    def drawGrid(self, month, year):
        # draw the grid in the middle of the calendar

        self.checkLinks(month, year)

        daysInMonth = self.getDaysInMonth(month, year)
        # first day of the month & year
        secs = time.mktime((year, month, 1, 0, 0, 0, 0, 0, -1))
        struct = time.localtime(secs)
        startPos = (struct.tm_wday + self.dayoffset) % 7
        slots = startPos + daysInMonth - 1
        rows = int(slots/7) + 1
        grid = Grid(rows+1, 7, # extra row for the days in the week
                    StyleName="calendar-grid") 
        grid.setWidth("100%")
        grid.addTableListener(self)
        self.middlePanel.setWidget(grid)
        cf = grid.getCellFormatter()
        #
        # put some content into the grid cells
        #
        for i in range(7):
            grid.setText(0, i, self.getDaysOfWeek()[i])
            cf.addStyleName(0, i, "calendar-header")
        #
        # draw cells which are empty first
        #
        day = 0
        pos = 0
        while pos < startPos:
            self._setCell(grid, 1, pos, BLANKCELL, "calendar-blank-cell")
            pos += 1
        # now for days of the month
        row = 1
        day = 1
        col = startPos
        while day <= daysInMonth:
            if pos % 7 == 0 and day != 1:
                row += 1
            col = pos % 7
            if not self._indaterange(self.currentYear, self.currentMonth, day):
                self._setCell(grid, row, col, BLANKCELL, "calendar-blank-cell")
                day += 1
                pos += 1
                continue
            if self.currentYear == self.todayYear and \
               self.currentMonth == self.todayMonth and day == self.todayDay:
                style = "calendar-cell-today"
            else:
                style = "calendar-day-cell"
            self._setCell(grid, row, col, str(day), style)
            day += 1
            pos += 1
        #
        # now blank lines on the last row
        #
        col += 1
        while col < 7:
            self._setCell(grid, row, col, BLANKCELL, "calendar-blank-cell")
            col += 1

        return grid
예제 #13
0
class Underway(HorizontalPanel):
    def __init__(self):
        HorizontalPanel.__init__(self, Spacing=4)
        self.add(Label('Underway:', StyleName='section'))
        s = ScrollPanel()
        self.add(s)
        v = VerticalPanel()
        s.add(v)
        self.queued = Grid(StyleName='users')
        v.add(self.queued)
        self.button = Button('Refresh', self, StyleName='refresh')
        self.add(self.button)
        self.err = Label()
        self.add(self.err)
        self.update()

    def update(self):
        remote = server.AdminService()
        id = remote.getUnderway(self)
        if id < 0:
            self.err.setText('oops: could not call getUnderway')

    def onRemoteResponse(self, result, request_info):
        self.button.setEnabled(True)
        self.queued.clear()
        if not result:
            self.queued.resize(1, 1)
            self.queued.setText(0, 0, 'No users are currently being added.')
        else:
            self.queued.resize(len(result) + 1, 6)
            self.queued.setText(0, 0, 'Pos')
            self.queued.setText(0, 1, 'Name')
            self.queued.setText(0, 2, 'Friends')
            self.queued.setText(0, 3, '% done')
            self.queued.setText(0, 4, 'Queued at')
            self.queued.setText(0, 5, 'Started at')
            row = 1
            for name, nFriends, done, queuedAt, startTime in result:
                self.queued.setText(row, 0, row)
                self.queued.setText(row, 1, name)
                self.queued.setText(row, 2, nFriends)
                self.queued.setText(row, 3, '%.2f' % done)
                self.queued.setText(row, 4, queuedAt)
                self.queued.setText(row, 5, startTime)
                row += 1

    def onRemoteError(self, code, message, request_info):
        self.button.setEnabled(True)
        self.err.setText('Could not getUnderway: ' + message)

    def onClick(self, sender):
        self.err.setText('')
        self.button.setEnabled(False)
        self.update()
예제 #14
0
class PopupPagina(PopupPanel):
    def __init__(self, autoHide=None, modal=True, **kwargs):

        PopupPanel.__init__(self, autoHide, modal, **kwargs)

        datasource = None
        id = None

        if kwargs.has_key("datasrc"):
            datasource = kwargs["datasrc"]
        if kwargs.has_key("id"):
            id = kwargs["id"]

        self.setSize(Window.getClientWidth() - 50, Window.getClientHeight() - 50)
        self.setPopupPosition(20, 0)
        DOM.setAttribute(self, "align", "center")

        # self.dbProxInstrucao = DialogBox()
        # self.dbProxInstrucao.setHTML("Alow")
        # botton = Button("Ok")
        # botton.addClickListener(self.onCloseDialog)
        # self.dbProxInstrucao.setWidget(botton)

        self.caption = HTML()
        self.child = None
        self.setHTML("<b>Soma de Matrizes.</b>")

        self.dragging = False
        self.dragStartX = 0
        self.dragStartY = 0

        self.imageFechar = Image("images/fechar.gif", Size=("32px", "32px"), StyleName="gwt-ImageButton")
        self.imgbtnDesfazer = Image("images/previous-arrow.png", Size=("32px", "20px"), StyleName="gwt-ImageButton")
        self.imgbtnFazer = Image("images/next-arrow.png", Size=("32px", "20px"), StyleName="gwt-ImageButton")
        #        self.imgbtnDesfazer.addClickListener(desfazerProxOperacao)
        #        self.imgbtnFazer.addClickListener(fazerProxOperacao)

        self.btnAutomatic = Button("Automático", self.onIniciarAnimacaoAutomatica)
        self.btnInterativo = Button("Interativo")
        if id == "escalar":
            self.btnStepByStep = Button("Passo a passo", IniciarAnimacaoPassoAPasso)
        else:
            self.btnStepByStep = Button("Passo a passo", self.onIniciarAnimacaoPassoAPasso)
        self.btnFazer = Button("fazer >>", fazerProxOperacao)
        # self.btnFazer.setEnabled(False);
        self.btnDesfazer = Button("<< desfazer", desfazerProxOperacao)
        # self.btnDesfazer.setEnabled(False);
        self.btnFechar = PushButton(imageFechar, imageFechar)
        self.btnTestarResposta = Button("Testar Solução")
        self.lbVelocidade = ListBox()
        self.lbVelocidade.setID("lbseg")

        self.lbVelocidade.addItem("0.5 segundo", value=2)
        self.lbVelocidade.addItem("1 segundo", value=1)
        self.lbVelocidade.addItem("2 segundos", value=0.5)
        self.lbVelocidade.addItem("3 segundos", value=1 / 3)
        self.lbVelocidade.addItem("4 segundos", value=0.25)
        self.lbVelocidade.addItem("5 segundos", value=0.20)
        self.lbVelocidade.addItem("6 segundos", value=0.167)
        self.lbVelocidade.addItem("7 segundos", value=0.143)
        self.lbVelocidade.addItem("8 segundos", value=0.125)
        self.lbVelocidade.addItem("10 segundos", value=0.1)

        lblinha1 = ListBox()
        lblinha1.setID("lm1")
        lblinha1.addItem("1", value=1)
        lblinha1.addItem("2", value=2)
        lblinha1.addItem("3", value=3)
        lblinha1.addItem("4", value=4)
        lblinha1.addItem("5", value=5)

        lblinha2 = ListBox()
        lblinha2.setID("lm2")
        lblinha2.addItem("1", value=1)
        lblinha2.addItem("2", value=2)
        lblinha2.addItem("3", value=3)
        lblinha2.addItem("4", value=4)
        lblinha2.addItem("5", value=5)

        lbcoluna1 = ListBox()
        lbcoluna1.setID("cm1")
        lbcoluna1.addItem("1", value=1)
        lbcoluna1.addItem("2", value=2)
        lbcoluna1.addItem("3", value=3)
        lbcoluna1.addItem("4", value=4)
        lbcoluna1.addItem("5", value=5)
        lbcoluna1.addItem("6", value=6)
        lbcoluna1.addItem("7", value=7)

        lbcoluna2 = ListBox()
        lbcoluna2.setID("cm2")
        lbcoluna2.addItem("1", value=1)
        lbcoluna2.addItem("2", value=2)
        lbcoluna2.addItem("3", value=3)
        lbcoluna2.addItem("4", value=4)
        lbcoluna2.addItem("5", value=5)
        lbcoluna2.addItem("6", value=6)
        lbcoluna2.addItem("7", value=7)

        self.lblStatus = Label("Label para Status")

        # Eventos
        self.imageFechar.addClickListener(self.onFecharPopup)

        # Cabeçalho da poupPanel
        self.grid = Grid(1, 16)
        self.grid.setWidth(self.getWidth())
        self.grid.setHTML(0, 0, "<b>Matriz 1:</b> Nº Linhas:")
        self.grid.setWidget(0, 1, lblinha1)
        self.grid.setText(0, 2, "Nº Colunas:")
        self.grid.setWidget(0, 3, lbcoluna1)
        self.grid.setHTML(0, 4, "<b>Matriz 2:</b> Nº Linhas:")
        self.grid.setWidget(0, 5, lblinha2)
        self.grid.setText(0, 6, "Nº Colunas:")
        self.grid.setWidget(0, 7, lbcoluna2)
        #        self.grid.setWidget(0, 3, self.txtColunas)
        self.grid.setWidget(0, 8, self.btnStepByStep)
        self.grid.setWidget(0, 9, self.btnDesfazer)
        self.grid.setWidget(0, 10, self.btnFazer)
        self.grid.setHTML(0, 11, "<b>Velocidade:</b>")
        self.grid.setWidget(0, 12, self.lbVelocidade)
        self.grid.setWidget(0, 13, self.btnAutomatic)
        # self.grid.setWidget(0, 14, self.btnInterativo)
        self.grid.setWidget(0, 15, self.imageFechar)
        # self.grid.setWidget(0, 7, self.btnFechar)
        self.grid.getCellFormatter().setAlignment(
            0, 15, HasHorizontalAlignment.ALIGN_RIGHT, HasVerticalAlignment.ALIGN_TOP
        )

        self.panel = FlexTable(Height="100%", width="100%", BorderWidth="0", CellPadding="0", CellSpacing="0")

        self.panel.setWidget(0, 0, self.caption)
        self.panel.setWidget(1, 0, self.grid)
        self.panel.getCellFormatter().setHeight(2, 0, "100%")
        self.panel.getCellFormatter().setWidth(2, 0, "100%")
        self.panel.getCellFormatter().setAlignment(
            2, 0, HasHorizontalAlignment.ALIGN_CENTER, HasVerticalAlignment.ALIGN_TOP
        )
        self.panel.setID("contetepopup")

        painelhorizontal = HorizontalPanel()
        gridinterativa = FlexTable()

        painelhorizontal.add(
            HTML(
                "<canvas id='%s' datasrc='%s' width='%s' height='%s' style='image-rendering: optimizespeed !important; '></canvas>"
                % ("soma", datasource, "1000px", "500px")
            )
        )

        ftInterativo = FlexTable(Height="100%", width="100%", BorderWidth="0", CellPadding="0", CellSpacing="0")

        gridinterativa = Grid(4, 4)
        gridinterativa.setWidget(
            0,
            0,
            HTML(
                "<b>M1(</b><input type='text' class='gwt-TextBox' id='linha1' style='width: 25px; height:20px;' maxLength='1'><b> , </b>"
            ),
        )

        gridinterativa.setWidget(
            0,
            1,
            HTML(
                "<input type='text' class='gwt-TextBox' id='coluna1' style='width: 25px;height:20px;' maxLength='1'><b>)&nbsp;+</b>"
            ),
        )

        gridinterativa.setWidget(
            0,
            2,
            HTML(
                "<b>M2(</b>&nbsp;<input type='text' class='gwt-TextBox' id='linha2' style='width: 25px; height:20px;' maxLength='1'><b> , </b>"
            ),
        )

        gridinterativa.setWidget(
            0,
            3,
            HTML(
                "<input type='text' class='gwt-TextBox' id='coluna2' style='width: 25px; height:20px;' maxLength='1'><b>)&nbsp;=</b>"
            ),
        )

        gridinterativa.setWidget(
            2,
            0,
            HTML(
                "&nbsp;&nbsp;<b>(</b><input type='text' class='gwt-TextBox' id='n1' style='width: 25px; height:20px;' maxLength='1'><b>)&nbsp;+</b>"
            ),
        )

        gridinterativa.setWidget(
            2,
            1,
            HTML(
                "<b>(</b><input type='text' class='gwt-TextBox' id='n2' style='width: 25px; height:20px;' maxLength='1'><b>)</b>"
            ),
        )

        gridinterativa.setWidget(
            2,
            2,
            HTML(
                "<b>=&nbsp;</b>&nbsp;<input type='text' class='gwt-TextBox' id='solucao' style='width: 25px; height:20px;' maxLength='1'>"
            ),
        )

        ftInterativo.setHTML(0, 0, "</br>")
        ftInterativo.setHTML(1, 0, "<b><h3>Painel Interativo<h3></b>")
        # ftInterativo.setWidget(2, 0, self.btnInterativo)
        ftInterativo.setWidget(3, 0, gridinterativa)
        ftInterativo.setWidget(4, 0, self.btnTestarResposta)
        ftInterativo.setHTML(5, 0, "</br>")
        ftInterativo.setHTML(6, 0, "Use a tecla tab para agilizar.")

        ftInterativo.getCellFormatter().setAlignment(
            4, 0, HasHorizontalAlignment.ALIGN_CENTER, HasVerticalAlignment.ALIGN_TOP
        )
        ftInterativo.getCellFormatter().setAlignment(
            1, 0, HasHorizontalAlignment.ALIGN_CENTER, HasVerticalAlignment.ALIGN_TOP
        )

        # painelhorizontal.add(ftInterativo)

        self.panel.setWidget(2, 0, painelhorizontal)

        self.panel.setWidget(3, 0, self.lblStatus)

        self.panel.setStyleName("dialogContent")

        PopupPanel.setWidget(self, self.panel)

        self.setStyleName("gwt-DialogBox")
        self.caption.setStyleName("Caption")
        self.caption.addMouseListener(self)

        # self.txtlm1.setFocus(True);

    def onFecharPopup(self, event):
        self.hide()
        PararAnimacao()

    def onIniciarAnimacaoPassoAPasso(self, event):
        self.btnFazer.setEnabled(True)
        self.btnDesfazer.setEnabled(True)

        if self.validarParametrosMatriz():
            IniciarAnimacaoPassoAPasso()

    def onIniciarAnimacaoAutomatica(self, event):

        if self.validarParametrosMatriz():
            IniciarAnimacaoAutomatica()

        def onTestarSolucao(self, event):
            pass
            # if self.validarParametrosMatriz():

            # def onCloseDialog(self, event):
            # self.dbProxInstrucao.hide()

            # def onOpenDialog(self, event):
            # self.dbProxInstrucao.show()

    def validarParametrosTestarSolucao():
        lm1 = DOM.getElementById("linha1")
        lm1 = lm1.value
        cm1 = DOM.getElementById("coluna1")
        cm1 = cm1.value
        lm2 = DOM.getElementById("linha2")
        lm2 = lm2.value
        cm2 = DOM.getElementById("coluna2")
        cm2 = cm2.value

    def validarParametrosMatriz():
        lm1 = DOM.getElementById("lm1")
        lm1 = lm1.value
        cm1 = DOM.getElementById("cm1")
        cm1 = cm1.value
        lm2 = DOM.getElementById("lm2")
        lm2 = lm2.value
        cm2 = DOM.getElementById("cm2")
        cm2 = cm2.value
        if not lm1 or not lm2:
            Window.alert("Informe o numero de linhas da matriz M1 e M2.")
            return False

        if lm1 != lm2:
            Window.alert("A quantidade de linhas da matriz M1 deve ser igual a da matriz M2 para operação de soma.")
            return False

        if lm1 > "5" or lm2 > "5" or len(lm1) != 1 or len(lm2) != 1:
            Window.alert("A quantidade de linhas da matriz M1 e da matriz M2, deve ser menor ou igual a 5.")
            return False

        if not cm1 or not cm2:
            Window.alert("Informe o numero de colunas da matriz M1 e M2.")
            return False

        if cm1 != cm2:
            Window.alert("A quantidade de colunas da matriz M1 deve ser igual a da matriz M2 para operação de soma.")
            return False

        if cm1 > "7" or cm2 > "7" or len(cm1) != 1 or len(cm2) != 1:
            Window.alert("A quantidade de colunas da matriz M1 e da matriz M2, deve ser menor ou igual a 7.")
            return False
        return True

    def getHTML(self):
        return self.caption.getHTML()

    def getText(self):
        return self.caption.getText()

    def onEventPreview(self, event):
        # preventDefault on mousedown events, outside of the
        # dialog, to stop text-selection on dragging
        type = DOM.eventGetType(event)
        if type == "mousedown":
            target = DOM.eventGetTarget(event)
            elem = self.caption.getElement()
            event_targets_popup = target and DOM.isOrHasChild(elem, target)
            if event_targets_popup:
                DOM.eventPreventDefault(event)
        return PopupPanel.onEventPreview(self, event)

    def onMouseDown(self, sender, x, y):
        self.dragging = True
        DOM.setCapture(self.caption.getElement())
        self.dragStartX = x
        self.dragStartY = y

    def onMouseMove(self, sender, x, y):
        if self.dragging:
            absX = x + self.getAbsoluteLeft()
            absY = y + self.getAbsoluteTop()
            self.setPopupPosition(absX - self.dragStartX, absY - self.dragStartY)

    def onMouseUp(self, sender, x, y):
        self.dragging = False
        DOM.releaseCapture(self.caption.getElement())

    def onMouseLeave(self, self, x, y):
        pass

    def onMouseEnter(self, self, x, y):
        pass

    def remove(self, widget):
        if self.child != widget:
            return False

        self.panel.remove(widget)
        self.child = None
        return True

    def setHTML(self, html):
        self.caption.setHTML(html)

    def setText(self, text):
        self.caption.setText(text)

    def doAttachChildren(self):
        PopupPanel.doAttachChildren(self)
        self.caption.onAttach()

    def doDetachChildren(self):
        PopupPanel.doDetachChildren(self)
        self.caption.onDetach()

    def setWidget(self, widget):
        if self.child is not None:
            self.panel.remove(self.child)

        if widget is not None:
            self.panel.setWidget(1, 0, widget)

        self.child = widget
예제 #15
0
class GridWidget(AbsolutePanel):
  def __init__(self):
    AbsolutePanel.__init__(self)

    StyleSheetCssText(margins) # initialize css...

    header = """<div><H2 align="center">Welcome to Unbeatable Tic-Tac-Toe!</H2><br>My <a href="https://github.com/chetweger/min-max-games/blob/master/ttt/ttt.py">implementation</a> uses the min-max search algorithm with alpha beta pruning and a transposition table!</div>"""
    header = HTML(header, StyleName='margins_both')
    self.add(header)

    self.ai_first = Button("AI first.", self, StyleName='margins_left')
    self.add(self.ai_first)

    self.new_game = Button("New game", self, StyleName='margins_left')
    self.add(self.new_game)

    self.g=Grid(StyleName='margins_left')
    self.g.resize(3, 3)
    self.g.setBorderWidth(2)
    self.g.setCellPadding(4)
    self.g.setCellSpacing(1)

    self.init()
    self.add(self.g)

    self.state = State()

    self.game_resolution=Label("", StyleName='margins_left')
    self.add(self.game_resolution)

  def start_new_game(self):
    self.state = State()
    self.game_over = False
    self.ai_first.setVisible(True)
    self.state_to_grid(self.state)

  def onClick(self, sender):
    if sender == self.ai_first:
      print 'player is ', self.state.player
      self.state.max_v = 1
      self.state.min_v = 2
      self.ai_first.setVisible(False)
      print 'button ai_first exists', hasattr(self, 'ai_first')

      self.state.print_me()
      next_state = ab(self.state)
      self.state = next_state
      self.state_to_grid(next_state)
      print '[after]player is ', self.state.player

    elif sender == self.new_game:
      self.start_new_game()

    else:
      print 'player is ', self.state.player
      '''
      self.g.setText(0, 1, 'wassup')
      self.g.setText(p['x'], p['y'], str(self.state.min_v))
      '''
      if self.ai_first.isVisible():
        print 'Setting state.max_v'
        self.state.max_v = 2
        self.state.min_v = 1
        self.ai_first.setVisible(False)
      p = sender.point
      self.g.setText(p['y'], p['x'], str(self.state.player))

      self.state = self.grid_to_state()
      self.check_for_tie() # end 1
      if is_win(self.state):
        self.state_to_grid(self.state, game_over=True, over_message='You won! This should not happen. This is a bug. Please email [email protected] describing the conditions of the game.')

      self.state.player = next_player(self.state.player)

      self.state.print_me()
      next_state = ab(self.state)
      self.state = next_state
      self.state_to_grid(next_state)
      self.check_for_tie() # end 1
      if is_win(self.state):
        self.state_to_grid(self.state, game_over=True, over_message='You lost! Better luck next time.')

  def check_for_tie(self):
    if is_over(self.state):
      self.state_to_grid(self.state, game_over=True, over_message='The game is a tie.')


  def state_to_grid(self, state, game_over=False, over_message=''):
    if over_message:
      self.game_resolution.setText(over_message)
      self.game_resolution.setVisible(True)
    else:
      self.game_resolution.setVisible(False)
    board = state.board
    for y in range(3):
      for x in range(3):
        if board[y][x] == 0:
          if not game_over:
            b = Button('Press', self)
            b.point = {'x':x, 'y':y}
            self.g.setWidget(y, x, b)
          else:
            self.g.setText(y, x, '-')
        elif board[y][x] == '1':
          self.g.setText(y, x, '1')
        elif board[y][x] == '2':
          self.g.setText(y, x, '2')
        else:
          print 'state_to_grid exception'
          #assert False

  def grid_to_state(self):
    next_state = State()
    for y in range(3):
      for x in range(3):
        if isinstance(self.g.getWidget(y, x), Button):
          print y, x
          next_state.board[y][x] = 0
        elif self.g.getText(y, x) == '1' or self.g.getText(y, x) == '2':
          next_state.board[y][x] = int(self.g.getText(y,x))
        else:
          print 'grid_to_state exception'
          #assert False
    next_state.min_v = self.state.min_v
    next_state.max_v = self.state.max_v
    next_state.player = self.state.player
    return next_state

  def init(self):
    for y in range(3):
      for x in range(3):
        b = Button('Press', self)
        b.point = {'x':x, 'y':y}
        self.g.setWidget(y, x, b)
예제 #16
0
    def __init__(self, statusSummary, sender):
        VerticalPanel.__init__(self, Spacing=10,
                               StyleName='userlist-error-box')
        self.add(HTML("We're currently working on users you mentioned",
                      StyleName='userlist-error-title'))

        self.add(HTML(
            """<p>Below is a summary of work already in progress, or
        queued, which must complete before we can run your query. Please
        note that Tickery is subject to Twitter's API rate limiting and
        general network latency, so you may need to be patient. We'll get
        there!</p>

        <p><a href=\"%s\">Here's a link</a> to this results page so you can
        come back to see how we're doing.  You can also click %r again to
        see updated progress.</p>""" %
            (sender.resultsLink(), go.goButtonText),
            StyleName='userlist-error-text'))

        nRows = 0

        underway = statusSummary['underway']
        nUnderway = len(underway)
        queued = statusSummary['queued']
        nQueued = len(queued)

        nCols = 4
        width = 200

        if nUnderway:
            nRows += nUnderway + 1
        if nQueued:
            nRows += nQueued + 1

        g = Grid(nRows, nCols, StyleName='users')
        g.setCellPadding(2)
        cellFormatter = g.getCellFormatter()
        row = 0

        if nUnderway:
            g.setHTML(row, 0, 'Users currently being processed&nbsp;')
            cellFormatter.setStyleName(row, 0, 'title-lhs')
            g.setText(row, 1, 'Name')
            cellFormatter.setStyleName(row, 1, 'title')
            g.setText(row, 2, 'Friends')
            cellFormatter.setStyleName(row, 2, 'title')
            g.setText(row, 3, '% done')
            cellFormatter.setStyleName(row, 3, 'title')
            cellFormatter.setWidth(row, 3, width)
            row += 1

            for u, nFriends, done in underway:
                cellFormatter.setStyleName(row, 0, 'blank')
                n = utils.splitthousands(nFriends)
                g.setHTML(row, 1, utils.screennameToTwitterLink(u))
                g.setHTML(row, 2, utils.screennameToTwitterFriendsLink(u, n))
                cellFormatter.setHorizontalAlignment(row, 2, 'right')

                pct = '%d' % int(done * 100.0)
                left = Label(pct, StyleName='done', Width=int(done * width))
                g.setWidget(row, 3, left)

                row += 1

        if nQueued:
            g.setHTML(row, 0, 'Users queued for processing&nbsp;')
            cellFormatter.setStyleName(row, 0, 'title-lhs')
            g.setText(row, 1, 'Name')
            cellFormatter.setStyleName(row, 1, 'title')
            g.setText(row, 2, 'Friends')
            cellFormatter.setStyleName(row, 2, 'title')
            g.setText(row, 3, 'Queue position')
            cellFormatter.setStyleName(row, 3, 'title')
            row += 1

            for u, nFriends, pos in queued:
                cellFormatter.setStyleName(row, 0, 'blank')
                n = utils.splitthousands(nFriends)
                g.setHTML(row, 1, utils.screennameToTwitterLink(u))
                g.setHTML(row, 2, utils.screennameToTwitterFriendsLink(u, n))
                cellFormatter.setHorizontalAlignment(row, 2, 'right')
                g.setText(row, 3, pos)
                cellFormatter.setHorizontalAlignment(row, 3, 'right')
                row += 1

        self.add(g)
예제 #17
0
파일: queued.py 프로젝트: jdunck/Tickery
class Queued(HorizontalPanel):
    def __init__(self):
        HorizontalPanel.__init__(self, Spacing=4)
        self.add(Label("Queued:", StyleName="section"))
        s = ScrollPanel()
        self.add(s)
        v = VerticalPanel()
        s.add(v)
        self.queued = Grid(StyleName="users")
        v.add(self.queued)
        self.button = Button("Refresh", self, StyleName="refresh")
        self.add(self.button)
        self.err = Label()
        self.add(self.err)
        self.update()

    def update(self):
        remote = server.AdminService()
        id = remote.getQueued(self)
        if id < 0:
            self.err.setText("oops: could not call getQueued")

    def onRemoteResponse(self, result, request_info):
        self.button.setEnabled(True)
        self.queued.clear()
        if not result:
            self.queued.resize(1, 1)
            self.queued.setText(0, 0, "No users are queued for addition.")
        else:
            self.queued.resize(len(result) + 1, 4)
            self.queued.setText(0, 0, "Pos")
            self.queued.setText(0, 1, "Name")
            self.queued.setText(0, 2, "Friends")
            self.queued.setText(0, 3, "Queued at")
            row = 1
            for name, nFriends, time in result:
                self.queued.setText(row, 0, row)
                self.queued.setText(row, 1, name)
                self.queued.setText(row, 2, nFriends)
                self.queued.setText(row, 3, time)
                row += 1

    def onRemoteError(self, code, message, request_info):
        self.button.setEnabled(True)
        self.err.setText("Could not getQueued: " + message)

    def onClick(self, sender):
        self.err.setText("")
        self.button.setEnabled(False)
        self.update()