Ejemplo n.º 1
0
 def __init__(self, **kwargs):
     DialogWindow.__init__(self, modal=True, close=True)
     v = VerticalPanel()
     v.setWidth(300)
     # v.setHeight(500)
     self.setText("definition")
     self.setPopupPosition(100, 100)
     self.setStyleAttribute("background-color", "#ffffff")
     self.setStyleAttribute("color", "#9847a2")
     self.setStyleAttribute("border-width", "5px")
     self.setStyleAttribute("border-style", "solid")
     h = HorizontalPanel()
     self.textbox_name = TextBox()
     h.add(Label("name"))
     h.add(self.textbox_name)
     v.add(h)
     h = HorizontalPanel()
     self.textbox_scheme = TextBox()
     h.add(Label("print scheme"))
     h.add(self.textbox_scheme)
     v.add(h)
     self.add(v)
     self.theorems = list()
     self.radios = list()
     for t in Theorem.theorems:
         if t.formula.is_in_unique_form():
             self.theorems.append(t)
             self.radios.append(RadioButton("group1", ""))
             h = HorizontalPanel()
             h.add(self.radios[-1])
             im = Image()
             im.setUrl(latex_to_url(t.formula.to_latex()))
             h.add(im)
             v.add(h)
     v.add(Button("Done", self.done_click))
Ejemplo n.º 2
0
    def refresh_theorems(self, folder):
        self.remove_images()

        def onClick(theorem):
            def name(n):
                return "var" + str(n + 1)

            def print_scheme(n):
                return ["\\alpha", "\\beta", "\\gamma", "\\delta", "\\epsilon"][n]

            def poas(sender):
                if len(theorem.operations) == 1:
                    constants = [Operation("const" + str(i + 1), 0, print_scheme(i), name(i), Operation.EXPRESSION)
                                 for i in range(theorem.operations[0].no_of_args)]

                    def after1(f):
                        self.after(
                            theorem.formula.substitute_definition(Formula([theorem.operations[0]] + constants), f),
                            predecessors=[], rule_name="insert")

                    request_formula([op for op in proof.get_operations()] + constants,
                                    after1, type=('rel' if theorem.operations[0].type == Operation.RELATION else 'exp'))
                else:
                    self.after(theorem.formula, predecessors=[], rule_name="insert")

            return poas

        for ax in [x for x in Theorem.theorems if x.folder == folder]:
            im = Image()
            im.addClickListener(onClick(ax))
            im.setUrl(latex_to_url(ax.formula.to_latex()))
            self.pok.add(im)
            self.images.append(im)
Ejemplo n.º 3
0
 def add_formula(self, f):
     h = HorizontalPanel()
     im = Image()
     im.setUrl(latex_to_url(f.to_latex()))
     c = CheckBox()
     h.add(c)
     h.add(im)
     self.pok.add(h)
     self.checkbox_list.append(c)
     self.hpanel_list.append(h)
     self.image_list.append(im)
Ejemplo n.º 4
0
class FormulaBuilder(DialogWindow):

    def __init__(self, operations,after,type='rel'):
        DialogWindow.__init__(self, modal=True, close=True)
        self.formula = Formula([])
        self.after=after

        left = 100
        top = 100

        self.ops_with_buttons = [{"op": op, "button": Button(op.name, self)} for op in operations if op.available]
        dock = DockPanel()
        dock.setSpacing(3)

        for owb in self.ops_with_buttons:
            dock.add(owb['button'], DockPanel.NORTH)

        dock.setWidth("300")

        self.image = Image(latex_to_url(self.formula.fill_with_placeholders().to_latex()))
        dock.add(self.image, DockPanel.EAST)
        dock.setCellHorizontalAlignment(self.image, HasAlignment.ALIGN_TOP)

        self.doneButton=Button("Done",self)
        self.doneButton.setEnabled(False)
        dock.add(self.doneButton,DockPanel.SOUTH)

        dock.add(HTML(""),DockPanel.CENTER)

        self.setText("opkop")
        self.setPopupPosition(left, top)
        self.setStyleAttribute("background-color", "#ffffff")
        self.setStyleAttribute("color", "blue")
        self.setStyleAttribute("border-width", "5px")
        self.setStyleAttribute("border-style", "solid")

        self.setWidget(dock)

    def onClick(self, sender):
        if sender==self.doneButton:
            self.hide()
            self.after(self.formula)

        op=None
        for owb in self.ops_with_buttons:
            if owb['button'] == sender:
                self.setText(sender.getText())
                op=owb['op']

        if not self.formula.is_closed():
            self.formula.add_one_op(op,type)
            self.image.setUrl(latex_to_url(self.formula.fill_with_placeholders().to_latex()))
            if self.formula.is_closed():
                self.doneButton.setEnabled(True)
Ejemplo n.º 5
0
class SaveDialog(DialogWindow):
    def __init__(self, theorem, **kwargs):
        DialogWindow.__init__(self, modal=True, close=True)
        self.theorem = theorem
        v = VerticalPanel()
        v.setWidth(300)
        # v.setHeight(500)
        self.setText("save")
        self.setPopupPosition(100, 100)
        self.setStyleAttribute("background-color", "#ffffff")
        self.setStyleAttribute("color", "red")
        self.setStyleAttribute("border-width", "5px")
        self.setStyleAttribute("border-style", "solid")
        self.im = Image()
        self.im.setUrl(latex_to_url(self.theorem.formula.to_latex()))
        v.add(self.im)
        h = HorizontalPanel()
        self.radio = RadioButton("group1", "Existing folder:")
        h.add(self.radio)
        self.list = ListBox()
        self.list.setVisibleItemCount(1)
        for f in Theorem.get_all_folders():
            self.list.addItem(f)

        h.add(self.list)
        v.add(h)
        h = HorizontalPanel()
        h.add(RadioButton("group1", "New folder:"))
        self.radio.setChecked(True)
        self.textbox = TextBox()
        h.add(self.textbox)
        v.add(h)
        v.add(Button("Done", self.done_click))
        self.add(v)

    def get_folder_name(self):
        if self.radio.getChecked():
            return self.list.getItemText(self.list.getSelectedIndex())
        else:
            return self.textbox.getText()

    def done_click(self):
        self.theorem.folder = self.get_folder_name()
        Theorem.theorems.append(self.theorem)
        IO.save()
        self.hide()
