Beispiel #1
0
    def replaceLinks(self, tagname="a", use_page_href=True, ajaxify=False):
        """ replaces <tag href="#pagename">sometext</tag> with:
            Hyperlink("sometext", "pagename").  Hyperlinks use
            the History module so the notification will come
            in on an onHistoryChanged.
        """
        self._clear_hyperlinks()
        tags = self.findTags(tagname)
        pageloc = Window.getLocation()
        pagehref = pageloc.getPageHref()
        for el in tags:
            href = el.href
            l = href.split("#")
            if len(l) != 2:
                continue
            if use_page_href and not l[0].startswith(pagehref):
                continue
            token = l[1]
            if not token:
                continue
            html = DOM.getInnerHTML(el)
            parent = DOM.getParent(el)
            index = DOM.getChildIndex(parent, el)
            if ajaxify:
                token = '!%s' % token
            hl = Hyperlink(TargetHistoryToken=token,
                           HTML=html,
                           Element=DOM.createSpan())
            DOM.insertChild(parent, hl.getElement(), index)
            parent.removeChild(el)

            self.children.insert(index, hl)
            hl.setParent(self)
            self.hyperlinks.append(hl)
Beispiel #2
0
 def replaceLinks(self, tagname="a"):
     """ replaces <tag href="#pagename">sometext</tag> with:
         Hyperlink("sometext", "pagename")
     """
     tags = self.findTags(tagname)
     pageloc = Window.getLocation()
     pagehref = pageloc.getPageHref()
     for el in tags:
         href = el.href
         l = href.split("#")
         if len(l) != 2:
             continue
         if l[0] != pagehref:
             continue
         token = l[1]
         if not token:
             continue
         html = DOM.getInnerHTML(el)
         parent = DOM.getParent(el)
         index = DOM.getChildIndex(parent, el)
         hl = Hyperlink(TargetHistoryToken=token,
                        HTML=html,
                        Element=DOM.createSpan())
         DOM.insertChild(parent, hl.getElement(), index)
         self.children.insert(index, hl)
         parent.removeChild(el)
Beispiel #3
0
    def _gridCancelLink(self):
        bh4 = Hyperlink(self.cancel)
        bh4.addClickListener(getattr(self, 'onCancel'))

        b2 = SimplePanel()
        b2.add(bh4)
        b2.addStyleName("calendar-cancel")
        self.vp.add(b2)
Beispiel #4
0
 def __init__(self, img, **kwargs):
     self.mouseListeners = []
     if not kwargs.has_key('StyleName'):
         kwargs['StyleName'] = 'gwt-HyperlinkImage'
     Hyperlink.__init__(self, **kwargs)
     DOM.appendChild(DOM.getFirstChild(self.getElement()), img.getElement())
     img.unsinkEvents(Event.ONCLICK | Event.MOUSEEVENTS)
     self.sinkEvents(Event.ONCLICK | Event.MOUSEEVENTS)
Beispiel #5
0
    def _gridCancelLink(self):
        bh4 = Hyperlink(self.cancel)
        bh4.addClickListener(getattr(self, 'onCancel'))

        b2 = SimplePanel()
        b2.add(bh4)
        b2.addStyleName("calendar-cancel")
        self.vp.add(b2)
Beispiel #6
0
    def __init__(self):
        GChart.__init__(self)

        self.SELECTION_CURVE = 0 # curve index of selection cursor
        self.p1 = Point(); # first corner (@mousedown) of selection rect
        self.p2 = Point(); # second corner (@mouseup) of selection rect
        self.selecting = False
        self.moving = False
        self.ctrlPressed = False; # as evaluated at mouse down
        self.altPressed = False
        # (# zoom ins) - (# zoom outs) since selection rect created
        # lets us know when to restore initial plot area limits/cursor
        self.zoomIndex = 0
        self.zoomController = ZoomController(self)
        # min plot area fraction zoom selection cursor must capture
        
        self.initialPlotRegion = Region()
        self.initialSelectionRegion = Region()
    
        self.setChartTitle(
        "Drag to pan; Press Ctrl while drag-selecting a rectangle to zoom")
        self.setChartSize(500, 150)
        a = Hyperlink("huh?")
        a.setPixelSize(10, 500)
        self.getYAxis().setAxisLabel(a)
        # another option is to use clipToDecoratedChart(True) instead.
        self.setClipToPlotArea(True)
        self.addCurve()
        for i in range(N_POINTS):
            self.getCurve().addPoint(i, math.sin((2* math.pi * i)/N_POINTS)*
                        math.sin(10*(2* math.pi * i)/N_POINTS))
        
        self.getCurve().getSymbol().setSymbolType(SymbolType.LINE)
        
        # will use this curve to create the selection cursor
        self.addCurve()
        self.getCurve().addPoint(-Double.MAX_VALUE, -Double.MAX_VALUE)
        self.getCurve().setVisible(False)
        # preferentially selects cursor over ordinary curves:
        self.getCurve().getSymbol().setDistanceMetric(0,0)
        self.getCurve().getSymbol().setHoverWidget(self.zoomController)
        self.getCurve().getSymbol().setHoverLocation( AnnotationLocation.CENTER)
        # hides hover-buttons when mouse is outside zoom-cursor
        self.getCurve().getSymbol().setBrushSize(0, 0)
        self.SELECTION_CURVE = self.getNCurves()-1
        # give them some x-panning space
        self.getXAxis().setAxisMin(0.25*N_POINTS)
        self.getXAxis().setAxisMax(0.75*N_POINTS)
        
        self.getYAxis().setTickLabelThickness(50)
        self.getYAxis().setAxisMin(-0.5)
        self.getYAxis().setAxisMax(0.5)
        
        """
        self.addClickListener(self)
        """
        self.addMouseListener(self)
Beispiel #7
0
    def onBrowserEvent(self, event):
        type = DOM.eventGetType(event)
        if type == 'mousedown' or type == 'mouseup' or type == 'mousemove' or type == 'mouseover' or type == 'mouseout':
            MouseListener.fireMouseEvent(self.mouseListeners, self, event)
            # stop event falling through esp. for drag on image
            DOM.eventPreventDefault(event)

        else:
            Hyperlink.onBrowserEvent(self, event)
Beispiel #8
0
    def onRemoteResponse(self, response, request_info):
#0  (x.id,               
#1 x.problem.name, 
#2 x.problem_id, 
#3 x.submitter.handle, 
#4 x.submitter_id,  
#5 status(x.code),
#6 x.judgeTime,
#7 x.submitTime )
        if response:
            for line in response:
                if line[0] in self.id2row:
                    idx =self.cnt- self.id2row[line[0]]
                    #alert(self.id2row[line[0]] + " " + idx + " " + self.cnt);
                    #return
                else:
                    idx = 1
                    self.table.insertRow(1)
                    self.id2row[line[0]] = self.cnt
                    self.cnt += 1          
                #Hyperlink
                self.table.setText(idx, 0, line[7])
                pl=Hyperlink(line[1])
                pl.addClickListener(self.problemLambda(line[2]));
                self.table.setWidget(idx, 1, pl)
                ul=Hyperlink(line[3])
                ul.addClickListener(self.userLambda(line[4]) );
                self.table.setWidget(idx, 2, ul)
                sl=Hyperlink(line[5])
                sl.addClickListener(self.submissionLambda(line[0]))
                self.table.setWidget(idx, 3, sl)
                if line[6] != 'None': self.time = max(self.time, line[6], line[7])
                else: self.time = max(self.time, line[7])
Beispiel #9
0
 def __init__(self, remove_callback):
     self._remove_callback = remove_callback
     self.panel = VerticalPanel()
     self.panel.add(HTML(self.desc(), StyleName='DisplayMath'))
     self.value_arrays = []
     for va in self._gen_arrays():
         self.value_arrays.append(va)
         self.panel.add(va.panel)
     link = Hyperlink("remove", StyleName="action")
     link.addClickListener(getattr(self, '_remove'))
     self.panel.add(link)
Beispiel #10
0
    def __init__(self, format='%d-%m-%Y'):
        DateSelectedHandler.__init__(self)
        if self.img_base is None:
            self.img_base = pygwt.getImageBaseURL(True)
        if self.icon_img is None:
            self.icon_img = self.img_base + 'icon_calendar.gif'
        self.format = format
        self.tbox = TextBox()
        self.tbox.setVisibleLength(10)
        # assume valid sep is - / . or nothing
        if format.find('-') >= 0:
            self.sep = '-'
        elif format.find('/') >= 0:
            self.sep = '/'
        elif format.find('.') >= 0:
            self.sep = '.'
        else:
            self.sep = ''
        # self.sep = format[2] # is this too presumptious?
        self.calendar = Calendar()
        self.img = Image(self.icon_img)
        self.img.addStyleName(self.icon_style)
        self.calendarLink = HyperlinkImage(self.img)
        self.todayLink = Hyperlink(self.today_text)
        self.todayLink.addStyleName(self.today_style)
        #
        # lay it out
        #
        hp = HorizontalPanel()
        hp.setSpacing(2)
        vp = VerticalPanel()
        hp.add(self.tbox)
        vp.add(self.calendarLink)
        vp.add(self.todayLink)
        #vp.add(self.calendar)
        hp.add(vp)

        Composite.__init__(self)
        self.initWidget(hp)
        #
        # done with layout, so now set up some listeners
        #
        self.tbox.addFocusListener(self) # hook to onLostFocus
        self.calendar.addSelectedDateListener(getattr(self, "onDateSelected"))
        self.todayLink.addClickListener(getattr(self, "onTodayClicked"))
        self.calendarLink.addClickListener(getattr(self, "onShowCalendar"))

        self.tbox.addChangeListener(getattr(self, "onFieldChanged"))
        self.tbox.addInputListener(getattr(self, "onFieldChanged"))

        self._last_date = None
Beispiel #11
0
 def __init__(self):
     self.WEIGHT_TYPES = [
         ProductWeights, OrderDependentWeights, PODWeights,
         ProjectionDependentWeights
     ]
     self._add_dialog, self._wtype = self._create_add_dialog()
     self.panel = VerticalPanel()
     self._list_panel = VerticalPanel(Spacing=8)
     self.panel.add(self._list_panel)
     link = Hyperlink("add...", StyleName="action")
     link.addClickListener(getattr(self, 'show_add_dialog'))
     self.panel.add(link)
     self._weights = []
     self._dimension = 0
Beispiel #12
0
    def __init__(self):
        SimplePanel.__init__(self)

        History.addHistoryListener(self)

        vPanel = VerticalPanel()

        self.stateDisplay = Label()
        vPanel.add(self.stateDisplay)

        hPanel = HorizontalPanel(Spacing=5)
        hPanel.add(Hyperlink("State 1", False, "state number 1"))
        hPanel.add(Hyperlink("State 2", False, "state number 2"))

        vPanel.add(hPanel)
        self.add(vPanel)
Beispiel #13
0
 def __init__(self, remove_callback):
     self._remove_callback = remove_callback
     self.dimension = None
     self.panel = VerticalPanel()
     self.panel.add(
         HTML(
             "Enter the mapping between coordinates and weights.  "
             "Each line must be <b>comma-separated list of coordinates</b> "
             "followed by a <b>colon</b> and a <b>weight value</b>.  "
             "Spaces are ignored.<br/>"
             "Example line: <code>1,2,5: 0.7</code>."))
     self._text = TextArea(CharacterWidth=20, VisibleLines=8)
     self.panel.add(self._text)
     link = Hyperlink("remove", StyleName="action")
     link.addClickListener(getattr(self, '_remove'))
     self.panel.add(link)
Beispiel #14
0
    def __init__(self, latsize):
        self._latsize = latsize
        self.panel = HorizontalPanel(Spacing=8)

        self.panel.add(
            HTML(r"<strong>Generating vector</strong> (\(\boldsymbol a\)): ",
                 StyleName="CaptionLabel"))
        self._array = TextBoxArray('1', show_indices=False)
        self.panel.add(self._array.panel)

        link = Hyperlink("Korobov...", StyleName="action")
        link.addClickListener(getattr(self, 'show_korobov_dialog'))
        self.panel.add(link)

        self._korobov_dialog, self._korobov_param = self._create_korobov_dialog(
        )
Beispiel #15
0
 def onRemoteResponse(self, response, request_info):
     for line in response:
         l=Hyperlink(line[1])
         l.addClickListener(self.problemLambda(line[1]));
         self.table.setWidget(self.cnt, 0, l)
         l=Hyperlink(line[0])
         l.addClickListener(self.problemLambda(line[1]));
         self.table.setWidget(self.cnt, 1, l)
         l=Hyperlink(line[3])
         l.addClickListener(self.userLambda(line[2]));
         self.table.setWidget(self.cnt, 2, l)
         self.app.submitTab.problem.insertItem(line[0]+" ("+line[1]+")",line[1],-1)
         self.cnt += 1       
Beispiel #16
0
 def onBreadcrumbsChanged(self, crumbs):
     self.crumbs.clear()
     for n, crumb in enumerate(crumbs):
         if n < len(crumbs) - 1:
             self.crumbs.add(Hyperlink(text=crumb['label'], TargetHistoryToken=crumb['token']))
             self.crumbs.add(Label('>'))
         else:
             self.crumbs.add(HTML('<b>%s</b>' % crumb['label']))
Beispiel #17
0
    def __init__(self, label, expr_var, expr_var_desc, default_value='0.0'):
        self._expr_var = expr_var
        self._expr_var_desc = expr_var_desc
        self._expr_dialog, self._expr = self._create_expr_dialog()
        link = Hyperlink("expression...", StyleName="action")
        link.addClickListener(getattr(self, 'show_expr_dialog'))

        self.panel = HorizontalPanel(Spacing=8)
        self._array = TextBoxArray(default_value, show_indices=True)

        panel = VerticalPanel(Spacing)
        panel.add(HTML("{}: ".format(label), StyleName="CaptionLabel"))
        panel.add(HTML("{}: ".format(self._expr_var),
                       StyleName="CaptionLabel"))
        self.panel.add(panel)
        self.panel.add(self._array.panel)
        self.panel.add(link)
Beispiel #18
0
    def onRemoteResponse(self, response, request_info):
        while self.cnt > 1:
            self.cnt -= 1
            self.table.removeRow(self.cnt)

        for line in response:
            l=Hyperlink(line[0])
            l.addClickListener(self.userLambda(line[0]));
            self.table.setWidget(self.cnt, 0, l)
            l=Hyperlink(line[1])
            l.addClickListener(self.userLambda(line[0]));
            self.table.setWidget(self.cnt, 1, l)
            l=Hyperlink(line[2])
            l.addClickListener(self.userLambda(line[0]));
            self.table.setWidget(self.cnt, 2, l)
            self.cnt += 1       
Beispiel #19
0
def drawControl(container):
    bar = HorizontalPanel(ID='aur-search-bar', VerticalAlignment='middle')
    adv = HorizontalPanel(ID='aur-search-advanced', Visible=False)
    adv_toggle = Hyperlink(Text='Advanced', StyleName='aur-link-stateless aur-search-bar-advanced', TargetHistoryToken=History.getToken())
    query = TextBox(Text='enter search term...', StyleName='aur-search-bar-query')
    go = Button(HTML='Go', StyleName='aur-search-bar-submit')

    container.add(bar)
    container.add(adv)

    # slight workaround to make sure the 'Advanced' toggle doesn't change the page
    def updateAdvToken(token):
        adv_toggle.setTargetHistoryToken(token)
    obj = object()
    setattr(obj, 'onHistoryChanged', updateAdvToken)
    History.addHistoryListener(obj)

    # clickListener to toggle the advanced section
    def toggleAdv(sender):
        if adv.isVisible():
            adv.setVisible(False)
            query.setEnabled(True)
            adv_toggle.setText('Advanced')
        else:
            adv.setVisible(True)
            query.setEnabled(False)
            adv_toggle.setText('Basic')
    adv_toggle.addClickListener(toggleAdv)

    def doGo():
        History.newItem('/package/search')
    go.addClickListener(doGo)

    bar.add(Label('Search Criteria', StyleName='aur-search-bar-label'))
    bar.add(query)
    bar.add(go)
    bar.add(Button(HTML='Orphans', StyleName='aur-search-bar-submit'))
    bar.add(adv_toggle)

    drawAdvanced(adv)
Beispiel #20
0
    def _gridShortcutsLinks(self):

        #
        # some links & handlers
        #
        bh1 = Hyperlink(self.yesterday)
        bh1.addClickListener(getattr(self, 'onYesterday'))
        bh2 = Hyperlink(self.today)
        bh2.addClickListener(getattr(self, 'onToday'))
        bh3 = Hyperlink(self.tomorrow)
        bh3.addClickListener(getattr(self, 'onTomorrow'))

        b = HorizontalPanel()
        b.add(bh1)
        b.add(bh2)
        b.add(bh3)
        b.addStyleName("calendar-shortcuts")
        self.vp.add(b)
Beispiel #21
0
    def _gridShortcutsLinks(self):
        bh1 = Hyperlink(_("Current"))
        bh1.addClickListener(getattr(self, 'onToday'))

        b2 = Button(_("Choose"), self.onMonthSelected)

        bh3 = Hyperlink(self.cancel)
        bh3.addClickListener(getattr(self, 'onCancel'))

        b = HorizontalPanel()
        b.addStyleName("calendar-shortcuts")
        b.add(bh1)
        b.add(b2)
        b.add(bh3)

        self.vp.add(b)