Ejemplo n.º 6
0
class SaveDialog(DialogWindow):
    def __init__(self, theorem, **kwargs):
        DialogWindow.__init__(self, modal=True, close=True)
        self.theorem=theorem
        v = VerticalPanel()
        v.setWidth(300)
        # v.setHeight(500)
        self.setText("save")
        self.setPopupPosition(100, 100)
        self.setStyleAttribute("background-color", "#ffffff")
        self.setStyleAttribute("color", "red")
        self.setStyleAttribute("border-width", "5px")
        self.setStyleAttribute("border-style", "solid")
        self.im=Image()
        self.im.setUrl(latex_to_url(self.theorem.formula.to_latex()))
        v.add(self.im)
        h=HorizontalPanel()
        self.radio=RadioButton("group1", "Existing folder:")
        h.add(self.radio)
        self.list = ListBox()
        self.list.setVisibleItemCount(1)
        for f in Theorem.get_all_folders():
            self.list.addItem(f)

        h.add(self.list)
        v.add(h)
        h=HorizontalPanel()
        h.add(RadioButton("group1", "New folder:"))
        self.radio.setChecked(True)
        self.textbox=TextBox()
        h.add(self.textbox)
        v.add(h)
        v.add(Button("Done",self.done_click))
        self.add(v)

    def get_folder_name(self):
        if self.radio.getChecked():
            return self.list.getItemText(self.list.getSelectedIndex())
        else:
            return self.textbox.getText()

    def done_click(self):
        self.theorem.folder=self.get_folder_name()
        Theorem.theorems.append(self.theorem)
        IO.save()
        self.hide()
Ejemplo n.º 7
0
    def refresh_theorems(self, folder):
        self.remove_images()

        def onClick(theorem):
            def name(n):
                return "var" + str(n + 1)

            def print_scheme(n):
                return [
                    "\\alpha", "\\beta", "\\gamma", "\\delta", "\\epsilon"
                ][n]

            def poas(sender):
                if len(theorem.operations) == 1:
                    constants = [
                        Operation("const" + str(i + 1), 0, print_scheme(i),
                                  name(i), Operation.EXPRESSION)
                        for i in range(theorem.operations[0].no_of_args)
                    ]

                    def after1(f):
                        self.after(theorem.formula.substitute_definition(
                            Formula([theorem.operations[0]] + constants), f),
                                   predecessors=[],
                                   rule_name="insert")

                    request_formula([op for op in proof.get_operations()] +
                                    constants,
                                    after1,
                                    type=('rel' if theorem.operations[0].type
                                          == Operation.RELATION else 'exp'))
                else:
                    self.after(theorem.formula,
                               predecessors=[],
                               rule_name="insert")

            return poas

        for ax in [x for x in Theorem.theorems if x.folder == folder]:
            im = Image()
            im.addClickListener(onClick(ax))
            im.setUrl(latex_to_url(ax.formula.to_latex()))
            self.pok.add(im)
            self.images.append(im)
Ejemplo n.º 8
0
class Images(Sink):
    def __init__(self):
        Sink.__init__(self)
        self.curImage=0
        self.image=Image()
        self.loadingImage = Image(self.baseURL() + "images/blanksearching.gif")
        self.nextButton = Image(self.baseURL() + "rembrandt/forward.gif")
        self.prevButton = Image(self.baseURL() + "rembrandt/back.gif")
        self.sImages=["rembrandt/JohannesElison.jpg", "rembrandt/LaMarcheNocturne.jpg", "rembrandt/SelfPortrait1628.jpg", "rembrandt/SelfPortrait1640.jpg", "rembrandt/TheArtistInHisStudio.jpg", "rembrandt/TheReturnOfTheProdigalSon.jpg"]

        for i in range(len(self.sImages)):
            self.sImages[i]=self.baseURL() + self.sImages[i]
        
        self.image.addLoadListener(self)
        self.prevButton.addClickListener(self)
        self.nextButton.addClickListener(self)
        
        topPanel = DockPanel()
        topPanel.setVerticalAlignment(HasAlignment.ALIGN_MIDDLE)
        topPanel.add(self.prevButton, DockPanel.WEST)
        topPanel.add(self.nextButton, DockPanel.EAST)
        topPanel.add(self.loadingImage, DockPanel.CENTER)
        
        panel = VerticalPanel()
        panel.setHorizontalAlignment(HasAlignment.ALIGN_CENTER)
        panel.add(HTML("<h2>A Bit of Rembrandt</h2>", True))
        panel.add(topPanel)
        panel.add(self.image)
        
        panel.setWidth("100%")
        self.initWidget(panel)
        self.image.setStyleName("ks-images-Image")
        self.nextButton.setStyleName("ks-images-Button")
        self.prevButton.setStyleName("ks-images-Button")
        
        self.loadImage(0)           

    def onClick(self, sender):
        if sender==self.prevButton:
            self.loadImage(self.curImage - 1)
        elif sender == self.nextButton:
            self.loadImage(self.curImage + 1)

    def onError(self, sender):
        pass

    def onLoad(self, sender=None):
        self.loadingImage.setUrl(self.baseURL() + "images/blanksearching.gif")

    def loadImage(self, index):
        if index < 0:
            index = len(self.sImages) - 1
        elif index > len(self.sImages) - 1:
            index = 0

        self.curImage = index
        self.loadingImage.setUrl(self.baseURL() + "images/searching.gif")
        self.image.setUrl(self.sImages[self.curImage])