Beispiel #22
0
def sect_markup(txt, name):

    res = ''
    idx = 0
    links = []

    while 1:
        prev_idx = idx
        idx = txt.find("L#{", idx)
        if idx == -1:
            res += txt[prev_idx:]
            break

        beg = txt[prev_idx:idx]
        idx += 3
        i = txt.find("}", idx)
        if i == -1:
            res += txt[prev_idx:]
            break

        if i == len(txt)-1:
            url = txt[idx:]
            end = ''
        else:
            url = txt[idx:i]
            end = txt[i+1:]

        res += beg
        idx = i+1

        page_url = "%s_" % name
        page_url += url.lower()
        i = HTMLPanel.createUniqueId()

        res += "<span id='%s'></span>" % str(i)

        links.append([i, Hyperlink(url, False, page_url)])

    if not links:
        return HTML(res)

    p = HTMLPanel(res)

    for il in links:
        i = il[0]
        l = il[1]
        p.add(l, i)

    return p
    def _gridShortcutsLinks(self):
        bh1 = Hyperlink(_("Current"))
        bh1.addClickListener(getattr(self, 'onToday'))

        b2 = Button(_("Choose"),self.onMonthSelected)

        bh3 = Hyperlink(self.cancel)
        bh3.addClickListener(getattr(self, 'onCancel'))
        
        
        b = HorizontalPanel()
        b.addStyleName("calendar-shortcuts")
        b.add(bh1)
        b.add(b2)
        b.add(bh3)
        
        self.vp.add(b)
Beispiel #24
0
    def drawFull(self, month, year):
        # should be called only once when we draw the calendar for
        # the first time
        self.vp = VerticalPanel()
        self.vp.setSpacing(2)
        self.vp.addStyleName("calendarbox calendar-module calendar")
        self.setWidget(self.vp)
        self.setVisible(False)
        #
        mth = int(month)
        yr = int(year)

        tp = HorizontalPanel()
        tp.addStyleName("calendar-top-panel")
        tp.setSpacing(5)

        h1 = Hyperlink('<<')
        h1.addClickListener(getattr(self, 'onPreviousYear'))
        h2 = Hyperlink('<')
        h2.addClickListener(getattr(self, 'onPreviousMonth'))
        h4 = Hyperlink('>')
        h4.addClickListener(getattr(self, 'onNextMonth'))
        h5 = Hyperlink('>>')
        h5.addClickListener(getattr(self, 'onNextYear'))

        tp.add(h1)
        tp.add(h2)

        # titlePanel can be changed, whenever we draw, so keep the reference
        txt = "<b>"
        txt += self.getMonthsOfYear()[mth-1] + " " + str(yr)
        txt += "</b>"
        self.titlePanel = SimplePanel()
        self.titlePanel.setWidget(HTML(txt))
        self.titlePanel.setStyleName("calendar-center")

        tp.add(self.titlePanel)
        tp.add(h4)
        tp.add(h5)
        tvp = VerticalPanel()
        tvp.setSpacing(10)
        tvp.add(tp)

        self.vp.add(tvp)

        # done with top panel

        self.middlePanel = SimplePanel()
        grid = self.drawGrid(mth, yr)
        self.middlePanel.setWidget(grid)
        self.vp.add(self.middlePanel)
        self.defaultGrid = grid

        self._gridShortcutsLinks()
        self._gridCancelLink()
        #
        # add code to test another way of doing the layout
        #
        self.setVisible(True)
        return
Beispiel #25
0
class DateField(Composite, DateSelectedHandler):

    img_base = None
    icon_img = None

    icon_style = "calendar-img"
    today_text = "Today"
    today_style = "calendar-today-link"

    def __init__(self, format='%d-%m-%Y'):
        DateSelectedHandler.__init__(self)
        if self.img_base is None:
            self.img_base = pygwt.getImageBaseURL(True)
        if self.icon_img is None:
            self.icon_img = self.img_base + 'icon_calendar.gif'
        self.format = format
        self.tbox = TextBox()
        self.tbox.setVisibleLength(10)
        # assume valid sep is - / . or nothing
        if format.find('-') >= 0:
            self.sep = '-'
        elif format.find('/') >= 0:
            self.sep = '/'
        elif format.find('.') >= 0:
            self.sep = '.'
        else:
            self.sep = ''
        # self.sep = format[2] # is this too presumptious?
        self.calendar = Calendar()
        self.img = Image(self.icon_img)
        self.img.addStyleName(self.icon_style)
        self.calendarLink = HyperlinkImage(self.img)
        self.todayLink = Hyperlink(self.today_text)
        self.todayLink.addStyleName(self.today_style)
        #
        # lay it out
        #
        hp = HorizontalPanel()
        hp.setSpacing(2)
        vp = VerticalPanel()
        hp.add(self.tbox)
        vp.add(self.calendarLink)
        vp.add(self.todayLink)
        #vp.add(self.calendar)
        hp.add(vp)

        Composite.__init__(self)
        self.initWidget(hp)
        #
        # done with layout, so now set up some listeners
        #
        self.tbox.addFocusListener(self) # hook to onLostFocus
        self.calendar.addSelectedDateListener(getattr(self, "onDateSelected"))
        self.todayLink.addClickListener(getattr(self, "onTodayClicked"))
        self.calendarLink.addClickListener(getattr(self, "onShowCalendar"))

        self.tbox.addChangeListener(getattr(self, "onFieldChanged"))
        self.tbox.addInputListener(getattr(self, "onFieldChanged"))

        self._last_date = None

    def emitSelectedDate(self):
        _d = self.getDate()
        if _d == self._last_date:
            return
        self._last_date = _d
        self.fireDateSelectedEvent(_d)

    def onFieldChanged(self, event):
        self.emitSelectedDate()

    def getTextBox(self):
        return self.tbox

    def getCalendar(self):
        return self.calendar

    def getDate(self):
        """ returns datetime.date object or None if empty/unparsable by current format"""
        _sdate = self.tbox.getText()
        try:
            return datetime.strptime(_sdate, self.format).date()
        except ValueError:
            return None

    def setID(self, id):
        self.tbox.setID(id)

    def onDateSelected(self, yyyy, mm, dd):
        secs = time.mktime((int(yyyy), int(mm), int(dd), 0, 0, 0, 0, 0, -1))
        d = time.strftime(self.format, time.localtime(secs))
        self.tbox.setText(d)
        self.emitSelectedDate()

    def onLostFocus(self, sender):
        #
        text = self.tbox.getText().strip()
        # if blank - leave it alone
        if text and len(text) == 8:
            # ok what format do we have? assume ddmmyyyy --> dd-mm-yyyy
            txt = text[0:2] + self.sep + text[2:4] + self.sep + text[4:8]
            self.tbox.setText(txt)
        self.emitSelectedDate()

    def onFocus(self, sender):
        pass

    def onTodayClicked(self, event):
        today = time.strftime(self.format)
        self.tbox.setText(today)
        self.emitSelectedDate()

    def onShowCalendar(self, sender):
        txt = self.tbox.getText().strip()
        try:
            if txt:
                _d = datetime.strptime(txt, self.format).date()
                self.calendar.setDate(_d)
        except ValueError: pass

        p = CalendarPopup(self.calendar)
        x = self.tbox.getAbsoluteLeft() + 10
        y = self.tbox.getAbsoluteTop() + 10
        p.setPopupPosition(x, y)
        p.show()
 def addAlgorithm(self, info):
     name = info.getName()
     link = Hyperlink(name, False, TargetHistoryToken=name)
     link.setStyleName("ks-AlgorithmItem")
     self.vp_list.add(link)
     self.Algorithms.append(info)
Beispiel #27
0
    def _gridShortcutsLinks(self):

        #
        # some links & handlers
        #
        bh1 = Hyperlink(self.yesterday)
        bh1.addClickListener(getattr(self, 'onYesterday'))
        bh2 = Hyperlink(self.today)
        bh2.addClickListener(getattr(self, 'onToday'))
        bh3 = Hyperlink(self.tomorrow)
        bh3.addClickListener(getattr(self, 'onTomorrow'))

        b = HorizontalPanel()
        b.add(bh1)
        b.add(bh2)
        b.add(bh3)
        b.addStyleName("calendar-shortcuts")
        self.vp.add(b)
Beispiel #28
0
    def drawFull(self, month, year):
        # should be called only once when we draw the calendar for
        # the first time
        self.vp = VerticalPanel()
        self.vp.setSpacing(2)
        self.vp.addStyleName("calendarbox calendar-module calendar")
        self.setWidget(self.vp)
        self.setVisible(False)
        #
        mth = int(month)
        yr = int(year)

        tp = HorizontalPanel()
        tp.addStyleName("calendar-top-panel")
        tp.setSpacing(5)

        h1 = Hyperlink('<<')
        h1.addClickListener(getattr(self, 'onPreviousYear'))
        h2 = Hyperlink('<')
        h2.addClickListener(getattr(self, 'onPreviousMonth'))
        h4 = Hyperlink('>')
        h4.addClickListener(getattr(self, 'onNextMonth'))
        h5 = Hyperlink('>>')
        h5.addClickListener(getattr(self, 'onNextYear'))

        tp.add(h1)
        tp.add(h2)

        # titlePanel can be changed, whenever we draw, so keep the reference
        txt = "<b>"
        txt += self.getMonthsOfYear()[mth - 1] + " " + str(yr)
        txt += "</b>"
        self.titlePanel = SimplePanel()
        self.titlePanel.setWidget(HTML(txt))
        self.titlePanel.setStyleName("calendar-center")

        tp.add(self.titlePanel)
        tp.add(h4)
        tp.add(h5)
        tvp = VerticalPanel()
        tvp.setSpacing(10)
        tvp.add(tp)

        self.vp.add(tvp)

        # done with top panel

        self.middlePanel = SimplePanel()
        grid = self.drawGrid(mth, yr)
        self.middlePanel.setWidget(grid)
        self.vp.add(self.middlePanel)
        self.defaultGrid = grid

        self._gridShortcutsLinks()
        self._gridCancelLink()
        #
        # add code to test another way of doing the layout
        #
        self.setVisible(True)
        return
Beispiel #29
0

if __name__ == '__main__':
    pyjd.setup("public/Anchor.html")
    # EXAMPLE 1
    a1 = Anchor(
        Widget=HTML('Test 1: Anchor to external site using HTML widget.'),
        Href='http://pyjs.org',
        Title='Test1')
    RootPanel().add(a1)
    # EXAMPLE 2
    label = Label(text='Test 2: Click listener added to a label.')
    label.addClickListener(onClick)
    RootPanel().add(label)
    # EXAMPLE 3
    a2 = Hyperlink(text='Hyperlink', Element=DOM.createSpan())
    a2.setID('param1')
    a2.addClickListener(onClick)
    html2 = HTMLPanel(
        "Test 3: <span id ='t3'></span> added to HTMLPanel with click listener."
    )
    html2.add(a2, "t3")
    RootPanel().add(html2)
    # EXAMPLE 4
    hpanel = HorizontalPanel()
    hpanel.append(HTML('Test 4:  Anchor to external site using Image widget'))
    a3 = Anchor(Widget=Image('http://pyjs.org/assets/images/pyjs.128x128.png'),
                Href='http://pyjs.org',
                Title='Test4')
    hpanel.append(a3)
    RootPanel().add(hpanel)
 def addAlgorithm(self, info):
     name = info.getName()
     link = Hyperlink(name, False, TargetHistoryToken=name)
     link.setStyleName("ks-AlgorithmItem")
     self.vp_list.add(link)
     self.Algorithms.append(info)
Beispiel #31
0
class DateField(Composite):

    icon_img = "icon_calendar.gif"
    icon_style = "calendar-img"
    today_text = "Today"
    today_style = "calendar-today-link"

    def __init__(self, format='%d-%m-%Y'):
        self.format = format
        self.tbox = TextBox()
        self.tbox.setVisibleLength(10)
        # assume valid sep is - / . or nothing
        if format.find('-') >= 0:
            self.sep = '-'
        elif format.find('/') >= 0:
            self.sep = '/'
        elif format.find('.') >= 0:
            self.sep = '.'
        else:
            self.sep = ''
        # self.sep = format[2] # is this too presumptious?
        self.calendar = Calendar()
        self.img = Image(self.icon_img)
        self.img.addStyleName(self.icon_style)
        self.calendarLink = HyperlinkImage(self.img)
        self.todayLink = Hyperlink(self.today_text)
        self.todayLink.addStyleName(self.today_style)
        #
        # lay it out
        #
        hp = HorizontalPanel()
        hp.setSpacing(2)
        vp = VerticalPanel()
        hp.add(self.tbox)
        vp.add(self.calendarLink)
        vp.add(self.todayLink)
        #vp.add(self.calendar)
        hp.add(vp)

        Composite.__init__(self)
        self.initWidget(hp)
        #
        # done with layout, so now set up some listeners
        #
        self.tbox.addFocusListener(self) # hook to onLostFocus
        self.calendar.addSelectedDateListener(getattr(self, "onDateSelected"))
        self.todayLink.addClickListener(getattr(self, "onTodayClicked"))
        self.calendarLink.addClickListener(getattr(self, "onShowCalendar"))

    def getTextBox(self):
        return self.tbox

    def getCalendar(self):
        return self.calendar

    def getDate(self):
        """ returns datetime.date object or None if empty/unparsable by current format"""
        _sdate = self.tbox.getText()
        try:
            return datetime.strptime(_sdate, self.format).date()
        except ValueError:
            return None

    def setID(self, id):
        self.tbox.setID(id)

    def onDateSelected(self, yyyy, mm, dd):
        secs = time.mktime((int(yyyy), int(mm), int(dd), 0, 0, 0, 0, 0, -1))
        d = time.strftime(self.format, time.localtime(secs))
        self.tbox.setText(d)

    def onLostFocus(self, sender):
        #
        text = self.tbox.getText().strip()
        # if blank - leave it alone
        if text and len(text) == 8:
            # ok what format do we have? assume ddmmyyyy --> dd-mm-yyyy
            txt = text[0:2] + self.sep + text[2:4] + self.sep + text[4:8]
            self.tbox.setText(txt)

    def onFocus(self, sender):
        pass

    def onTodayClicked(self, event):
        today = time.strftime(self.format)
        self.tbox.setText(today)

    def onShowCalendar(self, sender):
        txt = self.tbox.getText().strip()
        try:
            if txt:
                _d = datetime.strptime(txt,self.format).date()
                self.calendar.setDate(_d)
        except ValueError: pass

        p = CalendarPopup(self.calendar)
        x = self.tbox.getAbsoluteLeft() + 10
        y = self.tbox.getAbsoluteTop() + 10
        p.setPopupPosition(x, y)
        p.show()