Ejemplo n.º 9
0
class ControlButton(Composite):
    def __init__(self, up_url, down_url, up_msg, down_msg):
        Composite.__init__(self)
        self.state = "up"
        self.up_url = up_url
        self.down_url = down_url
        self.up_msg = up_msg
        self.down_msg = down_msg
        self.control = VerticalPanel()
        self.image = Image(up_url)
        self.image.setStyleName("gwt-Image-Cell")
        self.text = HTML(up_msg)
        self.image.base = self
        self.text.base = self
        self.text.horzAlign = "center"
        self.control.add(self.image)
        self.control.add(self.text)
        self.initWidget(self.control)

    def toggleImage(self):
        if self.state == "up":
            new_url = self.down_url
            new_msg = self.down_msg
            self.state = "down"
        elif self.state == "down":
            new_url = self.up_url
            new_msg = self.up_msg
            self.state = "up"

        self.image.setUrl(new_url)
        self.text.setHTML(new_msg)

    def toggleTimer(self):
        self.base.base.display_panel.timer.toggle()

    def addMouseListener(self, listner):
        self.image.addMouseListener(listner)
Ejemplo n.º 10
0
class FormulaBuilder(DialogWindow):
    def __init__(self, operations, after, **kwargs):
        DialogWindow.__init__(self, modal=True, close=True)
        self.formula = Formula([])
        self.after = after
        if "type" in kwargs:
            self.type = kwargs["type"]
        else:
            self.type = 'rel'

        self.set_styles()

        def op_button_click(op):
            def aio():
                self.add_op(op)

            return aio

        self.ops_with_buttons = [{
            "op": op,
            "button": Button(op.name, op_button_click(op))
        } for op in operations]

        for owb in self.ops_with_buttons:
            self.add_button(owb["button"])

        self.var = list()
        self.is_clicked = list()
        self.textbox = list()

        self.set_variables((0 if self.type == 'exp' else 5))

    def set_variables(self, no_of_vars, x=True):
        def name(n):
            return "var" + str(n)

        def print_scheme(n):
            return ["\\alpha", "\\beta", "\\gamma", "\\delta", "\\epsilon"][n]

        def button_click(n):
            def sopa():
                if not self.is_clicked[n]:
                    v = Operation(name(n), 0, self.textbox[n].getText(),
                                  name(n), Operation.VARIABLE)
                    self.var[n] = v
                    self.textbox[n].setEnabled(False)
                    self.is_clicked[n] = True
                self.add_op(self.var[n])

            return sopa

        for i in range(no_of_vars):
            h = HorizontalPanel()
            b = Button("variable", button_click(i))
            h.add(b)
            self.is_clicked.append(False)
            self.var.append(None)
            t = TextBox()
            self.textbox.append(t)
            t.setText(print_scheme(i))
            h.add(t)
            self.add_button(h)

    def set_styles(self):
        self.dock = DockPanel()
        self.dock.setSpacing(3)

        self.dock.setWidth("300")

        self.image = Image(
            latex_to_url(self.formula.fill_with_placeholders().to_latex()))
        self.dock.add(self.image, DockPanel.EAST)
        self.dock.setCellHorizontalAlignment(self.image,
                                             HasAlignment.ALIGN_TOP)

        self.backspaceButton_add()
        self.doneButton_add()

        self.dock.add(HTML(""), DockPanel.CENTER)
        left = 100
        top = 100

        self.setText("opkop")
        self.setPopupPosition(left, top)
        self.setStyleAttribute("background-color", "#ffffff")
        self.setStyleAttribute("color", "blue")
        self.setStyleAttribute("border-width", "5px")
        self.setStyleAttribute("border-style", "solid")

        self.setWidget(self.dock)

    def doneButton_add(self):
        def doneButton_click():
            self.hide()
            self.after(self.formula)

        self.doneButton = Button("Done", doneButton_click)
        self.doneButton.setEnabled(False)
        self.dock.add(self.doneButton, DockPanel.SOUTH)

    def backspaceButton_add(self):
        def backspaceButton_click():
            self.formula = Formula(self.formula.body[:-1])
            self.refresh()

        self.backspaceButton = Button("Backspace", backspaceButton_click)
        self.backspaceButton.setEnabled(False)
        self.dock.add(self.backspaceButton, DockPanel.SOUTH)

    def refresh(self):
        self.image.setUrl(
            latex_to_url(self.formula.fill_with_placeholders().to_latex()))
        self.doneButton.setEnabled(self.formula.is_closed())
        self.backspaceButton.setEnabled(len(self.formula.body) >= 0)

    def add_button(self, b):
        self.dock.add(b, DockPanel.NORTH)

    def add_op(self, op):
        if not self.formula.is_closed():
            self.formula.add_one_op(op, self.type)
            self.refresh()
Ejemplo n.º 11
0
class CollapserPanel(SimplePanel):
    def __init__(self, sink):
        SimplePanel.__init__(self)
        self.sink = sink
        self.caption = HTML()
        self.child = None
        self.showing = False
        self.dragging = False
        self.dragStartX = 0
        self.dragStartY = 0
        self.panel = FlexTable()

        self.collapse = Image("./images/cancel.png")
        self.collapse.addClickListener(self)
        dock = DockPanel()
        dock.setSpacing(0)

        dock.add(self.collapse, DockPanel.EAST)
        dock.add(self.caption, DockPanel.WEST)

        dock.setCellHorizontalAlignment(self.collapse,
                                        HasAlignment.ALIGN_RIGHT)
        dock.setCellVerticalAlignment(self.collapse, HasAlignment.ALIGN_TOP)
        dock.setCellHorizontalAlignment(self.caption, HasAlignment.ALIGN_LEFT)
        dock.setCellWidth(self.caption, "100%")
        dock.setWidth("100%")
        dock.setHeight("100%")

        self.panel.setWidget(0, 0, dock)
        self.panel.setHeight("100%")
        self.panel.setWidth("100%")
        self.panel.setBorderWidth(0)
        self.panel.setCellPadding(0)
        self.panel.setCellSpacing(0)
        self.panel.getCellFormatter().setHeight(1, 0, "100%")
        self.panel.getCellFormatter().setWidth(1, 0, "100%")
        self.panel.getCellFormatter().setAlignment(
            1, 0, HasHorizontalAlignment.ALIGN_LEFT,
            HasVerticalAlignment.ALIGN_TOP)
        SimplePanel.setWidget(self, self.panel)

        self.setStyleName("gwt-DialogBox")
        self.caption.setStyleName("Caption")
        self.collapse.setStyleName("Close")
        dock.setStyleName("Header")
        #self.caption.addMouseListener(self)
        self.collapsed = False

        self.collapsed_width = "15px"
        self.uncollapsed_width = "100%"

    def setInitialWidth(self, width):
        self.uncollapsed_width = width
        SimplePanel.setWidth(self, width)
        self.sink.setCollapserWidth(self, width)

    def setHeight(self, height):
        SimplePanel.setHeight(self, height)

    def onClick(self, sender):
        if self.collapsed == False:
            self.collapse.setUrl("./tree_closed.gif")
            self.collapsed = True
            self.caption.setVisible(False)
            if self.child:
                self.child.setVisible(False)
            self.setWidth(self.collapsed_width)
            self.sink.setCollapserWidth(self, self.collapsed_width)
        else:
            self.collapse.setUrl("./images/cancel.png")
            self.collapsed = False
            self.caption.setVisible(True)
            if self.child:
                self.child.setVisible(True)
            self.setWidth(self.uncollapsed_width)
            self.sink.setCollapserWidth(self, self.uncollapsed_width)

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

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

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

        self.panel.remove(widget)
        return True

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

    def doDetachChildren(self):
        SimplePanel.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
Ejemplo n.º 12
0
class kMeans(Algorithm):
    def __init__(self):
        Algorithm.__init__(self)
        self.MLAlgorithmService = MLAlgorithmService(self)
        self.image = Image(self.baseURL() +
                           "services/kMeansPictures/lenna.png",
                           Width="320px",
                           Height="360px")
        self.resultImage = Image("", Width="320px", Height="360px")
        self.loadingImage = Image(self.baseURL() + "images/blanksearching.gif")
        self.calculateButton = Button("RUN", self.onButtonClick)
        self.log = Button("SHOW LOG", self.openLogFile)
        self.log.setEnabled(False)

        self.image.addLoadListener(self)

        topPanel = DockPanel()
        topPanel.setVerticalAlignment(HasAlignment.ALIGN_MIDDLE)
        topPanel.add(self.calculateButton, DockPanel.WEST)
        topPanel.add(self.loadingImage, DockPanel.CENTER)
        topPanel.add(self.log, DockPanel.EAST)

        panel = DockPanel()
        panel.setHorizontalAlignment(HasAlignment.ALIGN_CENTER)
        panel.setVerticalAlignment(HasAlignment.ALIGN_MIDDLE)
        #panel.add(HTML("<h2>Image compression</h2>", True))
        panel.add(topPanel, DockPanel.NORTH)
        panel.add(self.image, DockPanel.WEST)
        panel.add(self.resultImage, DockPanel.EAST)

        panel.setWidth("100%")
        self.initWidget(panel)
        self.image.setStyleName("ks-images-Image")
        self.calculateButton.setStyleName("ks-images-Button")

        self.loadImage("picturem.png")

    def onButtonClick(self, sender):
        Window.alert("Starting image compression...")
        self.MLAlgorithmService.callMethod("lenna.png")

    def onError(self, sender):
        pass

    def onLoad(self, sender=None):
        self.loadingImage.setUrl(self.baseURL() + "images/blanksearching.gif")

    def loadImage(self, picture):
        self.loadingImage.setUrl(self.baseURL() + "images/searching.gif")
        self.image.setUrl(self.baseURL() + "services/kMeansPictures/lenna.png")
        self.resultImage.setUrl(self.baseURL() +
                                "services/kMeansPictures/lenna.png")
        self.resultImage.setUrl(self.baseURL() + "services/kMeansPictures/" +
                                picture)

    def onImageClicked(self):
        Window.alert("picture!")

    def openLogFile(self, sender):
        ###TODO: make logging output
        fileLocation = self.baseURL() + "services/contactjson.txt"
        dlg = FileOpenDlg(fileLocation=fileLocation)
        dlg.show()

    def showStatus(self, msg):
        Window.alert(msg)