Beispiel #32
0
class LatBuilderWeb:
    def setStyleSheet(self, sheet):
        e = DOM.createElement('link')
        e.setAttribute('rel', 'stylesheet')
        e.setAttribute('type', 'text/css')
        e.setAttribute('href', sheet)
        html = Window.getDocumentRoot().parentElement
        head = html.getElementsByTagName('head').item(0)
        head.appendChild(e)

    def includeMathJax(self, config):
        html = Window.getDocumentRoot().parentElement
        head = html.getElementsByTagName('head').item(0)

        e = DOM.createElement('script')
        e.setAttribute('type', 'text/javascript')
        e.setAttribute(
            'src', 'http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=' +
            config)
        head.appendChild(e)

        e = DOM.createElement('script')
        e.setAttribute('type', 'text/javascript')
        e.textContent = 'function Typeset() { MathJax.Hub.Queue(["Typeset",MathJax.Hub]); }'
        head.appendChild(e)

    def onModuleLoad(self):

        self.current_request = None

        Window.setTitle("Lattice Builder Web Interface")
        self.setStyleSheet("./LatBuilderWeb.css")
        self.includeMathJax('TeX-AMS-MML_HTMLorMML')

        self.TEXT_WAITING = "Lattice Builder is working..."
        self.TEXT_ERROR = "Server Error"
        self.FIGURES_OF_MERIT = [
            # (key, name)
            ('{cs}P2', 'P2'),
            ('{cs}P4', 'P4'),
            ('{cs}P6', 'P6'),
            ('{cs}R{alpha}', 'R_alpha'),
            ('spectral', 'spectral'),
        ]
        self.CONSTRUCTION_METHODS = [
            ('explicit:{genvec}', "Explicit (Evaluation)",
             "Evaluates the figure of merit for a given generating vector.<br/>"
             "<strong>Please specify the generating vector in the Lattice "
             "Properties panel above.</strong>"),
            ('exhaustive', "Exhaustive",
             "Examines all generating vectors and retains the best one."),
            ('random:{samples}', "Random",
             "Examines a number of randomly selected generating vectors and "
             "retains the best one."),
            ('Korobov', "Korobov",
             "Examines all generating vectors of the form (1, a, a^2 mod n, "
             "..., a^s mod n) and retains the best one."),
            ('random-Korobov:{samples}', "Random Korobov",
             "Examines a number of randomly selected generating vectors of "
             "the form (1, a, a^2 mod n, ..., a^s mod n) and retains the "
             "best one."),
            ('CBC', "Component-by-Component",
             "Examines all possible values of the components of the "
             "generating vector and selects the best ones, one coordinate "
             "at a time."),
            ('random-CBC:{samples}', "Random Component-by-Component",
             "Examines a number of randomly selected values of the "
             "components of the generating vector and selects the best "
             "ones, one coordinate at a time."),
            ('fast-CBC', "Fast Component-by-Component",
             "Examines all possible values of the components of the "
             "generating vector and selects the best ones, one coordinate "
             "at a time.  Computation is accelerated by using fast "
             "Fourier transforms."),
        ]
        self.COMBINER_TYPES = [
            ('level:max', 'highest level'),
            ('sum', 'weighted sum'),
            ('max', 'maximum weighted value'),
        ]
        self.NORMALIZATION_TYPES = [
            ('norm:P{alpha}-SL10', 'SL10 P-alpha'),
            ('norm:P{alpha}-DPW08', 'DPW08 P-alpha'),
        ]

        captionstyle = {
            'Width': '10em',
            'HorizontalAlignment': 'right',
        }

        self.remote = LatBuilderService()
        WeightValuesArray.REMOTE = self.remote

        main_panel = VerticalPanel(Spacing=30)

        # information

        info = """<h2>Lattice Builder Web Interface</h2>
        <p>This Web interface allows
        <a href="https://github.com/mungerd/latbuilder#readme">Lattice Builder</a>
        users to call the executable program without having to construct the
        command line explicitly.
        </p>
        <p>Enter the construction parameters below, and press the <em>Search for
        Good Lattices</em> button.  The results will show at the bottom.
        </p>"""

        main_panel.add(HTML(info))

        self.version_label = HTML()
        main_panel.add(self.version_label)
        self.remote.backend_version(self)

        params_panel = VerticalPanel(Spacing=15)
        main_panel.add(params_panel)

        # lattice type and size and dimension

        lat_panel = VerticalPanel()
        params_panel.add(CaptionPanel("Lattice Properties", lat_panel))
        lat_panel.add(
            HTML(
                r'\[ P_n = \left\{ (i \boldsymbol a \bmod n) / n \::\: i = 0, \dots, n \right\} \qquad (\boldsymbol a \in \mathbb Z^s) \]',
                StyleName='DisplayMath'))

        self.size = TextBox(Text="2^10")
        self.size.addChangeListener(self)

        self.embedded = CheckBox("embedded")
        self.embedded.addClickListener(self)

        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML(r"Size (\(n\)): ", StyleName="CaptionLabel"))
        panel.add(self.size)
        panel.add(self.embedded)
        lat_panel.add(panel)

        self.dimension = TextBox(Text="3")
        self.dimension.addChangeListener(self)

        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML(r"Dimension (\(s\)): ", StyleName="CaptionLabel"))
        panel.add(self.dimension)
        lat_panel.add(panel)

        self.generating_vector = GeneratingVector(self.size)
        self.generating_vector.panel.setVisible(False)
        lat_panel.add(self.generating_vector.panel)

        # figure of merit

        merit_panel = VerticalPanel()
        params_panel.add(CaptionPanel("Figure of Merit", merit_panel))
        merit_panel.add(
            HTML(
                r"\[ \left[ \mathcal D_q(P_n) \right]^q = "
                r"\sum_{\emptyset \neq u \subseteq \{1,\dots,s\}}"
                r"\gamma_u^q \, \left[\mathcal D_u(P_n)\right]^q"
                r"\qquad (q > 0) \]",
                StyleName='DisplayMath'))

        self.norm_type = TextBox(Text="2")
        self.norm_type.addChangeListener(self)

        panel = HorizontalPanel(Spacing=8)
        panel.add(
            HTML(r"Norm type (\(q\) or <b>inf</b>): ",
                 StyleName="CaptionLabel"))
        panel.add(self.norm_type)
        merit_panel.add(panel)

        self.merit = ListBox()
        self.merit.addChangeListener(self)
        for key, name in self.FIGURES_OF_MERIT:
            self.merit.addItem(name)

        self.merit_cs = CheckBox("Use coordinate-symmetric implementation",
                                 Checked=True)

        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Figure of merit: ", StyleName="CaptionLabel"))
        panel.add(self.merit)
        panel.add(self.merit_cs)
        merit_panel.add(panel)

        self.merit_alpha_panel = HorizontalPanel(Spacing=8)
        self.merit_alpha = TextBox(Text="2")
        self.merit_alpha_panel.add(
            HTML("Value of alpha: ", StyleName="CaptionLabel"))
        self.merit_alpha_panel.add(self.merit_alpha)
        merit_panel.add(self.merit_alpha_panel)

        # filters and combiner

        multilevel_panel = VerticalPanel(Spacing=8)
        self.multilevel_panel = CaptionPanel("Multilevel Filters and Combiner",
                                             multilevel_panel,
                                             Visible=False)
        params_panel.add(self.multilevel_panel)

        self.ml_normalization_enable = CheckBox("Normalization")
        self.ml_normalization_enable.addClickListener(self)
        multilevel_panel.add(self.ml_normalization_enable)

        self.ml_normalization_panel = VerticalPanel(Spacing=4,
                                                    Visible=False,
                                                    StyleName='SubPanel')
        multilevel_panel.add(self.ml_normalization_panel)

        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Normalization type: ", StyleName="CaptionLabel"))
        self.ml_normalization_type = ListBox()
        for key, name in self.NORMALIZATION_TYPES:
            self.ml_normalization_type.addItem(name, value=key)
        panel.add(self.ml_normalization_type)
        self.ml_normalization_panel.add(panel)

        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Minimum level: ", StyleName="CaptionLabel"))
        self.ml_min_level = TextBox(Text="1")
        panel.add(self.ml_min_level)
        self.ml_normalization_panel.add(panel)

        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Maximum level: ", StyleName="CaptionLabel"))
        self.ml_max_level = TextBox(Text="1")
        panel.add(self.ml_max_level)
        self.ml_normalization_panel.add(panel)

        self.ml_lowpass_enable = CheckBox("Low-pass filter")
        self.ml_lowpass_enable.addClickListener(self)
        multilevel_panel.add(self.ml_lowpass_enable)

        self.ml_lowpass_panel = VerticalPanel(Spacing=4,
                                              Visible=False,
                                              StyleName='SubPanel')
        multilevel_panel.add(self.ml_lowpass_panel)

        self.ml_lowpass = TextBox(Text="1.0")
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Low-pass threshold: ", StyleName="CaptionLabel"))
        panel.add(self.ml_lowpass)
        self.ml_lowpass_panel.add(panel)

        self.combiner_type = ListBox()
        for key, name in self.COMBINER_TYPES:
            self.combiner_type.addItem(name, value=key)
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Combiner: ", StyleName="CaptionLabel"))
        panel.add(self.combiner_type)
        multilevel_panel.add(panel)

        # weights

        self.weights = CompoundWeights()
        weights_panel = VerticalPanel()
        params_panel.add(CaptionPanel("Weights", weights_panel))
        weights_panel.add(
            HTML(r"\[ \gamma_u^p \qquad (u \subseteq \{1, \dots, s\}) \]",
                 StyleName='DisplayMath'))

        self.weights_power = TextBox(Text="2")
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML(r"Weights power (\(p\)): ", StyleName="CaptionLabel"))
        panel.add(self.weights_power)

        weights_panel.add(panel)
        weights_panel.add(self.weights.panel)
        self.weights.add_weights(ProductWeights)

        # construction method

        cons_panel = VerticalPanel()
        params_panel.add(CaptionPanel("Construction Method", cons_panel))

        self.construction = ListBox()
        self.construction.addChangeListener(self)
        for key, name, desc in self.CONSTRUCTION_METHODS:
            self.construction.addItem(name, value=key)
        self.construction_desc = HTML()

        panel = HorizontalPanel(Spacing=8)
        panel.add(self.construction)
        panel.add(self.construction_desc)
        cons_panel.add(panel)

        self.construction_samples_panel = HorizontalPanel(Spacing=8)
        self.construction_samples = TextBox(Text="30")
        self.construction_samples_panel.add(
            HTML("Random samples: ", StyleName="CaptionLabel"))
        self.construction_samples_panel.add(self.construction_samples)
        cons_panel.add(self.construction_samples_panel)

        # execute button

        panel = VerticalPanel(Spacing=8,
                              Width="100%",
                              HorizontalAlignment='center')
        main_panel.add(panel)

        button_panel = HorizontalPanel()
        panel.add(button_panel)
        self.button_search = Button("Search", self)
        button_panel.add(self.button_search)
        self.button_abort = Button("Abort", self, Visible=False)
        button_panel.add(self.button_abort)

        self.status = Label()
        panel.add(self.status)

        # results

        results_panel = VerticalPanel()
        self.results_panel = CaptionPanel("Results",
                                          results_panel,
                                          Visible=False)
        main_panel.add(self.results_panel)

        self.results_size = Label()
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Lattice size: ", StyleName="ResultsCaptionLabel"))
        panel.add(self.results_size)
        results_panel.add(panel)

        self.results_gen = Label()
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Generating vector: ", StyleName="ResultsCaptionLabel"))
        panel.add(self.results_gen)
        results_panel.add(panel)

        self.results_merit = Label()
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Merit value: ", StyleName="ResultsCaptionLabel"))
        panel.add(self.results_merit)
        results_panel.add(panel)

        self.results_cpu_time = Label()
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("CPU time: ", StyleName="ResultsCaptionLabel"))
        panel.add(self.results_cpu_time)
        results_panel.add(panel)

        self.results_cmd = Label(StyleName='Command', Visible=False)
        panel = HorizontalPanel(Spacing=8)

        self.results_cmd_link = Hyperlink("Command line: ",
                                          StyleName="ResultsCaptionLabel")
        self.results_cmd_link.addClickListener(self)
        panel.add(self.results_cmd_link)
        panel.add(self.results_cmd)
        results_panel.add(panel)

        # update selections

        self.construction.selectValue('CBC')

        self.onChange(self.size)
        self.onChange(self.construction)
        self.onChange(self.merit)
        self.onChange(self.dimension)
        self.onClick(self.embedded)
        self.onChange(self.ml_normalization_enable)
        self.onChange(self.ml_lowpass_enable)

        RootPanel().add(main_panel)

    def onChange(self, sender):

        if sender == self.construction:
            key, name, desc = \
                    self.CONSTRUCTION_METHODS[self.construction.getSelectedIndex()]
            self.construction_desc.setHTML(desc)
            self.construction_samples_panel.setVisible('{samples}' in key)
            if key.startswith('explicit'):
                self.generating_vector.panel.setVisible(True)
                self.button_search.setText("Evaluate Figure of Merit")
            else:
                self.generating_vector.panel.setVisible(False)
                self.button_search.setText("Search for Good Lattices")

        elif sender == self.merit:
            key, name = \
                    self.FIGURES_OF_MERIT[self.merit.getSelectedIndex()]
            self.merit_alpha_panel.setVisible('{alpha}' in key)
            self.merit_cs.setVisible('{cs}' in key)

        elif sender == self.size:
            max_level = LatSize(self.size.getText()).max_level
            if int(self.ml_min_level.getText()) > max_level:
                self.ml_min_level.setText(max_level)
            self.ml_max_level.setText(max_level)

        elif sender == self.dimension:
            # resize weights
            dimension = int(self.dimension.getText())
            self.generating_vector.dimension = dimension
            self.weights.dimension = dimension

        elif sender == self.norm_type:
            q = self.norm_type.getText().strip()
            self.merit_cs.setVisible(q == '2')
            if q == 'inf':
                self.weights_power.setText('1')
            else:
                self.weights_power.setText(q)

    def onClick(self, sender):
        if sender == self.embedded:
            self.multilevel_panel.setVisible(self.embedded.getChecked())

        elif sender == self.ml_normalization_enable:
            self.ml_normalization_panel.setVisible(
                self.ml_normalization_enable.getChecked())

        elif sender == self.ml_lowpass_enable:
            self.ml_lowpass_panel.setVisible(
                self.ml_lowpass_enable.getChecked())

        elif sender == self.results_cmd_link:
            self.results_cmd.setVisible(not self.results_cmd.getVisible())

        elif sender == self.button_search:

            self.results_panel.setVisible(False)
            self.button_search.setVisible(False)
            self.button_abort.setVisible(True)

            lattype = self.embedded.getChecked() and 'embedded' or 'ordinary'
            size = self.size.getText()
            dimension = self.dimension.getText()

            norm_type = self.norm_type.getText()
            merit, merit_name = \
                    self.FIGURES_OF_MERIT[self.merit.getSelectedIndex()]
            alpha = self.merit_alpha.getText()
            cs = norm_type == 2 and self.merit_cs.getChecked() and 'CS:' or ''

            weights_power = self.weights_power.getText()
            weights = [w.as_arg() for w in self.weights.weights]

            construction, construction_name, desc = \
                    self.CONSTRUCTION_METHODS[self.construction.getSelectedIndex()]
            samples = self.construction_samples.getText()
            genvec = ','.join(self.generating_vector.values)

            mlfilters = []
            combiner_type = None

            if self.embedded.getChecked():
                if self.ml_normalization_enable.getChecked():
                    ml_normalization_type, ml_normalization_name = \
                            self.NORMALIZATION_TYPES[self.ml_normalization_type.getSelectedIndex()]
                    ml_normalization_type += ':even:{},{}'.format(
                        self.ml_min_level.getText(),
                        self.ml_max_level.getText())
                    mlfilters.append(ml_normalization_type.format(alpha=alpha))
                if self.ml_lowpass_enable.getChecked():
                    mlfilters.append('low-pass:{}'.format(
                        self.ml_lowpass.getText()))

                combiner_type, combiner_name = \
                        self.COMBINER_TYPES[self.combiner_type.getSelectedIndex()]

            self.status.setText(self.TEXT_WAITING)

            self.current_request = self.remote.latbuilder_exec(
                lattype, size, dimension, norm_type,
                merit.format(alpha=alpha, cs=cs),
                construction.format(samples=samples, genvec=genvec), weights,
                weights_power, None, mlfilters, combiner_type, self)

        elif sender == self.button_abort:
            # Need to patch JSONService.sendRequest():
            #
            # return HTTPRequest().asyncPost(self.url, msg_data,
            #                                JSONResponseTextHandler(request_info)
            #                                False, self.content_type,
            #                                self.headers)
            if self.current_request:
                self.current_request.abort()
                self.current_request = None
            self.button_abort.setVisible(False)
            self.button_search.setVisible(True)

        elif sender == self.product_weights_expr_link:
            self.showDialog(self._product_weights_expr_dialog)

        elif sender == self.order_weights_expr_link:
            self.showDialog(self._order_weights_expr_dialog)

    def onRemoteResponse(self, response, request_info):
        try:
            if request_info.method == 'latbuilder_exec':
                self.button_search.setVisible(True)
                self.button_abort.setVisible(False)
                cmd, points, gen, merit, seconds = eval(response)
                self.results_size.setText(points)
                self.results_gen.setText(', '.join(gen))
                self.results_merit.setText(merit)
                self.results_cpu_time.setText(format_time(seconds=seconds))
                self.results_cmd.setText(cmd)
                self.results_panel.setVisible(True)
                self.status.setText("")
            elif request_info.method == 'backend_version':
                version = response
                self.version_label.setHTML(
                    "<b>Backend:</b> {}".format(version))
        except:
            self.status.setText(response.replace('\n', '  |  '))

    def onRemoteError(self, code, errobj, request_info):
        if request_info.method == 'latbuilder_exec':
            self.button_search.setVisible(True)
            self.button_abort.setVisible(False)
        message = errobj['message']
        if code != 0:
            self.status.setText("HTTP error %d: %s" % (code, message['name']))
        else:
            code = errobj['code']
            if code == -32603:
                self.status.setText("Aborted.")
            else:
                self.status.setText("JSONRPC Error %s: %s" % (code, message))
 def add(self, info):
     name = info.getName()
     link = Hyperlink(name, False, TargetHistoryToken=name)
     link.setStyleName("ks-SinkItem")
     self.vp_list.add(link)
     self.sinks.append(info)