Ejemplo n.º 13
0
class kMeans(Algorithm):
    def __init__(self):
        Algorithm.__init__(self)
	self.MLAlgorithmService = MLAlgorithmService(self)
        self.image=Image(self.baseURL() + "services/kMeansPictures/lenna.png",Width="320px", Height="360px")
        self.resultImage=Image("",Width="320px", Height="360px")
        self.loadingImage = Image(self.baseURL() + "images/blanksearching.gif")
        self.calculateButton = Button("RUN", self.onButtonClick)
        self.log = Button("SHOW LOG", self.openLogFile)
        self.log.setEnabled(False)

        self.image.addLoadListener(self)
        
        topPanel = DockPanel()
        topPanel.setVerticalAlignment(HasAlignment.ALIGN_MIDDLE)
        topPanel.add(self.calculateButton, DockPanel.WEST)
        topPanel.add(self.loadingImage, DockPanel.CENTER)
        topPanel.add(self.log, DockPanel.EAST)
        
        panel = DockPanel()
        panel.setHorizontalAlignment(HasAlignment.ALIGN_CENTER)
        panel.setVerticalAlignment(HasAlignment.ALIGN_MIDDLE)
        #panel.add(HTML("<h2>Image compression</h2>", True))
        panel.add(topPanel, DockPanel.NORTH)
        panel.add(self.image, DockPanel.WEST)
        panel.add(self.resultImage, DockPanel.EAST)
        
        panel.setWidth("100%")
        self.initWidget(panel)
        self.image.setStyleName("ks-images-Image")
        self.calculateButton.setStyleName("ks-images-Button")
        
        self.loadImage("picturem.png")

    def onButtonClick(self, sender):
        Window.alert("Starting image compression...")
        self.MLAlgorithmService.callMethod("lenna.png")


    def onError(self, sender):
        pass

    def onLoad(self, sender=None):
        self.loadingImage.setUrl(self.baseURL() + "images/blanksearching.gif")

    def loadImage(self, picture):
        self.loadingImage.setUrl(self.baseURL() + "images/searching.gif")
        self.image.setUrl(self.baseURL() + "services/kMeansPictures/lenna.png")
        self.resultImage.setUrl(self.baseURL() + "services/kMeansPictures/lenna.png")
        self.resultImage.setUrl(self.baseURL() + "services/kMeansPictures/" + picture)

    def onImageClicked(self):
        Window.alert("picture!")

    def openLogFile(self, sender):
###TODO: make logging output
        fileLocation = self.baseURL() + "services/contactjson.txt"
        dlg = FileOpenDlg(fileLocation=fileLocation)
        dlg.show()

    def showStatus(self, msg):
        Window.alert(msg)
Ejemplo n.º 14
0
class Trees(Sink):
    def __init__(self):

        Sink.__init__(self)

        self.formula = AX_REG
        self.image1 = Image(latex_to_url(self.formula.fill_with_placeholders().to_latex()))
        self.cnf=self.formula.simplify().to_cnf()
        self.image2 = Image(latex_to_url(self.cnf.to_latex()))
        self.vars=self.cnf.get_vars()

        self.vars_with_proto = [{"var": var, "proto": Proto(var.name)} for var in self.vars]
        self.fProto = [
            Proto("Beethoven", [x["proto"] for x in self.vars_with_proto])
        ]

        self.fTree = Tree()

        for i in range(len(self.fProto)):
            self.createItem(self.fProto[i])
            self.fTree.addItem(self.fProto[i].item)

        self.fTree.addTreeListener(self)

        self.panel = HorizontalPanel(VerticalAlignment=HasAlignment.ALIGN_TOP)
        self.panel.setSpacing(40)
        self.panel.add(self.fTree)

        self.panel.add(self.image1)
        self.panel.add(self.image2)

        self.initWidget(self.panel)

    def onTreeItemSelected(self, item):
        var=None
        for vwb in self.vars_with_proto:
            if vwb['proto'] == item.userObject:
                var=vwb['var']

        def after(formula):
            self.cnf=self.cnf.substitute(Formula([var]),formula)
            self.image2.setUrl(latex_to_url(self.cnf.to_latex()))

        dlg = FormulaBuilder([op for op in operations if op.available and op.type==Operation.EXPRESSION],after,type='expr')

        dlg.show()

    def onTreeItemStateChanged(self, item):
        child = item.getChild(0)
        if hasattr(child, "isPendingItem"):
            item.removeItem(child)

            proto = item.getUserObject()
            for i in range(len(proto.children)):
                self.createItem(proto.children[i])
                index = self.getSortIndex(item, proto.children[i].text)
                # demonstrate insertItem.  addItem is easy.
                item.insertItem(proto.children[i].item, index)

    def getSortIndex(self, parent, text):
        nodes = parent.getChildCount()
        node = 0
        text = text.lower()

        while node < nodes:
            item = parent.getChild(node)
            if cmp(text, item.getText().lower()) < 0:
                break;
            else:
                node += 1

        return node

    def createItem(self, proto):
        proto.item = TreeItem(proto.text)
        proto.item.setUserObject(proto)
        if len(proto.children) > 0:
            proto.item.addItem(PendingItem())
class DisplayHistogramsView(object) :
	"""
	@brief View in the MVP pattern for displaying histograms.

	@author Mark Grimes ([email protected])
	@date 09/Feb/2014
	"""
	def __init__( self ) :
		self.cbcList=ListBox(MultipleSelect=True, VisibleItemCount=4)
		self.channelList=ListBox(MultipleSelect=True, VisibleItemCount=20)
		self.updateButton=Button("Update")

		controls=VerticalPanel()
		controls.add(self.updateButton)
		controls.add(self.cbcList)
		controls.add(self.channelList)

		controls.setCellHorizontalAlignment( self.updateButton, HasHorizontalAlignment.ALIGN_CENTER )
		self.cbcList.setWidth("95%")
		self.channelList.setWidth("95%")

		self.cbcList.addItem( "waiting..." )
		for index in range(0,254) :
			self.channelList.addItem( "Channel %3d"%index )

		self.histogram = Image()
		self.mainPanel = HorizontalPanel()
		self.mainPanel.add( controls )
		self.mainPanel.add( self.histogram )
		self.histogram.setUrl( "defaultScurveHistogram.png" )

	def getPanel( self ) :
		return self.mainPanel

	def setAvailableCBCs( self, cbcNames ) :
		self.cbcList.clear()
		for name in cbcNames :
			self.cbcList.addItem( name )

	def enable( self ) :
		self.updateButton.setEnabled(True)
		self.cbcList.setEnabled(True)
		self.channelList.setEnabled(True)

	def disable( self ) :
		self.updateButton.setEnabled(False)
		self.cbcList.setEnabled(False)
		self.channelList.setEnabled(False)
	
	def getUpdateButton( self ) :
		return self.updateButton
	
	def getSelectedCBCChannels( self ) :
		"""
		Returns a dictionary of which channels are selected, with CBC name as a key and
		an array of the channels for that CBC as the value.
		"""
		# The way this view is currently set up, the selected channels have to be the same
		# for each selected CBC.
		selectedChannels=[]
		for index in range(self.channelList.getItemCount()) :
			if self.channelList.isItemSelected(index) :
				selectedChannels.append(index)
		returnValue={}
		for index in range(self.cbcList.getItemCount()) :
			if self.cbcList.isItemSelected(index) : returnValue[self.cbcList.getItemText(index)]=selectedChannels

		return returnValue

	def setImage( self, url ) :
		self.histogram.setUrl( url )
Ejemplo n.º 16
0
class CollapserPanel(SimplePanel):
    def __init__(self, sink):
        SimplePanel.__init__(self)
        self.sink = sink
        self.caption = HTML()
        self.child = None 
        self.showing = False
        self.dragging = False
        self.dragStartX = 0
        self.dragStartY = 0
        self.panel = FlexTable()

        self.collapse = Image("./images/cancel.png")
        self.collapse.addClickListener(self)
        dock = DockPanel()
        dock.setSpacing(0)
        
        dock.add(self.collapse, DockPanel.EAST)
        dock.add(self.caption, DockPanel.WEST)

        dock.setCellHorizontalAlignment(self.collapse, HasAlignment.ALIGN_RIGHT)
        dock.setCellVerticalAlignment(self.collapse, HasAlignment.ALIGN_TOP)
        dock.setCellHorizontalAlignment(self.caption, HasAlignment.ALIGN_LEFT)
        dock.setCellWidth(self.caption, "100%")
        dock.setWidth("100%")
        dock.setHeight("100%")

        self.panel.setWidget(0, 0, dock)
        self.panel.setHeight("100%")
        self.panel.setWidth("100%")
        self.panel.setBorderWidth(0)
        self.panel.setCellPadding(0)
        self.panel.setCellSpacing(0)
        self.panel.getCellFormatter().setHeight(1, 0, "100%")
        self.panel.getCellFormatter().setWidth(1, 0, "100%")
        self.panel.getCellFormatter().setAlignment(1, 0, HasHorizontalAlignment.ALIGN_LEFT, HasVerticalAlignment.ALIGN_TOP)
        SimplePanel.setWidget(self, self.panel)

        self.setStyleName("gwt-DialogBox")
        self.caption.setStyleName("Caption")
        self.collapse.setStyleName("Close")
        dock.setStyleName("Header")
        #self.caption.addMouseListener(self)
        self.collapsed = False

        self.collapsed_width = "15px"
        self.uncollapsed_width = "100%"

    def setInitialWidth(self, width):
        self.uncollapsed_width = width
        SimplePanel.setWidth(self, width)
        self.sink.setCollapserWidth(self, width)

    def setHeight(self, height):
        SimplePanel.setHeight(self, height)

    def onClick(self, sender):
        if self.collapsed == False:
            self.collapse.setUrl("./tree_closed.gif")
            self.collapsed = True
            self.caption.setVisible(False)
            if self.child:
                self.child.setVisible(False)
            self.setWidth(self.collapsed_width)
            self.sink.setCollapserWidth(self, self.collapsed_width)
        else:
            self.collapse.setUrl("./images/cancel.png")
            self.collapsed = False
            self.caption.setVisible(True)
            if self.child:
                self.child.setVisible(True)
            self.setWidth(self.uncollapsed_width)
            self.sink.setCollapserWidth(self, self.uncollapsed_width)

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

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

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

        self.panel.remove(widget)
        return True

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

    def doDetachChildren(self):
        SimplePanel.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
Ejemplo n.º 17
0
class LargeAvatar(VerticalPanel):
    def __init__(self, userListPanel, tabPanel, topPanel):
        VerticalPanel.__init__(self, StyleName='large-avatar-panel')
        self.userListPanel = userListPanel
        self.tabPanel = tabPanel
        self.topPanel = topPanel
        upperPanel = HorizontalPanel(StyleName='large-avatar-upper-panel',
                                     Spacing=8)
        self.image = Image(StyleName='large-avatar')
        self.upperText = HTML(StyleName='large-avatar-upper-text')
        upperPanel.add(self.image)
        upperPanel.add(self.upperText)
        self.add(upperPanel)
        self.lowerText = HTML(StyleName='large-avatar-lower-text')
        self.add(self.lowerText)
        self.followButton = None
        self.user = None
        insertPanel = HorizontalPanel(Spacing=3)
        insertPanel.add(Label('Use name: '))
        if tabPanel.tabName == 'simple':
            b1 = Button('upper', SimpleInserter(self, 'upper'))
            b2 = Button('lower', SimpleInserter(self, 'lower'))
            insertPanel.add(b1)
            insertPanel.add(b2)
        else:
            b1 = Button('or', QueryInserter(self, 'or'))
            b2 = Button('and', QueryInserter(self, 'and'))
            b3 = Button('except', QueryInserter(self, 'except'))
            insertPanel.add(b1)
            insertPanel.add(b2)
            insertPanel.add(b3)
        self.add(insertPanel)

    def setUser(self, u):
        self.user = u
        screenname = u['screen_name']
        self.image.setUrl(u['profile_image_url'])
        self.upperText.setHTML(
            '''%s<br/>%s''' %
            (u['name'],
             utils.screennameToTwitterLink(screenname, '@' + screenname)))
        
        friends = utils.splitthousands(u['friends_count'])
        followers = utils.splitthousands(u['followers_count'])
        tweets = utils.splitthousands(u['statuses_count'])
        location = u['location'] or 'unknown'
        self.lowerText.setHTML(
            '''Friends:&nbsp;%s<br/>
               Followers:&nbsp;%s<br/>
               Tweets:&nbsp;%s<br/>
               Location:&nbsp;%s<br/>
               Twitter id:&nbsp;%s<br/>
               Private:&nbsp;%s''' %
            (utils.screennameToTwitterFriendsLink(screenname, friends),
             utils.screennameToTwitterFollowersLink(screenname, followers),
             utils.screennameToTwitterLink(screenname, tweets),
             location, utils.splitthousands(u['id']), u['protected']))

        if self.followButton:
            self.remove(self.followButton)
            self.followButton = None
            
        following = u.get('following')
        if following is not None:
            if self.topPanel.loginPanel.screenname == screenname:
                # OK, I admit, this is ugly.
                self.followButton = Label("That's you!",
                                          StyleName='follow-button')
            else:
                if following:
                    text = _unfollowText
                else:
                    text = _followText
                self.followButton = Button(text, self,
                                           StyleName='follow-button')
            self.add(self.followButton)

    def onClick(self, sender):
        self.followButton.setEnabled(False)
        cookie = self.topPanel.loginPanel.oauthCookie
        remote = server.TickeryService()
        if self.user['following']:
            func = remote.unfollow
        else:
            func = remote.follow
        id = func(cookie, self.user['id'],
                  UpdateFollow(self, self.userListPanel, self.topPanel))
        if id < 0:
            self.add(Label('oops: could not call follow/unfollow'))