Beispiel #34
0
    def onModuleLoad(self):

        self.current_request = None

        Window.setTitle("Lattice Builder Web Interface")
        self.setStyleSheet("./LatBuilderWeb.css")
        self.includeMathJax('TeX-AMS-MML_HTMLorMML')

        self.TEXT_WAITING = "Lattice Builder is working..."
        self.TEXT_ERROR = "Server Error"
        self.FIGURES_OF_MERIT = [
            # (key, name)
            ('{cs}P2', 'P2'),
            ('{cs}P4', 'P4'),
            ('{cs}P6', 'P6'),
            ('{cs}R{alpha}', 'R_alpha'),
            ('spectral', 'spectral'),
        ]
        self.CONSTRUCTION_METHODS = [
            ('explicit:{genvec}', "Explicit (Evaluation)",
             "Evaluates the figure of merit for a given generating vector.<br/>"
             "<strong>Please specify the generating vector in the Lattice "
             "Properties panel above.</strong>"),
            ('exhaustive', "Exhaustive",
             "Examines all generating vectors and retains the best one."),
            ('random:{samples}', "Random",
             "Examines a number of randomly selected generating vectors and "
             "retains the best one."),
            ('Korobov', "Korobov",
             "Examines all generating vectors of the form (1, a, a^2 mod n, "
             "..., a^s mod n) and retains the best one."),
            ('random-Korobov:{samples}', "Random Korobov",
             "Examines a number of randomly selected generating vectors of "
             "the form (1, a, a^2 mod n, ..., a^s mod n) and retains the "
             "best one."),
            ('CBC', "Component-by-Component",
             "Examines all possible values of the components of the "
             "generating vector and selects the best ones, one coordinate "
             "at a time."),
            ('random-CBC:{samples}', "Random Component-by-Component",
             "Examines a number of randomly selected values of the "
             "components of the generating vector and selects the best "
             "ones, one coordinate at a time."),
            ('fast-CBC', "Fast Component-by-Component",
             "Examines all possible values of the components of the "
             "generating vector and selects the best ones, one coordinate "
             "at a time.  Computation is accelerated by using fast "
             "Fourier transforms."),
        ]
        self.COMBINER_TYPES = [
            ('level:max', 'highest level'),
            ('sum', 'weighted sum'),
            ('max', 'maximum weighted value'),
        ]
        self.NORMALIZATION_TYPES = [
            ('norm:P{alpha}-SL10', 'SL10 P-alpha'),
            ('norm:P{alpha}-DPW08', 'DPW08 P-alpha'),
        ]

        captionstyle = {
            'Width': '10em',
            'HorizontalAlignment': 'right',
        }

        self.remote = LatBuilderService()
        WeightValuesArray.REMOTE = self.remote

        main_panel = VerticalPanel(Spacing=30)

        # information

        info = """<h2>Lattice Builder Web Interface</h2>
        <p>This Web interface allows
        <a href="https://github.com/mungerd/latbuilder#readme">Lattice Builder</a>
        users to call the executable program without having to construct the
        command line explicitly.
        </p>
        <p>Enter the construction parameters below, and press the <em>Search for
        Good Lattices</em> button.  The results will show at the bottom.
        </p>"""

        main_panel.add(HTML(info))

        self.version_label = HTML()
        main_panel.add(self.version_label)
        self.remote.backend_version(self)

        params_panel = VerticalPanel(Spacing=15)
        main_panel.add(params_panel)

        # lattice type and size and dimension

        lat_panel = VerticalPanel()
        params_panel.add(CaptionPanel("Lattice Properties", lat_panel))
        lat_panel.add(
            HTML(
                r'\[ P_n = \left\{ (i \boldsymbol a \bmod n) / n \::\: i = 0, \dots, n \right\} \qquad (\boldsymbol a \in \mathbb Z^s) \]',
                StyleName='DisplayMath'))

        self.size = TextBox(Text="2^10")
        self.size.addChangeListener(self)

        self.embedded = CheckBox("embedded")
        self.embedded.addClickListener(self)

        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML(r"Size (\(n\)): ", StyleName="CaptionLabel"))
        panel.add(self.size)
        panel.add(self.embedded)
        lat_panel.add(panel)

        self.dimension = TextBox(Text="3")
        self.dimension.addChangeListener(self)

        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML(r"Dimension (\(s\)): ", StyleName="CaptionLabel"))
        panel.add(self.dimension)
        lat_panel.add(panel)

        self.generating_vector = GeneratingVector(self.size)
        self.generating_vector.panel.setVisible(False)
        lat_panel.add(self.generating_vector.panel)

        # figure of merit

        merit_panel = VerticalPanel()
        params_panel.add(CaptionPanel("Figure of Merit", merit_panel))
        merit_panel.add(
            HTML(
                r"\[ \left[ \mathcal D_q(P_n) \right]^q = "
                r"\sum_{\emptyset \neq u \subseteq \{1,\dots,s\}}"
                r"\gamma_u^q \, \left[\mathcal D_u(P_n)\right]^q"
                r"\qquad (q > 0) \]",
                StyleName='DisplayMath'))

        self.norm_type = TextBox(Text="2")
        self.norm_type.addChangeListener(self)

        panel = HorizontalPanel(Spacing=8)
        panel.add(
            HTML(r"Norm type (\(q\) or <b>inf</b>): ",
                 StyleName="CaptionLabel"))
        panel.add(self.norm_type)
        merit_panel.add(panel)

        self.merit = ListBox()
        self.merit.addChangeListener(self)
        for key, name in self.FIGURES_OF_MERIT:
            self.merit.addItem(name)

        self.merit_cs = CheckBox("Use coordinate-symmetric implementation",
                                 Checked=True)

        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Figure of merit: ", StyleName="CaptionLabel"))
        panel.add(self.merit)
        panel.add(self.merit_cs)
        merit_panel.add(panel)

        self.merit_alpha_panel = HorizontalPanel(Spacing=8)
        self.merit_alpha = TextBox(Text="2")
        self.merit_alpha_panel.add(
            HTML("Value of alpha: ", StyleName="CaptionLabel"))
        self.merit_alpha_panel.add(self.merit_alpha)
        merit_panel.add(self.merit_alpha_panel)

        # filters and combiner

        multilevel_panel = VerticalPanel(Spacing=8)
        self.multilevel_panel = CaptionPanel("Multilevel Filters and Combiner",
                                             multilevel_panel,
                                             Visible=False)
        params_panel.add(self.multilevel_panel)

        self.ml_normalization_enable = CheckBox("Normalization")
        self.ml_normalization_enable.addClickListener(self)
        multilevel_panel.add(self.ml_normalization_enable)

        self.ml_normalization_panel = VerticalPanel(Spacing=4,
                                                    Visible=False,
                                                    StyleName='SubPanel')
        multilevel_panel.add(self.ml_normalization_panel)

        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Normalization type: ", StyleName="CaptionLabel"))
        self.ml_normalization_type = ListBox()
        for key, name in self.NORMALIZATION_TYPES:
            self.ml_normalization_type.addItem(name, value=key)
        panel.add(self.ml_normalization_type)
        self.ml_normalization_panel.add(panel)

        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Minimum level: ", StyleName="CaptionLabel"))
        self.ml_min_level = TextBox(Text="1")
        panel.add(self.ml_min_level)
        self.ml_normalization_panel.add(panel)

        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Maximum level: ", StyleName="CaptionLabel"))
        self.ml_max_level = TextBox(Text="1")
        panel.add(self.ml_max_level)
        self.ml_normalization_panel.add(panel)

        self.ml_lowpass_enable = CheckBox("Low-pass filter")
        self.ml_lowpass_enable.addClickListener(self)
        multilevel_panel.add(self.ml_lowpass_enable)

        self.ml_lowpass_panel = VerticalPanel(Spacing=4,
                                              Visible=False,
                                              StyleName='SubPanel')
        multilevel_panel.add(self.ml_lowpass_panel)

        self.ml_lowpass = TextBox(Text="1.0")
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Low-pass threshold: ", StyleName="CaptionLabel"))
        panel.add(self.ml_lowpass)
        self.ml_lowpass_panel.add(panel)

        self.combiner_type = ListBox()
        for key, name in self.COMBINER_TYPES:
            self.combiner_type.addItem(name, value=key)
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Combiner: ", StyleName="CaptionLabel"))
        panel.add(self.combiner_type)
        multilevel_panel.add(panel)

        # weights

        self.weights = CompoundWeights()
        weights_panel = VerticalPanel()
        params_panel.add(CaptionPanel("Weights", weights_panel))
        weights_panel.add(
            HTML(r"\[ \gamma_u^p \qquad (u \subseteq \{1, \dots, s\}) \]",
                 StyleName='DisplayMath'))

        self.weights_power = TextBox(Text="2")
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML(r"Weights power (\(p\)): ", StyleName="CaptionLabel"))
        panel.add(self.weights_power)

        weights_panel.add(panel)
        weights_panel.add(self.weights.panel)
        self.weights.add_weights(ProductWeights)

        # construction method

        cons_panel = VerticalPanel()
        params_panel.add(CaptionPanel("Construction Method", cons_panel))

        self.construction = ListBox()
        self.construction.addChangeListener(self)
        for key, name, desc in self.CONSTRUCTION_METHODS:
            self.construction.addItem(name, value=key)
        self.construction_desc = HTML()

        panel = HorizontalPanel(Spacing=8)
        panel.add(self.construction)
        panel.add(self.construction_desc)
        cons_panel.add(panel)

        self.construction_samples_panel = HorizontalPanel(Spacing=8)
        self.construction_samples = TextBox(Text="30")
        self.construction_samples_panel.add(
            HTML("Random samples: ", StyleName="CaptionLabel"))
        self.construction_samples_panel.add(self.construction_samples)
        cons_panel.add(self.construction_samples_panel)

        # execute button

        panel = VerticalPanel(Spacing=8,
                              Width="100%",
                              HorizontalAlignment='center')
        main_panel.add(panel)

        button_panel = HorizontalPanel()
        panel.add(button_panel)
        self.button_search = Button("Search", self)
        button_panel.add(self.button_search)
        self.button_abort = Button("Abort", self, Visible=False)
        button_panel.add(self.button_abort)

        self.status = Label()
        panel.add(self.status)

        # results

        results_panel = VerticalPanel()
        self.results_panel = CaptionPanel("Results",
                                          results_panel,
                                          Visible=False)
        main_panel.add(self.results_panel)

        self.results_size = Label()
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Lattice size: ", StyleName="ResultsCaptionLabel"))
        panel.add(self.results_size)
        results_panel.add(panel)

        self.results_gen = Label()
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Generating vector: ", StyleName="ResultsCaptionLabel"))
        panel.add(self.results_gen)
        results_panel.add(panel)

        self.results_merit = Label()
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Merit value: ", StyleName="ResultsCaptionLabel"))
        panel.add(self.results_merit)
        results_panel.add(panel)

        self.results_cpu_time = Label()
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("CPU time: ", StyleName="ResultsCaptionLabel"))
        panel.add(self.results_cpu_time)
        results_panel.add(panel)

        self.results_cmd = Label(StyleName='Command', Visible=False)
        panel = HorizontalPanel(Spacing=8)

        self.results_cmd_link = Hyperlink("Command line: ",
                                          StyleName="ResultsCaptionLabel")
        self.results_cmd_link.addClickListener(self)
        panel.add(self.results_cmd_link)
        panel.add(self.results_cmd)
        results_panel.add(panel)

        # update selections

        self.construction.selectValue('CBC')

        self.onChange(self.size)
        self.onChange(self.construction)
        self.onChange(self.merit)
        self.onChange(self.dimension)
        self.onClick(self.embedded)
        self.onChange(self.ml_normalization_enable)
        self.onChange(self.ml_lowpass_enable)

        RootPanel().add(main_panel)