Ejemplo n.º 18
0
class Images(Sink):
    def __init__(self):
        Sink.__init__(self)
        self.curImage = 0
        self.image = Image()
        self.loadingImage = Image(self.baseURL() + "images/blanksearching.gif")
        self.nextButton = Image(self.baseURL() + "rembrandt/forward.gif")
        self.prevButton = Image(self.baseURL() + "rembrandt/back.gif")
        self.sImages = [
            "rembrandt/JohannesElison.jpg", "rembrandt/LaMarcheNocturne.jpg",
            "rembrandt/SelfPortrait1628.jpg", "rembrandt/SelfPortrait1640.jpg",
            "rembrandt/TheArtistInHisStudio.jpg",
            "rembrandt/TheReturnOfTheProdigalSon.jpg"
        ]

        for i in range(len(self.sImages)):
            self.sImages[i] = self.baseURL() + self.sImages[i]

        self.image.addLoadListener(self)
        self.prevButton.addClickListener(self)
        self.nextButton.addClickListener(self)

        topPanel = DockPanel()
        topPanel.setVerticalAlignment(HasAlignment.ALIGN_MIDDLE)
        topPanel.add(self.prevButton, DockPanel.WEST)
        topPanel.add(self.nextButton, DockPanel.EAST)
        topPanel.add(self.loadingImage, DockPanel.CENTER)

        panel = VerticalPanel()
        panel.setHorizontalAlignment(HasAlignment.ALIGN_CENTER)
        panel.add(HTML("<h2>A Bit of Rembrandt</h2>", True))
        panel.add(topPanel)
        panel.add(self.image)

        panel.setWidth("100%")
        self.initWidget(panel)
        self.image.setStyleName("ks-images-Image")
        self.nextButton.setStyleName("ks-images-Button")
        self.prevButton.setStyleName("ks-images-Button")

        self.loadImage(0)

    def onClick(self, sender):
        if sender == self.prevButton:
            self.loadImage(self.curImage - 1)
        elif sender == self.nextButton:
            self.loadImage(self.curImage + 1)

    def onError(self, sender):
        pass

    def onLoad(self, sender=None):
        self.loadingImage.setUrl(self.baseURL() + "images/blanksearching.gif")

    def loadImage(self, index):
        if index < 0:
            index = len(self.sImages) - 1
        elif index > len(self.sImages) - 1:
            index = 0

        self.curImage = index
        self.loadingImage.setUrl(self.baseURL() + "images/searching.gif")
        self.image.setUrl(self.sImages[self.curImage])