Beispiel #35
0
 def addSink(self, info):
     name = info.getName()
     link = Hyperlink(name, False, TargetHistoryToken=name)
     link.setStyleName("ks-SinkItem")
     self.vp_list.add(link)
     self.sinks.append(info)
Beispiel #36
0
    def drawFull(self, month, year):
        # should be called only once when we draw the calendar for
        # the first time
        self.vp = VerticalPanel()
        self.vp.setSpacing(0)
        self.vp.setPadding(0)
        self.vp.addStyleName("calendarbox calendar-module calendar")
        self.setWidget(self.vp)
        self.setVisible(False)
        #
        mth = int(month)
        yr = int(year)

        tp = HorizontalPanel(Width="100%")
        tp.addStyleName("calendar-top-panel")
        tp.setSpacing(0)
        tp.setPadding(0)

        self.h1 = None
        self.h2 = None
        self.h4 = None
        self.h5 = None
        if self.backyear:
            self.h1 = self.bkls(self.backyear, StyleName="calendar-arrows")
            self.h1.addClickListener(getattr(self, 'onPreviousYear'))
            tp.add(self.h1)
            tp.setCellHorizontalAlignment(self.h1, "left")
        if self.backmonth:
            self.h2 = self.bkls(self.backmonth, StyleName="calendar-arrows")
            self.h2.addClickListener(getattr(self, 'onPreviousMonth'))
            tp.add(self.h2)
            tp.setCellHorizontalAlignment(self.h2, "left")

        # titlePanel can be changed, whenever we draw, so keep the reference
        txt = "<b>"
        txt += self.getMonthsOfYear()[mth-1] + " " + str(yr)
        txt += "</b>"
        self.titlePanel = SimplePanel()
        self.titlePanel.setWidget(HTML(txt))
        self.titlePanel.setStyleName("calendar-center")

        tp.add(self.titlePanel)
        tp.setCellHorizontalAlignment(self.titlePanel, "center")
        tp.setCellWidth(self.titlePanel, "100%")

        if self.fwdmonth:
            self.h4 = self.bkls(self.fwdmonth, StyleName="calendar-arrows")
            self.h4.addClickListener(getattr(self, 'onNextMonth'))
            tp.add(self.h4)
            tp.setCellHorizontalAlignment(self.h4, "right")
            tp.setCellWidth(self.h4, "100%")
            self.h4.setWidth("100%")
        if self.fwdyear:
            self.h5 = self.bkls(self.fwdyear, StyleName="calendar-arrows")
            self.h5.addClickListener(getattr(self, 'onNextYear'))
            tp.add(self.h5)
            tp.setCellHorizontalAlignment(self.h5, "right")

        tvp = VerticalPanel(Width="100%")
        tvp.setSpacing(2)
        tvp.add(tp)

        self.vp.add(tvp)

        # done with top panel

        self.middlePanel = SimplePanel()
        grid = self.drawGrid(mth, yr)
        self.middlePanel.setWidget(grid)
        self.vp.add(self.middlePanel)
        self.defaultGrid = grid

        if self.addbuttons:
            #
            # some links & handlers
            #
            bh1 = Hyperlink(self.yesterday)
            bh1.addClickListener(getattr(self, 'onYesterday'))
            bh2 = Hyperlink(self.today)
            bh2.addClickListener(getattr(self, 'onToday'))
            bh3 = Hyperlink(self.tomorrow)
            bh3.addClickListener(getattr(self, 'onTomorrow'))
            bh4 = Hyperlink(self.cancel)
            bh4.addClickListener(getattr(self, 'onCancel'))

            #
            # add code to test another way of doing the layout
            #
            b = HorizontalPanel()
            b.add(bh1)
            b.add(bh2)
            b.add(bh3)
            b.addStyleName("calendar-shortcuts")
            self.vp.add(b)
            b2 = SimplePanel()
            b2.add(bh4)
            b2.addStyleName("calendar-cancel")
            self.vp.add(b2)

        self.checkLinks(mth, yr)
        self.setVisible(True)
Beispiel #37
0
class DateField(Composite):

    icon_img = "icon_calendar.gif"
    icon_style = "calendar-img"
    today_text = "Today"
    today_style = "calendar-today-link"

    def __init__(self, format='%d-%m-%Y'):
        self.format = format
        self.tbox = TextBox()
        self.tbox.setVisibleLength(10)
        # assume valid sep is - / . or nothing
        if format.find('-') >= 0:
            self.sep = '-'
        elif format.find('/') >= 0:
            self.sep = '/'
        elif format.find('.') >= 0:
            self.sep = '.'
        else:
            self.sep = ''
        # self.sep = format[2] # is this too presumptious?
        self.calendar = Calendar()
        self.img = Image(self.icon_img)
        self.img.addStyleName(self.icon_style)
        self.calendarLink = HyperlinkImage(self.img)
        self.todayLink = Hyperlink(self.today_text)
        self.todayLink.addStyleName(self.today_style)
        #
        # lay it out
        #
        hp = HorizontalPanel()
        hp.setSpacing(2)
        vp = VerticalPanel()
        hp.add(self.tbox)
        vp.add(self.calendarLink)
        vp.add(self.todayLink)
        #vp.add(self.calendar)
        hp.add(vp)

        Composite.__init__(self)
        self.initWidget(hp)
        #
        # done with layout, so now set up some listeners
        #
        self.tbox.addFocusListener(self) # hook to onLostFocus
        self.calendar.addSelectedDateListener(getattr(self, "onDateSelected"))
        self.todayLink.addClickListener(getattr(self, "onTodayClicked"))
        self.calendarLink.addClickListener(getattr(self, "onShowCalendar"))

    def getTextBox(self):
        return self.tbox

    def getCalendar(self):
        return self.calendar

    def setID(self, id):
        self.tbox.setID(id)

    def onDateSelected(self, yyyy, mm, dd):
        secs = time.mktime((int(yyyy), int(mm), int(dd), 0, 0, 0, 0, 0, -1))
        d = time.strftime(self.format, time.localtime(secs))
        self.tbox.setText(d)

    def onLostFocus(self, sender):
        #
        text = self.tbox.getText().strip()
        # if blank - leave it alone
        if text and len(text) == 8:
            # ok what format do we have? assume ddmmyyyy --> dd-mm-yyyy
            txt = text[0:2] + self.sep + text[2:4] + self.sep + text[4:8]
            self.tbox.setText(txt)

    def onFocus(self, sender):
        pass

    def onTodayClicked(self, event):
        today = time.strftime(self.format)
        self.tbox.setText(today)

    def onShowCalendar(self, sender):
        p = CalendarPopup(self.calendar)
        x = self.tbox.getAbsoluteLeft() + 10
        y = self.tbox.getAbsoluteTop() + 10
        p.setPopupPosition(x, y)
        p.show()
Beispiel #38
0

def onClick(sender):
    Window.alert('Make service request using %s'%sender.getID())
    
if __name__ == '__main__':
    pyjd.setup("public/Anchor.html")
    # EXAMPLE 1
    a1 = Anchor(Widget = HTML('Test 1: Anchor to external site using HTML widget.'), Href='http://pyjs.org', Title = 'Test1')
    RootPanel().add(a1) 
    # EXAMPLE 2
    label = Label(text = 'Test 2: Click listener added to a label.')
    label.addClickListener(onClick)
    RootPanel().add(label) 
    # EXAMPLE 3
    a2 = Hyperlink(text = 'Hyperlink', Element = DOM.createSpan())
    a2.setID('param1')
    a2.addClickListener(onClick)
    html2=HTMLPanel("Test 3: <span id ='t3'></span> added to HTMLPanel with click listener.")
    html2.add(a2, "t3")
    RootPanel().add(html2)
    # EXAMPLE 4
    hpanel = HorizontalPanel()
    hpanel.append(HTML('Test 4:  Anchor to external site using Image widget'))
    a3 = Anchor(Widget = Image('http://pyjs.org/assets/images/pyjs.128x128.png'), Href='http://pyjs.org', Title = 'Test4')
    hpanel.append(a3)
    RootPanel().add(hpanel) 
    # EXAMPLE 5
    serverXml = \
"""
<html>