Ejemplo n.º 19
0
class PageBookComments:
    def onModuleLoad(self):
        # parse get data
        self.location = Window.getLocation().getHref()
        self.get_data = {}
        self.tmp = self.location.split('?')
        self.tmp = self.tmp[len(self.tmp) - 1].split("&")
        for e in self.tmp:
            get_var = e.split("=")
            if len(get_var) == 2:
                self.get_data[get_var[0]] = get_var[1]

        # JSON RPC response holders
        self.facebook_user = {}
        self.app_info = {}
        self.sellers = []
        self.book = {}
        self.has_book = "none"
        
        # setup JSON RPC
        self.remote = DataService()

        self.remote.get_facebook_user(self)
        self.remote.get_app_info(self, "book_detail")
        if "asin" in self.get_data:
            self.remote.get_book_details(self, self.get_data["asin"])
            self.remote.get_sellers(self, self.get_data["asin"])
            self.remote.user_has_book(self, self.get_data["asin"])

        # create panels
        self.main_panel = HorizontalPanel()
        self.info_panel = VerticalPanel()
        self.sell_btn_panel = VerticalPanel()
        self.wish_btn_panel = VerticalPanel()
        self.seller_panel = VerticalPanel()
        self.add_comment_panel = VerticalPanel()

        # images
        self.img_book_cover = Image()

        # html labels
        self.html_book_title = HTML()
        self.html_book_author = HTML()
        self.html_book_isbn10 = HTML()
        self.html_book_publisher = HTML()
        self.html_book_publish_date = HTML()
        self.html_book_edition = HTML()
        self.html_book_binding = HTML()

        self.html_btn_sell = HTML()
        self.html_btn_wish = HTML()
        
        self.html_seller_title = HTML()

        # check for no get data!
        if "asin" not in self.get_data:
            self.html_book_title.setHTML("<h1>Book not found!</h1>\n<p>The book you are looking for does not exist.</p>")
            self.info_panel.setWidth("100%")
            self.main_panel.setWidth("100%")
            self.info_panel.add(self.html_book_title)
            self.main_panel.add(self.info_panel)
            RootPanel("page_book_comments").add(self.main_panel)
            return

        # add to sellers panel
        self.seller_panel.add(self.html_seller_title)
        self.seller_panel.addStyleName("comments")

        self.info_panel.add(self.html_book_title)
        self.info_panel.add(self.html_book_author)
        self.info_panel.add(self.html_book_isbn10)
        self.info_panel.add(self.html_book_publisher)
        self.info_panel.add(self.html_book_publish_date)
        self.info_panel.add(self.html_book_edition)
        self.info_panel.add(self.html_book_binding)
        self.info_panel.add(self.add_comment_panel)
        self.info_panel.add(self.seller_panel)
        self.info_panel.addStyleName("info_panel")
        
        self.main_panel.add(self.info_panel)
        self.main_panel.add(self.img_book_cover)
        
        RootPanel("page_book_comments").add(self.main_panel)
        
        # spin until book info get here
        class SpinTimer(Timer):
            def __init__(self, max_tries = 10, interval = 500):
                Timer.__init__(self)
                self.interval = interval
                self.max_tries = max_tries
                self.tries = 0
                self.func = func
                self.params = params
                self.scheduleRepeating(self.interval)

            def run(self):
                self.tries += 1

                if self.tries >= self.max_tries:
                    Window.alert("It looks like there's a connection problem. We're sorry about the inconvenience. Please try again later.")
                    self.cancel()
                    return

                if populate_book_details():
                    self.cancel()
        
        populate_book_details = self.populate_book_details
        st = SpinTimer()

    def populate_book_details(self):
        """ fill in book information on this page
        """
        if len(self.facebook_user) == 0: return False
        if len(self.app_info) == 0: return False
        if len(self.book) == 0: return False
        if self.book['num_sellers'] != 0 and len(self.sellers) == 0: return False

        if 'title' not in self.book or 'binding' not in self.book: return False
        binding = "Hardcover"
        if self.book['binding'] != "Hardcover" and not self.book['binding']: binding = "Paperback"
        self.html_book_title.setHTML("<span class=\"title\">%s [%s]</span>" % (self.book['title'], binding))

        if 'author' not in self.book: return False
        self.html_book_author.setHTML("<span class=\"author\">%s</span>" % self.book['author'])

        if 'isbn10' not in self.book: return False
        self.html_book_isbn10.setHTML("<span class=\"isbn\">ISBN 10: %s</span>" % self.book['isbn10'])

        # add these in
        #self.html_book_publisher.setHTML("<span class=\"info\">Publisher: %s</span>" % self.book['publisher'])
        #self.html_book_publish_date.setHTML("<span class=\"info\">Published: %s</span>" % self.book['publish_date'])

        if 'edition' not in self.book: return False
        self.html_book_edition.setHTML("<span class=\"info\">Edition: %s</span>" % self.book['edition'])

        if 'thumbnail' not in self.book: return False
        if self.book['thumbnail'] == "N/A":
            self.book['thumbnail'] = self.app_info['url'] + "static/images/default_thumbnail.png"
        self.img_book_cover.setUrl(self.book['thumbnail'])

        if 'num_sellers' not in self.book: return False
        amount = "amount_low"
        if int(self.book['num_sellers']) > 3: amount = "amount_medium"
        elif int(self.book['num_sellers']) > 7: amount = "amount_high"
        self.html_btn_sell.setHTML("<span class=\"num_sellers\">Sellers: <span class=\"%s\">%d</span></span>" % (amount, self.book['num_sellers']))

        if 'num_watchers' not in self.book: return False
        amount = "amount_low"
        if int(self.book['num_watchers']) > 3: amount = "amount_medium"
        elif int(self.book['num_watchers']) > 7: amount = "amount_high"
        self.html_btn_wish.setHTML("<span class=\"num_watchers\">Watchers: <span class=\"%s\">%d</span></span>" % (amount, self.book['num_watchers']))

        self.html_seller_title.setHTML("<h1>%s's Seller Activity for %s</h1>" % (self.facebook_user['first_name'], self.book['title']))

        comments_url = self.app_info['url']
        comments_url += "fbcommentsplugin?asin=" + self.get_data['asin']
        comments_url += "&fbid=" + self.get_data['fbid']

        self.frame_seller_comments = HTML('<div data-height="600px" class="fb-comments" data-num-posts="3" data-width="600"></div>')

        self.seller_panel.add(self.html_seller_title)
        self.seller_panel.add(self.frame_seller_comments)
        return True

    def onRemoteResponse(self, response, request_info):
        """ Called when a response is received from an RPC
        """
        if not request_info.method in DataService.methods:
            Window.alert('Unrecognized JSONRPC method.')
            return

        if request_info.method == "get_facebook_user":
            self.facebook_user = {}
            for k, v in response.items():
                self.facebook_user[k] = v
        elif request_info.method == "get_book_details":
            self.book = {}
            for k, v in response.items():
                self.book[k] = v
        elif request_info.method == "get_app_info":
            self.app_info = {}
            for k, v in response.items():
                self.app_info[k] = v
        elif request_info.method == "get_sellers":
            self.sellers = response
        elif request_info.method == "user_has_book":
            self.has_book = response["result"]

    def onRemoteError(self, code, message, request_info):
        """ Called when a returned response is invalid for Server Error
        """
        code = str(code)
        message = str(message)

        if len(code) > 200: code = code[0:200] + "..."
        if len(message) > 200: message = message[0:200] + "..."

        err_msg = Label("Server Error or invalid response: ERROR " + str(code) + " - " + str(message))
        err_msg.addStyleName("status")
        Window.alert(err_msg.getText())