예제 #1
0
 def run( self ) :
     frame = JFrame( 'ButtonDemo_02' )
     frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE )
     button = frame.add( JButton( 'Press me' ) )
     button.addActionListener( self )
     frame.pack()
     frame.setVisible( 1 )
예제 #2
0
def complex_console():
    global frame
    #generates frame
    frame = JFrame("[BETA] Game Master\'s Bot - Console Log")
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
    frame.setResizable(False)
    frame.setAlwaysOnTop(True)
    frame.setBounds(8,545,600,130)
    frame.contentPane.layout = FlowLayout()
    
    #add QUIT button
    quitButton = JButton("QUIT", actionPerformed = closeFrame)
    quitButton.setForeground(Color.RED)
    quitButton.setPreferredSize(Dimension(100,100))
    frame.contentPane.add(quitButton)
    
    #add text message
    global textArea
    textArea = JTextArea(6,38)
    textArea.setEditable(False)
    frame.contentPane.add(textArea)
    scrollPane = JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)
    frame.contentPane.add(scrollPane)
    
    #show frame
    frame.pack()
    frame.setVisible(True)
    log("Welcome to Game Master\'s Bot!")
예제 #3
0
 def run( self ) :
     frame = JFrame( 'ButtonDemo_03' )
     frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE )
     button = frame.add( JButton( 'Press me' ) )
     button.actionPerformed = self.buttonPressed
     frame.pack()
     frame.setVisible( 1 )
예제 #4
0
def makeUI(model):
    table = JTable(model)
    jsp = JScrollPane(table)
    regex_label = JLabel("Search: ")
    regex_field = JTextField(20)
    top = JPanel()
    top.add(regex_label)
    top.add(regex_field)
    top.setLayout(BoxLayout(top, BoxLayout.X_AXIS))
    base_path_label = JLabel("Base path:")
    base_path_field = JTextField(50)
    bottom = JPanel()
    bottom.add(base_path_label)
    bottom.add(base_path_field)
    bottom.setLayout(BoxLayout(bottom, BoxLayout.X_AXIS))
    all = JPanel()
    all.add(top)
    all.add(jsp)
    all.add(bottom)
    all.setLayout(BoxLayout(all, BoxLayout.Y_AXIS))
    frame = JFrame("File paths")
    frame.getContentPane().add(all)
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
    frame.addWindowListener(Closing())
    frame.pack()
    frame.setVisible(True)
    # Listeners
    regex_field.addKeyListener(EnterListener(table, model, frame))
    table.addMouseListener(RowClickListener(base_path_field))
    #
    return model, table, regex_field, frame
예제 #5
0
def test_swing():
    frame = JFrame("Hello Jython")
    button = JButton("Pulsar", actionPerformed = hello)
    frame.add(button)
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    frame.setSize(200, 100)
    frame.show()
예제 #6
0
    def bg(self, panel2, e):
        bground = JFrame()
        bground.setTitle("Change Background")
        bground.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)
        bground.setSize(350, 100)
        bground.setLocationRelativeTo(None)
        bground.setVisible(True)
        bground.setResizable(False)

        panel = JPanel()
        #panel.setBackground(Color(46, 64, 96))
        bground.getContentPane().add(panel)

        path = JLabel("File:")
        panel.add(path)

        path2 = JTextField()
        path2.setPreferredSize(Dimension(180, 20))
        panel.add(path2)

        browse = JButton("Browse file",
                         actionPerformed=lambda e: self.browse(path2, e))
        panel.add(browse)

        change = JButton(
            "Change",
            actionPerformed=lambda e: self.change(path2.getText(), panel2, e))
        panel.add(change)

        bground.add(panel)
예제 #7
0
    def onInfo(self, e):
        info = JFrame()
        info.setTitle("Info")
        info.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)
        info.setSize(410, 400)
        info.setLocationRelativeTo(None)
        info.setResizable(False)
        info.setVisible(True)

        panel = JPanel()
        #panel.setBackground(Color(46, 64, 96))
        #panel.setLayout(GridLayout(0, 2))

        logo = JLabel(ImageIcon("/icons/logo.jpg"))
        panel.add(logo)

        f = Font("", Font.ITALIC, 40)
        title = JLabel("Stylus OS 1.0 beta")
        title.setFont(f)
        panel.add(title)

        f = Font("", Font.ITALIC, 14)
        copyright = JLabel(
            "Copyright (c) 2016 Niccolo' Ciavarella. All rights reserved.")
        copyright.setFont(f)
        panel.add(copyright)

        info.getContentPane().add(panel)
        info.add(panel)
예제 #8
0
    def initResultados(self):
        diag = JFrame()
        self.lineas = list()
        self.areaResultados = JTextArea()
        numLineas = self.readResultados()

        panelResultados = JPanel()
        #panelResultados.setAutoscrolls(True)
        panelResultados.setBorder(BorderFactory.createEtchedBorder())
        panelResultados.setLayout(GridLayout(0, 1))

        pane = JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                           JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)
        pane.viewport.view = self.areaResultados

        #pane.getViewport().add(panelResultados)

        diag.setTitle("RESULTADOS OBTENIDOS")

        diag.setSize(1000, 450)
        diag.setLayout(BorderLayout())
        diag.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        diag.setLocationRelativeTo(None)
        diag.setVisible(True)

        panelResultados.add(pane)
        diag.add(panelResultados, BorderLayout.CENTER)
def changePasswordForm(check):
    global frame
    global tfOldPassword
    global tfNewPassword
    global tfConfirmPassword
    global value

    value = check

    frame = JFrame("Change Password")
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    frame.setSize(500, 350)
    frame.setLocation(200, 200)
    frame.setLayout(None)
    frame.setVisible(True)

    panel = JPanel()
    panel.setSize(500, 350)
    panel.setLocation(0, 0)
    panel.setLayout(None)
    panel.setVisible(True)
    panel.setBackground(Color.LIGHT_GRAY)

    heading = JLabel("Change Password")
    heading.setBounds(200, 30, 150, 40)

    lbOldPassword = JLabel("Old Password")
    lbNewPassword = JLabel("New Password")
    lbConfirmPassword = JLabel("Confirm Password")

    tfOldPassword = JTextField()
    tfNewPassword = JTextField()
    tfConfirmPassword = JTextField()

    lbOldPassword.setBounds(50, 100, 150, 30)
    lbNewPassword.setBounds(50, 150, 150, 30)
    lbConfirmPassword.setBounds(50, 200, 150, 30)

    tfOldPassword.setBounds(220, 100, 150, 30)
    tfNewPassword.setBounds(220, 150, 150, 30)
    tfConfirmPassword.setBounds(220, 200, 150, 30)

    btnSave = JButton("Save", actionPerformed=clickSave)
    btnCancel = JButton("Cancel", actionPerformed=clickCancel)

    btnSave.setBounds(350, 280, 100, 30)
    btnCancel.setBounds(50, 280, 100, 30)

    panel.add(heading)
    panel.add(lbOldPassword)
    panel.add(lbNewPassword)
    panel.add(lbConfirmPassword)
    panel.add(tfOldPassword)
    panel.add(tfNewPassword)
    panel.add(tfConfirmPassword)
    panel.add(btnSave)
    panel.add(btnCancel)

    frame.add(panel)
예제 #10
0
 def run(self):
     frame = JFrame('Global Security')
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
     security = AdminConfig.list('Security')
     status = AdminConfig.showAttribute(security, 'enabled')
     frame.add(JLabel('Security enabled: ' + status))
     frame.pack()
     frame.setVisible(1)
예제 #11
0
def startGui():
    frame = JFrame("MonkeyPySon")
    frame.setContentPane(getContentPane())
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    frame.pack()
    frame.setVisible(True)
    frame.addWindowFocusListener(GuiWindowFocusListener())
    startLookingDevices()
예제 #12
0
def addCourse():
    global tfCourseName
    global tfCourseId
    global tfCourseFee
    global frame
    global btnEnter

    frame = JFrame("Add Course ")
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    frame.setSize(450, 450)
    frame.setLocation(200, 200)
    frame.setLayout(None)
    frame.setVisible(True)

    panel = JPanel()
    panel.setSize(450, 450)
    panel.setLocation(0, 0)
    panel.setLayout(None)
    panel.setVisible(True)
    panel.setBackground(Color.LIGHT_GRAY)

    heading = JLabel("ADD COURSE")
    heading.setBounds(200, 30, 150, 40)

    lbCourseName = JLabel("Course Name ")
    lbCourseId = JLabel("Course Id")
    lbCourseFee = JLabel(" Course Fee")

    tfCourseName = JTextField()
    tfCourseId = JTextField()
    tfCourseFee = JTextField()

    lbCourseName.setBounds(70, 120, 130, 30)
    lbCourseId.setBounds(70, 170, 130, 30)
    lbCourseFee.setBounds(70, 220, 130, 30)

    tfCourseName.setBounds(220, 120, 150, 30)
    tfCourseId.setBounds(220, 170, 150, 30)
    tfCourseFee.setBounds(220, 220, 150, 30)

    btnEnter = JButton("Enter", actionPerformed=clickAddCourseFee)
    btnEnter.setBounds(300, 300, 100, 40)

    btnCancel = JButton("Cancel", actionPerformed=clickCancel)
    btnCancel.setBounds(70, 300, 100, 40)

    panel.add(heading)
    panel.add(lbCourseName)
    panel.add(lbCourseId)
    panel.add(lbCourseFee)
    panel.add(tfCourseFee)
    panel.add(tfCourseName)
    panel.add(tfCourseId)
    panel.add(tfCourseFee)
    panel.add(btnEnter)
    panel.add(btnCancel)

    frame.add(panel)
예제 #13
0
    def createAndShowGUI(self):
        frame = JFrame("HelloWorldSwing")
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

        label = JLabel("Hello World")
        frame.getContentPane().add(label)

        frame.pack()
        frame.setVisible(True)
예제 #14
0
 def run(self):
     frame = JFrame('ButtonDemo_04')
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
     button = frame.add(JButton('Press me'))
     button.actionPerformed = self.buttonPressed
     self.label = JLabel('button press pending')
     frame.add(self.label, BorderLayout.SOUTH)
     frame.pack()
     frame.setVisible(1)
예제 #15
0
def studentLogined(stObj):
    global panel
    global table
    global heading
    global frame

    frame = JFrame("Student  Page ")
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    frame.setSize(500, 600)
    frame.setLocation(200, 200)
    frame.setLayout(None)

    panel = JPanel()
    panel.setSize(500, 580)
    panel.setLocation(0, 20)
    panel.setLayout(None)
    panel.setVisible(True)
    panel.setBackground(Color.WHITE)

    heading = JLabel()
    heading.setBounds(210, 10, 200, 30)

    table = JTable()
    table.setBounds(0, 50, 500, 470)
    sp = JScrollPane(table, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                     ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS)

    bar = JMenuBar()

    profile = JMenu("Profile")
    showProfile = JMenuItem("Show Profile",
                            actionPerformed=clickShowStudentProfile)
    changePassword = JMenuItem("Change Password",
                               actionPerformed=changeStudentPassword)
    profile.add(showProfile)
    profile.add(changePassword)
    bar.add(profile)

    attendence = JMenu("Attendence")
    showAllAttendence = JMenuItem("Show All Attendence",
                                  actionPerformed=clickAllAttendence)
    showAttendenceInMonth = JMenuItem("show attendence in month",
                                      actionPerformed=clickAttendenceInMonth)
    attendence.add(showAllAttendence)
    attendence.add(showAttendenceInMonth)
    bar.add(attendence)

    logout = JMenuItem("logout", actionPerformed=clickLogout)
    bar.add(logout)

    panel.add(table)

    frame.setJMenuBar(bar)
    frame.add(panel)

    frame.setVisible(True)
예제 #16
0
 def app(self, label="InQL Scanner"):
     frame = JFrame(label)
     frame.setForeground(Color.black)
     frame.setBackground(Color.lightGray)
     cp = frame.getContentPane()
     cp.add(self.this)
     frame.pack()
     frame.setVisible(True)
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
     while frame.isVisible():
         time.sleep(1)
예제 #17
0
    def run(self):
        frame = JFrame('BlueLabel')  # Create a JFrame with a title
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

        Label = JLabel()  # Create an empty label
        Label.setOpaque(1)  # Must be opaque for color to be seen
        Label.setBackground(Color.BLUE)  # Make the label blue
        Label.setPreferredSize(Dimension(200, 200))

        frame.getContentPane().add(Label)  # Add the label to the content pane

        frame.pack()  # Size frame to display the contents
        frame.setVisible(1)  # Finally, make the frame visible
예제 #18
0
def show_plot_in_frame(mainPanel):
    """
    embeds panel containing plots in a closable frame
    clears the panel background to white 
    """
    fr=JFrame()
    fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    fr.getContentPane().add(mainPanel)
    fr.setSize(1100,850);
    mainPanel.setSize(1100,850);
    mainPanel.setBackground(Color.WHITE);
    fr.show();
    return fr
예제 #19
0
def show_plot_in_frame(mainPanel):
    """
    embeds panel containing plots in a closable frame
    clears the panel background to white 
    """
    fr = JFrame()
    fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    fr.getContentPane().add(mainPanel)
    fr.setSize(1100, 850)
    mainPanel.setSize(1100, 850)
    mainPanel.setBackground(Color.WHITE)
    fr.show()
    return fr
예제 #20
0
파일: Main.py 프로젝트: sedjrodonan/lositan
def createFrame():
    global isDominant
    manager = doAction()
    if isTemporal:
        frame = JFrame("LosiTemp - LOoking for Selection In TEMPoral datasets")
    elif isDominant:
        frame = JFrame("Mcheza - Dominant Selection Workbench")
    else:
        frame = JFrame("LOSITAN - Selection Workbench")
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    doPrettyType(frame, manager)
    frame.setVisible(1)
    frame.setResizable(0)
    return frame
class FrameTestApp(object):
    def __init__(self, title, component):
        self._frame = JFrame(title)

        self._frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)

        self._frame.setPreferredSize(Dimension(640, 480))

        self._frame.add(component)

        self._frame.pack()

    def run(self):
        self._frame.setVisible(True)
예제 #22
0
def simple_console():
    global frame
    frame = JFrame("[BETA] GameMaster Bot - Log")
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
    frame.setBounds(0,45,560,30)
    global messageLOG
    messageLOG = JLabel("")
    frame.add(messageLOG,BorderLayout.CENTER)
    button = JButton("QUIT", actionPerformed =closeFrame)
    button.setForeground(Color.RED)
    frame.add(button,BorderLayout.WEST)
    frame.setUndecorated(True)
    frame.setAlwaysOnTop(True)
    frame.setVisible(True)
    log("Welcome to GameMaster\'s Bot!")
예제 #23
0
    def run_update(self):
        #from javax.swing import JFrame, JButton

        frame = JFrame("Hello")
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        frame.setLocation(100, 100)
        frame.setSize(300, 200)

        def updatePressed(event):
            jmri.jmrit.signalling.SignallingPanel.updatePressed(ActionEvent)(e)

        btn = JButton("Add", actionPerformed=updatePressed)
        frame.add(btn)

        frame.setVisible(True)
        btn.doClick
        frame.dispose()
예제 #24
0
def showLoginIdPassword(data):    
    global frame
    
    frame = JFrame("Show Id  Password ")
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    frame.setSize(500,350)
    frame.setLocation(200,200)
    frame.setLayout(None)
    frame.setVisible(True)
    
    panel = JPanel()
    panel.setSize(500,350)
    panel.setLocation(0,0)
    panel.setLayout(None)
    panel.setVisible(True)
    panel.setBackground(Color.LIGHT_GRAY)
    
    heading = JLabel("LoginId AND Password")
    heading.setBounds(200,30,150,40)
    
    lbLoginId = JLabel("LoginId")
    lbPassword = JLabel("password")
    
    tfLoginId = JTextField(data[0].encode('ascii'))
    tfPassword = JTextField(data[1].encode('ascii'))
    
    tfLoginId.setEditable(False)
    tfPassword.setEditable(False)
    
    lbLoginId.setBounds(50,100,150,30)
    lbPassword.setBounds(50,150,150,30)
    
    tfLoginId.setBounds(220,100,150,30)
    tfPassword.setBounds(220,150,150,30)
    
    btnOk = JButton("Ok",actionPerformed=clickOk)
    
    btnOk.setBounds(250,220,100,30)
    
    panel.add(heading)
    panel.add(lbLoginId)
    panel.add(lbPassword)
    panel.add(tfLoginId)
    panel.add(tfPassword)
    panel.add(btnOk)
    frame.add(panel)
예제 #25
0
    def run(self):
        #-----------------------------------------------------------------------
        # Create and set up the window.
        #-----------------------------------------------------------------------
        frame = JFrame('GlassPaneDemo')
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

        #-----------------------------------------------------------------------
        # Start creating and adding components.
        #-----------------------------------------------------------------------
        changeButton = JCheckBox('Glass pane "visible"')
        changeButton.setSelected(0)

        #-----------------------------------------------------------------------
        # Set up the content pane, where the 'main GUI' lives.
        #-----------------------------------------------------------------------
        contentPane = frame.getContentPane()
        contentPane.setLayout(FlowLayout())
        contentPane.add(changeButton)
        contentPane.add(JButton('Button 1'))
        contentPane.add(JButton('Button 2'))

        #-----------------------------------------------------------------------
        # Set up the menu bar, which appears above the content pane.
        #-----------------------------------------------------------------------
        menuBar = JMenuBar()
        menu = JMenu('Menu')
        menu.add(JMenuItem('Do nothing'))
        menuBar.add(menu)
        frame.setJMenuBar(menuBar)

        #-----------------------------------------------------------------------
        # Set up the glass pane, which appears over both menu bar and
        # content pane and is an item listener on the change button
        #-----------------------------------------------------------------------
        myGlassPane = MyGlassPane(changeButton, menuBar, contentPane)
        changeButton.addItemListener(myGlassPane)
        frame.setGlassPane(myGlassPane)

        #-----------------------------------------------------------------------
        # Resize the frame to display the visible components contain therein,
        # and have the frame (application) make itself visisble.
        #-----------------------------------------------------------------------
        frame.pack()
        frame.setVisible(1)
def getCourseName(check):    
    global frame
    global tfStudentCourseChoice
    global value

    value = check
    
    frame = JFrame("Course Name ")
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    frame.setSize(500,250)
    frame.setLocation(200,200)
    frame.setLayout(None)
    frame.setVisible(True)
    
    panel = JPanel()
    panel.setSize(500,250)
    panel.setLocation(0,0)
    panel.setLayout(None)
    panel.setVisible(True)
    panel.setBackground(Color.LIGHT_GRAY)
    
    heading = JLabel("Get Course Name")
    heading.setBounds(200,30,150,40)
    
    lbStudentCourseChoice = JLabel("Student course name")
    tfStudentCourseChoice = JTextField()
    
    lbStudentCourseChoice.setBounds(50,70,150,30)
    tfStudentCourseChoice.setBounds(220,70,150,30)
    
    btnEnter = JButton("Enter",actionPerformed=clickStudentCourseChoice)
    btnCancel = JButton("Cancel",actionPerformed=clickBtnCancel)
    
    btnEnter.setBounds(350,150,100,30)
    btnCancel.setBounds(50,150,100,30)
    
    panel.add(heading)
    panel.add(lbStudentCourseChoice)
    panel.add(tfStudentCourseChoice)
    panel.add(btnEnter)
    panel.add(btnCancel)
    frame.add(panel)
예제 #27
0
def createAndShowGUI():
    # Create the GUI and show it. As with all GUI code, this must run
    # on the event-dispatching thread.
    frame = JFrame("GUI Development ")
    frame.setSize(500, 600)
    frame.setLayout(BorderLayout())
    splitPane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
    
    #Create and set up the content pane.
    psimures= ResourcePanel()
    psimures.setOpaque(True)
    pconfig = ConfigurationPanel()
    pconfig.setOpaque(True)      #content panes must be opaque

    # show the GUI
    splitPane.add(psimures)
    splitPane.add(pconfig)
    frame.add(splitPane)
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
    frame.setVisible(True)
예제 #28
0
def showStudentAttendenceSheetTeacherLogin():
    global table
    global heading
    global frame
    global panel
    global btnSave
    global btnCancel
    
    frame = JFrame("Student Attendence Sheet ")
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    frame.setSize(500,600)
    frame.setLocation(200,200)
    frame.setLayout(None)
    frame.setVisible(True)
    
    panel = JPanel()
    panel.setSize(500,600)
    panel.setLocation(0,0)
    panel.setLayout(None)
    panel.setVisible(True)
    panel.setBackground(Color.WHITE)
    
    heading = JLabel()
    heading.setBounds(200,10,150,30)
    
    table = JTable()
    table.setBounds(0,50,500,450)
    panel.add(table)
    
    btnSave = JButton("Save",actionPerformed = clickSaveBtn)
    btnCancel = JButton("Cancel",actionPerformed = clickCancelBtn)
    
    btnSave.setBounds(350,540,100,40)
    btnCancel.setBounds(70,540,100,40)

    panel.add(heading)
    panel.add(table)
    panel.add(btnSave)
    panel.add(btnCancel)
    
    frame.add(panel)
예제 #29
0
def createAndShowGUI():
    # Create the GUI and show it. As with all GUI code, this must run
    # on the event-dispatching thread.
    frame = JFrame("MAE ")
    frame.setSize(1024, 768)
    panel= JPanel()
    panel.setLayout(GridBagLayout())
    
    #Create and set up the content pane.
    psimures= SimoutPanel()
    psimures.setOpaque(True)
    c = GridBagConstraints()
    c.fill = GridBagConstraints.HORIZONTAL
    c.weightx = 1
    c.gridx = 0
    c.gridy = 0
    panel.add(psimures, c);
    pmeasure= MeasPanel()
    pmeasure.setOpaque(True)
    c = GridBagConstraints()
    c.fill = GridBagConstraints.HORIZONTAL
    c.weightx = 1
    c.gridx = 0
    c.gridy = 1
    panel.add(pmeasure, c);
    preport = ReportPanel()
    preport.setOpaque(True)
    c = GridBagConstraints()
    c.fill = GridBagConstraints.VERTICAL
    c.weighty = 1
    c.gridx = 1
    c.gridy = 0
    c.gridheight= 2
    panel.add(preport,c)
    # show the GUI
    
    frame.add(panel)
#     frame.add(pmeasure)
#     frame.add(preport)
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
    frame.setVisible(True)
예제 #30
0
    class SwingExample:
        def __init__(self):
            self.mainFrame = None
            self.mainTabbedPane = JTabbedPane()

        def start(self):
            self.mainFrame = JFrame("SwingTest")
            self.mainFrame.setSize(800, 600)
            self.mainFrame.setLocationRelativeTo(None)
            self.mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
            self.mainFrame.add(self.mainTabbedPane)
            self.mainFrame.setVisible(True)

        def addToTabbedPane(self, tabName, component):
            self.mainTabbedPane.addTab(tabName, component)

        def main(self):
            self.addToTabbedPane("Beautify", BeautifierPanel())
            self.addToTabbedPane("Options", BeautifierOptionsPanel(None))

            self.start()
예제 #31
0
    def __init__(self):
        frame = JFrame("Jython JTable Example")
        frame.setSize(500, 250)
        frame.setLayout(BorderLayout())

        self.tableData = [
            ['Mouse 1', eventNames[0], eventScriptType[0]],
            ['Mouse 2', eventNames[1], eventScriptType[1]],
            ['Mouse 3', eventNames[2], eventScriptType[2]],
            ['Mouse 1 Shift', eventNames[3], eventScriptType[3]],
            ['Mouse 2 Shift', eventNames[4], eventScriptType[4]],
            ['Mouse 3 Shift', eventNames[5], eventScriptType[5]],
            ['Mouse 1 Control', eventNames[6], eventScriptType[6]],
            ['Mouse 2 Control', eventNames[7], eventScriptType[7]],
            ['Mouse 3 Control', eventNames[8], eventScriptType[8]],
        ]
        colNames = ('Script/Event', 'Name', 'Type')
        dataModel = DefaultTableModel(self.tableData, colNames)
        self.table = JTable(dataModel)

        scrollPane = JScrollPane()
        scrollPane.setPreferredSize(Dimension(400, 200))
        scrollPane.getViewport().setView((self.table))

        panel = JPanel()
        panel.add(scrollPane)

        frame.add(panel, BorderLayout.CENTER)

        self.label = JLabel('Hello from Jython')
        frame.add(self.label, BorderLayout.NORTH)
        button = JButton('Save Settings', actionPerformed=self.setText)
        frame.add(button, BorderLayout.SOUTH)
        exitButton = JButton('Exit', actionPerformed=self.myExit)
        frame.add(exitButton, BorderLayout.EAST)

        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
        frame.setVisible(True)
예제 #32
0
  def __init__(self):
    frame = JFrame("Jython JTable Example")
    frame.setSize(500, 250)
    frame.setLayout(BorderLayout())

    self.tableData = [
      ['Mouse 1', eventNames[0], eventScriptType[0]],
      ['Mouse 2', eventNames[1] , eventScriptType[1]],
      ['Mouse 3', eventNames[2], eventScriptType[2]],
      ['Mouse 1 Shift', eventNames[3], eventScriptType[3]],
      ['Mouse 2 Shift',eventNames[4], eventScriptType[4]],
      ['Mouse 3 Shift',eventNames[5], eventScriptType[5]],
      ['Mouse 1 Control',eventNames[6], eventScriptType[6]],
      ['Mouse 2 Control',eventNames[7], eventScriptType[7]],
      ['Mouse 3 Control',eventNames[8], eventScriptType[8]],
       ]
    colNames = ('Script/Event','Name','Type')
    dataModel = DefaultTableModel(self.tableData, colNames)
    self.table = JTable(dataModel)

    scrollPane = JScrollPane()
    scrollPane.setPreferredSize(Dimension(400,200))
    scrollPane.getViewport().setView((self.table))

    panel = JPanel()
    panel.add(scrollPane)

    frame.add(panel, BorderLayout.CENTER)

    self.label = JLabel('Hello from Jython')
    frame.add(self.label, BorderLayout.NORTH)
    button = JButton('Save Settings',actionPerformed=self.setText)
    frame.add(button, BorderLayout.SOUTH)
    exitButton = JButton('Exit',actionPerformed=self.myExit)
    frame.add(exitButton, BorderLayout.EAST)

    frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
    frame.setVisible(True)
예제 #33
0
    def onExit(self, e):
        exit = JFrame()
        exit.setTitle("Exit Stylus")
        exit.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)
        exit.setSize(250, 225)
        exit.setLocationRelativeTo(None)
        exit.setVisible(True)
        exit.setResizable(False)

        panel = JPanel()
        panel.setBorder(BorderFactory.createEtchedBorder())
        panel.setLayout(GridLayout(0, 1))
        exit.getContentPane().add(panel)

        icon1 = ImageIcon("/icons/shutdown.png")
        poweroff = JButton("Shutdown", icon1, actionPerformed=self.shutdown)
        panel.add(poweroff)

        icon2 = ImageIcon("/icons/reboot.png")
        reboot = JButton("  Reboot    ", icon2, actionPerformed=self.reboot)
        panel.add(reboot)

        exit.add(panel)
예제 #34
0
파일: animate.py 프로젝트: cgraziano/misc
def main(args):
  _WIDTH = 300
  _HEIGHT = 300
  fps = 20#frames per second
  bgColor = Color.white
  frame = JFrame("Graphics!")
  frame.setBackground(bgColor);
  frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)

  drawgraphics = DrawGraphics()
  content = Animator(drawgraphics, _WIDTH, _HEIGHT, fps)
  content.setBackground(bgColor)
  content.setSize(_WIDTH, _HEIGHT)
  content.setMinimumSize(Dimension(_WIDTH, _HEIGHT))
  content.setPreferredSize(Dimension(_WIDTH, _HEIGHT))

  frame.setSize(_WIDTH, _HEIGHT)
  frame.setContentPane(content)
  frame.setResizable(True)
  frame.pack()

  Thread(content).start()
  frame.setVisible(True)
예제 #35
0
class BurpExtender(IBurpExtender, IBurpExtenderCallbacks, IIntruderPayloadProcessor, ITab, IExtensionStateListener):
    def registerExtenderCallbacks( self, callbacks):
        self._helpers = callbacks.getHelpers()
        callbacks.setExtensionName("JWT FuzzHelper")
        callbacks.registerIntruderPayloadProcessor(self)
        callbacks.registerExtensionStateListener(self)
        
        self._stdout = PrintWriter(callbacks.getStdout(), True)
        self._stderr = PrintWriter(callbacks.getStderr(), True)

        # Holds values passed by user from Configuration panel
        self._fuzzoptions = { 
                                "target" : "Header", 
                                "selector" : None, 
                                "signature" : False,
                                "algorithm" : "HS256",
                                "key" : "",
                                "key_cmd" : ""
                            }

        self._isNone = lambda val: isinstance(val, type(None))

        # Configuration panel Layout
        self._configurationPanel = JPanel()
        gridBagLayout = GridBagLayout()
        gridBagLayout.columnWidths = [ 0, 0, 0]
        gridBagLayout.rowHeights = [ 10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
        gridBagLayout.columnWeights = [ 0.0, 0.0, 0.0 ]
        gridBagLayout.rowWeights = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]
        self._configurationPanel.setLayout(gridBagLayout)

        # Setup tabs
        self._tabs = JTabbedPane()
        self._tabs.addTab('Configuration',self._configurationPanel)
        #self._tabs.addTab('Help',self._helpPanel)

        # Target Options
        targetLabel = JLabel("Target Selection (Required): ")
        targetLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 1
        c.insets = Insets(0,10,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(targetLabel,c)

        options = [ 'Header', 'Payload' ]
        self._targetComboBox = JComboBox(options)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 1
        c.anchor = GridBagConstraints.LINE_START
        self._configurationPanel.add(self._targetComboBox,c)

        # Help Button
        self._helpButton = JButton("Help", actionPerformed=self.helpMenu)
        c = GridBagConstraints()
        c.gridx = 2
        c.gridy = 1
        c.anchor = GridBagConstraints.FIRST_LINE_START
        self._configurationPanel.add(self._helpButton,c)

        # Selector Options
        self._selectorLabel = JLabel("JSON Selector [Object Identifier-Index Syntax] (Required): ")
        self._selectorLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 2
        c.insets = Insets(0,10,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(self._selectorLabel, c)

        self._selectorTextField = JTextField('',50)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 2
        self._configurationPanel.add(self._selectorTextField, c)

        # Regex option

        self._regexLabel = JLabel("Use regex as JSON Selector? (Optional): ")
        self._regexLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 3
        c.insets = Insets(0,0,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(self._regexLabel,c)

        self._regexCheckBox = JCheckBox("", actionPerformed=self.regexSelector)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 3
        c.anchor = GridBagConstraints.FIRST_LINE_START
        self._configurationPanel.add(self._regexCheckBox,c)

        # Signature Options
        generateSignatureLabel = JLabel("Generate signature? (Required): ")
        generateSignatureLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 4
        c.insets = Insets(0,10,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(generateSignatureLabel,c)

        options = ["False", "True"]
        self._generateSignatureComboBox = JComboBox(options)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 4
        c.anchor = GridBagConstraints.LINE_START
        self._configurationPanel.add(self._generateSignatureComboBox,c)

        signatureAlgorithmLabel = JLabel("Signature Algorithm (Optional): ")
        signatureAlgorithmLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 5
        c.insets = Insets(0,10,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(signatureAlgorithmLabel,c)

        options = ["None", "HS256","HS384","HS512","ES256","ES384","ES512","RS256","RS384","RS512","PS256","PS256","PS384","PS512"]
        self._algorithmSelectionComboBox = JComboBox(options)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 5
        c.anchor = GridBagConstraints.LINE_START
        self._configurationPanel.add(self._algorithmSelectionComboBox,c)

        # Signing key options
        self._signingKeyLabel = JLabel("Signing Key (Optional): ")
        self._signingKeyLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 6
        c.insets = Insets(0,10,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(self._signingKeyLabel,c)

        self.addSigningKeyTextArea()
        self._fromFileTextField = JTextField('',50) 

        fromFileLabel = JLabel("Signing key from file? (Optional): ")
        fromFileLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 7
        c.insets = Insets(0,0,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(fromFileLabel,c)

        self._fromFileCheckBox = JCheckBox("", actionPerformed=self.fromFile)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 7
        c.anchor = GridBagConstraints.FIRST_LINE_START
        self._configurationPanel.add(self._fromFileCheckBox,c)

        self._fromCmdTextField = JTextField('',50)

        fromCmdLabel = JLabel("Signing key from command? (Optional): ")
        fromCmdLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 8
        c.insets = Insets(0,0,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(fromCmdLabel,c)

        self._fromCmdCheckBox = JCheckBox("", actionPerformed=self.fromCmd)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 8
        c.anchor = GridBagConstraints.FIRST_LINE_START
        self._configurationPanel.add(self._fromCmdCheckBox,c)

        self._saveButton = JButton("Save Configuration", actionPerformed=self.saveOptions)
        self._saveButton.setText("Save Configuration")
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 9
        c.anchor = GridBagConstraints.FIRST_LINE_START
        self._configurationPanel.add(self._saveButton,c)

        
        callbacks.customizeUiComponent(self._configurationPanel)
        callbacks.customizeUiComponent(self._tabs)
        callbacks.addSuiteTab(self)

        self._stdout.println("[JWT FuzzHelper] Loaded successfully")
        return


    def getProcessorName(self):
        return "JWT Fuzzer"

    def extensionUnloaded(self):
        del self._configurationPanel
        return

    # Intruder logic function
    def processPayload(self, currentPayload, originalPayload, baseValue):
        dataParameter = self._helpers.bytesToString(
                         self._helpers.urlDecode(baseValue)
                       )

        # utf-8 encode
        header,payload,signature = [unicode(s).encode('utf-8') for s in dataParameter.split(".",3)]
        decoded_header = self._helpers.bytesToString(
                            self._helpers.base64Decode(header + "=" * (-len(header) % 4))
                        )
        decoded_payload = self._helpers.bytesToString(
                            self._helpers.base64Decode(payload+"=" * (-len(payload) % 4))
                        )

        # Decode header and payload, preserving order if they are JSON objects

        # Decode header
        try:
            header_dict = json.loads(decoded_header, object_pairs_hook=OrderedDict)
        except ValueError:
            raise RuntimeException("[JWT FuzzHelper] Error: ValueError. Failed to decode header!")
        except Exception as e:
            self._stderr.println("[ERROR] Encountered an unknown error when decoding header:\n{}\nCarrying on...".format(e))

        # Decode payload
        # Payload does not have to be a JSON object.
        #   Ref: https://github.com/auth0/node-jsonwebtoken#usage
        payload_is_string = False
        try:
            payload_dict = json.loads(decoded_payload, object_pairs_hook=OrderedDict)
        except ValueError:
            payload_is_string = True
            payload_dict = decoded_payload
        except Exception as e:
            self._stderr.println("[ERROR] Encountered an unknown error when decoding payload:\n{}\nCarrying on...".format(e))

        target = header_dict if self._fuzzoptions["target"] == "Header" else payload_dict
        selector = self._fuzzoptions["selector"]

        # If using Object Identifier-Index then retrieve the 
        # value specified by the selector, 
        # if this value does not exist, assume the user
        # wants to add the value that would have been specified
        # by the selector to the desired JWT segment (this behavior will 
        # be noted in the help docs)

        intruderPayload = self._helpers.bytesToString(currentPayload)
        if not self._fuzzoptions["regex"]:
            if selector != [""]:
                try:
                    value = self.getValue(target, selector)
                except Exception:
                    target = self.buildDict(target, selector)

            if not self._isNone(selector) and selector != [""]:
                target = self.setValue(target, selector, intruderPayload)
        
        # Simple match-replace for regex
        if self._fuzzoptions["regex"]:
            target_string = target if payload_is_string else json.dumps(target)
            target_string = re.sub(selector, intruderPayload, target_string)
            target = target_string if payload_is_string else json.loads(target_string, object_pairs_hook=OrderedDict)
            if self._fuzzoptions["target"] == "Payload":
                payload_dict = target
            else:
                header_dict = target
                

        algorithm = self._fuzzoptions["algorithm"]
        if self._fuzzoptions["signature"]: 
            # pyjwt requires lowercase 'none'. If user wants to try
            # "none", "NonE", "nOnE", etc... they should use .alg
            # as selector, delete sig from intruder and use those
            # permutations as their fuzz list (outlined in help docs)
            # and keep "Generate Signature" as False
            algorithm = "none" if algorithm.lower() == "none" else algorithm
            header_dict["alg"] = algorithm

        header = json.dumps(header_dict, separators=(",",":"))
        payload = payload_dict if payload_is_string else json.dumps(payload_dict, separators=(",",":"))
        header = self._helpers.base64Encode(header).strip("=")
        payload = self._helpers.base64Encode(payload).strip("=")

        contents = header + "." + payload
        
        key = self._fuzzoptions["key"]

        if len(self._fuzzoptions["key_cmd"]) > 0:
            # we provide 'contents' value as an only argument to key-generating command
            # it is expected that the command will print only the signature
            signature = check_output([self._fuzzoptions["key_cmd"], contents])
            modified_jwt = contents + "." + signature
        elif self._fuzzoptions["signature"]:
            # pyjwt throws error when using a public key in symmetric alg (for good reason of course),
            # must do natively to support algorithmic sub attacks
            if algorithm.startswith("HS"):
                if algorithm == "HS256":
                    hmac_algorithm = hashlib.sha256
                elif algorithm == "HS384":
                    hmac_algorithm = hashlib.sha384
                else:
                    hmac_algorithm = hashlib.sha512
            
                signature = self._helpers.base64Encode(
                            hmac.new(
                                    key, contents, hmac_algorithm
                                ).digest()
                    ).strip("=")

                modified_jwt = contents + "." +signature

            # JWT can't sign non-JSON payloads. WTF. This block is for non-JSON payloads.
            elif algorithm.startswith("RS") and payload_is_string:
                if algorithm == "RS256":
                    rsa_algorithm = "SHA-256"
                elif algorithm == "RS384":
                    rsa_algorithm = "SHA-384"
                else:
                    rsa_algorithm = "SHA-512"
                privkey = rsa.PrivateKey.load_pkcs1(key)
                signature = rsa.sign(contents,privkey,rsa_algorithm)
                signature = base64.b64encode(signature).encode('utf-8').replace("=", "")
                modified_jwt = contents + "." + signature
            else:
                # Use pyjwt when using asymmetric alg
                if algorithm == "none":
                    key = ""
                modified_jwt = jwt.encode(payload_dict,key,algorithm=algorithm,headers=header_dict)
        else:
            modified_jwt = contents + "." + signature

        return self._helpers.stringToBytes(modified_jwt)

    
    #-----------------------
    # getValue:
    #   @return: A value at arbitrary depth in dictionary
    #   @throws: TypeError
    #-----------------------
    def getValue(self, dictionary, values):
        return reduce(dict.__getitem__, values, dictionary)

    #-----------------------
    # buildDict:
    #   @note: Will build dictionary of arbitrary depth
    #-----------------------
    def buildDict(self, dictionary, keys):
        if self._isNone(keys):
            return dictionary

        root = current = dictionary
        for key in keys:
            if key not in current:
                current[key] = {}
            current = current[key]
        return root

    #----------------------
    # setValue:
    #   @note: Will set key of arbitrary depth
    #-----------------------
    def setValue(self, dictionary, keys, value):
        root = current = dictionary
        for i,key in enumerate(keys):
            if i == len(keys) - 1:
                current[key] = value
                break
            if key in current:
                current = current[key]
            else:
                # Should never happen
                current = self.buildDict(current, keys)
        return root
    
    #-----------------------
    # addSigningKeyTextArea:
    #   @note: Will toggle if fromFile selected. Be DRY.
    #----------------------
    def addSigningKeyTextArea(self):
        self._signingKeyTextArea = JTextArea()
        self._signingKeyTextArea.setColumns(50)
        self._signingKeyTextArea.setRows(10)
        self._signingKeyScrollPane = JScrollPane(self._signingKeyTextArea)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 6
        c.anchor = GridBagConstraints.LINE_START
        self._configurationPanel.add(self._signingKeyScrollPane,c)

    def addSigningKeyFromFileTextField(self):
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 6
        self._configurationPanel.add(self._fromFileTextField, c)

    def addSigningKeyFromCmdTextField(self):
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 6
        self._configurationPanel.add(self._fromCmdTextField, c)
    #-----------------------
    # End Helpers
    #-----------------------

    #-----------------------
    # Implement ITab
    #-----------------------

    def getTabCaption(self):
        return "JWT FuzzHelper"

    def getUiComponent(self):
        return self._tabs

    #---------------------------
    # Save configuration options
    #---------------------------

    def saveOptions(self,event):
        self._fuzzoptions["target"]     = self._targetComboBox.getSelectedItem()
        self._fuzzoptions["selector"]   = self._selectorTextField.getText()
        self._fuzzoptions["signature"]  = True if self._generateSignatureComboBox.getSelectedItem() == "True" else False
        self._fuzzoptions["algorithm"]  = self._algorithmSelectionComboBox.getSelectedItem()
        self._fuzzoptions["key_cmd"]    = ""
        
        if self._fromFileCheckBox.isSelected():
            filename = self._fromFileTextField.getText()
            if os.path.isdir(filename):
                self._stderr.println("{} is a directory".format(filename))
                return
            if os.path.exists(filename):
                with open(filename, 'rb') as f:
                    self._fuzzoptions["key"] = f.read()
        elif self._fromCmdCheckBox.isSelected():
            self._fuzzoptions["key_cmd"] = self._fromCmdTextField.getText()
        else:
            self._fuzzoptions["key"]    = unicode(self._signingKeyTextArea.getText()).encode("utf-8")
        # RSA keys need to end with a line break. Many headaches because of this.
        if not self._fuzzoptions["key"].endswith("\n") and self._fuzzoptions["algorithm"].startswith("RS"):
            self._fuzzoptions["key"] += "\n"
        self._stdout.println("[JWT FuzzHelper] Saved options:\n{}".format(self._fuzzoptions))


        # Sanity check selector if it's not a regular expression
        self._fuzzoptions["regex"] = self._regexCheckBox.isSelected()
        if not self._regexCheckBox.isSelected():
            m = re.search("(\.\w+)+",self._fuzzoptions["selector"])
            if self._fuzzoptions["selector"] != "." and (isinstance(m,type(None)) or m.group(0) != self._fuzzoptions["selector"]):
                self._saveButton.setText("Invalid JSON Selector!")
            else:
                self._fuzzoptions["selector"] = self._fuzzoptions["selector"].split(".")[1:]
                self._saveButton.setText("Saved!")
        # Sanity check the regular expression
        else:
            try:
                re.compile(self._fuzzoptions["selector"])
                self._saveButton.setText("Saved!")
            except re.error:
                self._saveButton.setText("Invalid Regex!")
        return

    #-------------------------
    # From file options
    #------------------------
    def fromFile(self,event):
        if self._fromFileCheckBox.isSelected():
            self._signingKeyLabel.setText("Path to Signing Key (Optional): ")
            self._configurationPanel.remove(self._signingKeyScrollPane)
            self.addSigningKeyFromFileTextField()
        else:
            self._signingKeyLabel.setText("Signing Key (Optional): ")
            self._configurationPanel.remove(self._fromFileTextField)
            self.addSigningKeyTextArea()
        self._configurationPanel.repaint()
        return

    def fromCmd(self,event):
        if self._fromCmdCheckBox.isSelected():
            self._signingKeyLabel.setText("Path to Signing Cmd (Optional): ")
            self._configurationPanel.remove(self._signingKeyScrollPane)
            self.addSigningKeyFromCmdTextField()
        else:
            self._signingKeyLabel.setText("Signing Key (Optional): ")
            self._configurationPanel.remove(self._fromCmdTextField)
            self.addSigningKeyTextArea()
        self._configurationPanel.repaint()
        return

    def regexSelector(self,event):
        if self._regexCheckBox.isSelected():
            self._selectorLabel.setText("Selector [Regex] (Required): ")
        else:
            self._selectorLabel.setText("JSON Selector [Object Identifier-Index Syntax] (Required): ")
        self._configurationPanel.repaint()
        return
    #-------------------------
    # Help popup
    #-------------------------
    def helpMenu(self,event):
        self._helpPopup = JFrame('JWT Fuzzer', size=(550, 450) );
        self._helpPopup.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
        helpPanel = JPanel()
        helpPanel.setPreferredSize(Dimension(550, 450))
        helpPanel.setBorder(EmptyBorder(10, 10, 10, 10))
        helpPanel.setLayout(BoxLayout(helpPanel, BoxLayout.Y_AXIS))
        self._helpPopup.setContentPane(helpPanel)
        helpHeadingText = JLabel("<html><h2>JWT Fuzzer</h2></html>")
        authorText = JLabel("<html><p>@author: &lt;pinnace&gt;</p></html>")
        aboutText = JLabel("<html><br /> <p>This extension adds an Intruder payload processor for JWTs.</p><br /></html>")
        repositoryText = JLabel("<html>Documentation and source code:</html>")
        repositoryLink = JLabel("<html>- <a href=\"https://github.com/pinnace/burp-jwt-fuzzhelper-extension\">https://github.com/pinnace/burp-jwt-fuzzhelper-extension</a></html>")
        licenseText = JLabel("<html><br/><p>JWT Fuzzer uses a GPL 3 license. This license does not apply to the dependency below:<p></html>") 
        dependencyLink = JLabel("<html>- <a href=\"https://github.com/jpadilla/pyjwt/blob/master/LICENSE\">pyjwt</a></html>")
        dependencyLink.addMouseListener(ClickListener())
        dependencyLink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR))
        repositoryLink.addMouseListener(ClickListener())
        repositoryLink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR))
        
        helpPanel.add(helpHeadingText)
        helpPanel.add(authorText)
        helpPanel.add(aboutText)
        helpPanel.add(repositoryText)
        helpPanel.add(repositoryLink)
        helpPanel.add(licenseText)
        helpPanel.add(dependencyLink)

        self._helpPopup.setSize(Dimension(550, 450))
        self._helpPopup.pack()
        self._helpPopup.setLocationRelativeTo(None)
        self._helpPopup.setVisible(True)
        return
예제 #36
0
파일: image.py 프로젝트: HenryStevens/jes
class Image:
   """Holds an image of RGB pixels accessed by column and row indices (col, row).  
      Origin (0, 0) is at upper left."""
      
# QUESTION:  For efficiency, should we also extract and save self.pixels (at image reading time)?
# Also make setPixel(), getPixel(), setPixels() and getPixels() work on/with self.pixels.  
# And when writing, use code in current setPixels() to update image buffer, before writing it out?
# This is something to try.
   
   def __init__(self, filename, width=None, height=None): 
      """Create an image from a file, or an empty (black) image with specified dimensions."""
      
      # Since Python does not allow constructors with different signatures,
      # the trick is to reuse the first argument as a filename or a width.
      # If it is a string, we assume they want is to open a file.
      # If it is an int, we assume they want us to create a blank image.
      
      if type(filename) == type(""):  # is it a string?
         self.filename = filename        # treat is a filename
         self.image = BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB)  # create a dummy image
         self.read(filename)             # and read external image into ti
                  
      elif type(filename) == type(1): # is it a int?
      
         # create blank image with specified dimensions
         self.filename = "Untitled"
         self.width = filename       # holds image width (shift arguments)
         self.height = width         # holds image height
         self.image = BufferedImage(self.width, self.height, BufferedImage.TYPE_INT_RGB)  # holds image buffer (pixels)
      else:
         raise  TypeError("Image(): first argument must a filename (string) or an blank image width (int).")
         
      # display image
      self.display = JFrame()      # create frame window to hold image
      icon = ImageIcon(self.image) # wrap image appropriately for displaying in a frame
      container = JLabel(icon)         
      self.display.setContentPane(container)  # and place it

      self.display.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
      self.display.setTitle(self.filename)
      self.display.setResizable(False)
      self.display.pack()
      self.display.setVisible(True)

 
   def getWidth(self):
      """Returns the width of the image.""" 
      
      return self.width
      
   def getHeight(self):
      """Returns the height of the image.""" 
      
      return self.height
      
   def getPixel(self, col, row):
      """Returns a list of the RGB values for this pixel, e.g., [255, 0, 0].""" 
      
      # Obsolete - convert the row so that row zero refers to the bottom row of pixels.
      #row = self.height - row - 1

      color = Color(self.image.getRGB(col, row))  # get pixel's color
      return [color.getRed(), color.getGreen(), color.getBlue()]  # create list of RGB values (0-255)

   def setPixel(self, col, row, RGBlist):
      """Sets this pixel's RGB values, e.g., [255, 0, 0].""" 
      
      # Obsolete - convert the row so that row zero refers to the bottom row of pixels.
      #row = self.height - row - 1

      color = Color(RGBlist[0], RGBlist[1], RGBlist[2])  # create color from RGB values
      self.image.setRGB(col, row, color.getRGB())


   def getPixels(self):
      """Returns a 2D list of pixels (col, row) - each pixel is a list of RGB values, e.g., [255, 0, 0].""" 
      
      pixels = []                      # initialize list of pixels
      #for row in range(self.height-1, 0, -1):   # load pixels from image      
      for row in range(0, self.height):   # load pixels from image      
         pixels.append( [] )              # add another empty row
         for col in range(self.width):    # populate row with pixels    
            # RGBlist = self.getPixel(col, row)   # this works also (but slower)    
            color = Color(self.image.getRGB(col, row))  # get pixel's color
            RGBlist = [color.getRed(), color.getGreen(), color.getBlue()]  # create list of RGB values (0-255)
            pixels[-1].append( RGBlist )   # add a pixel as (R, G, B) values (0-255, each)

      # now, 2D list of pixels has been created, so return it
      return pixels

   def setPixels(self, pixels):
      """Sets image to the provided 2D list of pixels (col, row) - each pixel is a list of RGB values, e.g., [255, 0, 0].""" 
      
      self.height = len(pixels)        # get number of rows
      self.width  = len(pixels[0])     # get number of columns (assume all columns have same length
      
      #for row in range(self.height-1, 0, -1):   # iterate through all rows      
      for row in range(0, self.height):   # iterate through all rows     
         for col in range(self.width):    # iterate through every column on this row
         
            RGBlist = pixels[row][col]
            #self.setPixel(col, row, RGBlist)   # this works also (but slower)
            color = Color(RGBlist[0], RGBlist[1], RGBlist[2])  # create color from RGB values
            self.image.setRGB(col, row, color.getRGB())

   def read(self, filename): 
      """Read an image from a .png, .gif, or .jpg file. as 2D list of RGB pixels."""
      
      # JEM working directory fix (see above)
      filename = fixWorkingDirForJEM( filename )   # does nothing if not in JEM
	  
      # ***
      #print "fixWorkingDirForJEM( filename ) =", filename

      file = File(filename)    # read file from current directory
      self.image = ImageIO.read(file)
      self.width  = self.image.getWidth(None)
      self.height = self.image.getHeight(None)
      
      pixels = []   # initialize list of pixels
      
      # load pixels from image
      for row in range(self.height):
         pixels.append( [] )   # add another empty row
         for col in range(self.width):   # now, populate row with pixels
            color = Color(self.image.getRGB(col, row))  # get pixel's color
            RGBlist = [color.getRed(), color.getGreen(), color.getBlue()]  # create list of RGB values (0-255)
            pixels[-1].append( RGBlist )   # add a pixel as (R, G, B) values (0-255, each)

      # now, pixels have been loaded from image file, so create an image
      self.setPixels(pixels)
      
   def write(self, filename):
      """Saves the pixels to a file (.png or .jpg)."""
      
      # JEM working directory fix (see above)
      filename = fixWorkingDirForJEM( filename )   # does nothing if not in JEM
	  
      # ***
      #print "fixWorkingDirForJEM( filename ) =", filename

      # get suffix
      suffix = filename[-3:]   
      suffix = suffix.lower()
      
      if suffix == "jpg" or suffix =="png":
         ImageIO.write(self.image, suffix, File(filename))  # save, and also
         self.filename = filename               # update image filename
         self.display.setTitle(self.filename)   # update display title            
      else:
         print "Filename must end in .jpg or .png"

   def show(self):
      """It displays the image."""
      
      self.display.setVisible(True)
      #self.display.repaint()          # draw it

   def hide(self):
      """It hides the image."""
      
      self.display.setVisible(False)
예제 #37
0
def click(event):
    print li.getSelectedIndex()

def add(event):
    listModel.addElement("7")

def change(event):
    listModel.clear()
    [listModel.addElement(e) for e in b]

liste = [1,2,3,4]
b = [6,8,9]
f = JFrame("list")
frame2 = JFrame("frame2")

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)


p = JPanel()
grid = GridLayout(3,1)
p.setLayout(grid)

button = JButton("selected?", actionPerformed=click)
addButton = JButton("add 7", actionPerformed=add)
remButton = JButton("remove element", actionPerformed=rem)
chButton = JButton("Change to list B", actionPerformed=change)



listModel = DefaultListModel()
[listModel.addElement(e) for e in liste]
예제 #38
0
파일: twitfriends.py 프로젝트: jython/book
class JyTwitter(object):
    def __init__(self):
        self.frame = JFrame("Jython Twitter")
        self.frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
 
        self.loginPanel = JPanel(GridLayout(0,2))
        self.frame.add(self.loginPanel)

        self.usernameField = JTextField('',15)
        self.loginPanel.add(JLabel("username:"******"password:"******"Please Log in")
        self.loginPanel.add(self.message)

        self.frame.pack()
        self.frame.visible = True

    def login(self,event):
        self.message.text = "Attempting to Log in..."
        self.frame.show()
        username = self.usernameField.text
        try:
            self.api = twitter.Api(username, self.passwordField.text)
            self.timeline(username)
            self.loginPanel.visible = False
            self.message.text = "Logged in"
        except:
            self.message.text = "Log in failed."
            raise
        self.frame.size = 400,800
        self.frame.show()

    def timeline(self, username):
        timeline = self.api.GetFriendsTimeline(username)
        self.resultPanel = JPanel()
        self.resultPanel.layout = BoxLayout(self.resultPanel, BoxLayout.Y_AXIS)
        for s in timeline:
            self.showTweet(s)

        scrollpane = JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                                 JScrollPane.HORIZONTAL_SCROLLBAR_NEVER)
        scrollpane.preferredSize = 400, 800
        scrollpane.viewport.view = self.resultPanel

        self.frame.add(scrollpane)

    def showTweet(self, status):
        user = status.user
        p = JPanel()

        # image grabbing seems very expensive, good place for a callback?
        p.add(JLabel(ImageIcon(URL(user.profile_image_url))))

        p.add(JTextArea(text = status.text,
                        editable = False,
                        wrapStyleWord = True,
                        lineWrap = True,
                        alignmentX = Component.LEFT_ALIGNMENT,
                        size = (300, 1)
             ))
        self.resultPanel.add(p)
class BurpExtender(IBurpExtender, IContextMenuFactory):
    # Implement IBurpExtender
    def registerExtenderCallbacks(self, callbacks):

        self.printHeader()

        # Set extension name
        callbacks.setExtensionName("Directory Listing Parser for Burp Suite")

        # Callbacks object
        self._callbacks = callbacks

        # Helpers object
        self._helpers = callbacks.getHelpers()

        # Register a factory for custom context menu items
        callbacks.registerContextMenuFactory(self)

        return

    # Create a menu item if the appropriate section of the UI is selected
    def createMenuItems(self, invocation):
        menu = []

        # Which part of the interface the user selects
        ctx = invocation.getInvocationContext()

        # Message Viewer Req/Res, Site Map Table, and Proxy History will show menu item if selected by the user
        if ctx == 2 or ctx == 3 or  ctx == 4 or ctx == 5 or ctx == 6:
            menu.append(JMenuItem("Import Directory Listing", None, actionPerformed=lambda x, inv=invocation: self.openGUI(inv)))

        return menu if menu else None

    # Create and place GUI components on JFrame
    def openGUI(self, invocation):
        try:
            # Get values from request or response the extension is invoked from and prepopulate GUI values
            invMessage = invocation.getSelectedMessages()
            message = invMessage[0]
            originalHttpService = message.getHttpService()
            self.originalMsgProtocol = originalHttpService.getProtocol()
            self.originalMsgHost = originalHttpService.getHost()
            self.originalMsgPort = originalHttpService.getPort()
        except:
            self.originalMsgProtocol = ''
            self.originalMsgHost = ''
            self.originalMsgPort = ''

        try:
            self.cookies = self._callbacks.getCookieJarContents()
            self.cookie = ''
        except:
            pass

        self.SSL = 'http://'
        self.listType = ''
        self.parsedList = []

        # Set up main window (JFrame)
        self.window = JFrame("Directory Listing Parser for Burp Suite", preferredSize=(600, 475), windowClosing=self.closeUI)
        self.window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
        emptyBorder = BorderFactory.createEmptyBorder(10, 10, 10, 10)
        self.window.contentPane.setBorder(emptyBorder)
        self.window.contentPane.layout = BorderLayout()

        # Main window title placed at the top of the main window with an invisible bottom border
        titlePanel = JPanel()
        titleBorder = BorderFactory.createEmptyBorder(0, 0, 10, 0)
        title = JLabel("Directory Listing Parser for Burp Suite", JLabel.CENTER)
        title.setBorder(titleBorder)
        title.setFont(Font("Default", Font.PLAIN, 18))
        titlePanel.add(title)
        self.window.contentPane.add("North", titlePanel)

        # Left panel for user input, consisting of hostname, directory prefix, ssl, port, type of listing, and file
        self.leftPanel = JPanel()
        self.leftPanel.layout = GridLayout(14, 1, 3, 3)
        hostnameLabel = JLabel("Hostname:")

        if self.originalMsgHost:
            self.hostnameTextField = JTextField(self.originalMsgHost.rstrip())
        else:
            self.hostnameTextField = JTextField('Hostname')

        dirPrefixLabel = JLabel("Full Directory Prefix (Windows):")
        self.dirPrefixField = JTextField('C:\\var\www\\')
        
        sslLabel = JLabel("SSL:")
        self.radioBtnSslEnabled = JRadioButton('Enabled (https)', actionPerformed=self.radioSsl)
        self.radioBtnSslDisabled = JRadioButton('Disabled (http)', actionPerformed=self.radioSsl)
        sslButtonGroup = ButtonGroup()
        sslButtonGroup.add(self.radioBtnSslEnabled)
        sslButtonGroup.add(self.radioBtnSslDisabled)
        
        if self.originalMsgProtocol == "https":
            self.radioBtnSslEnabled.setSelected(True)
        else:
            self.radioBtnSslDisabled.setSelected(True)
        
        portLabel = JLabel("Port:")

        if self.originalMsgPort:
            self.portTextField = JTextField(str(self.originalMsgPort).rstrip())
        else:
            self.portTextField = JTextField('80')

        osLabel = JLabel("Type of File Listing:")
        self.types = ('Windows \'dir /s\'', 'Linux \'ls -lR\'', 'Linux \'ls -R\'')
        self.comboListingType = JComboBox(self.types)
        uploadLabel = JLabel("Directory Listing File:")
        self.uploadTextField = JTextField('')
        uploadButton = JButton('Choose File', actionPerformed=self.chooseFile)

        self.leftPanel.add(hostnameLabel)
        self.leftPanel.add(self.hostnameTextField)
        self.leftPanel.add(dirPrefixLabel)
        self.leftPanel.add(self.dirPrefixField)
        self.leftPanel.add(sslLabel)
        self.leftPanel.add(self.radioBtnSslEnabled)
        self.leftPanel.add(self.radioBtnSslDisabled)
        self.leftPanel.add(portLabel)
        self.leftPanel.add(self.portTextField)
        self.leftPanel.add(osLabel)
        self.leftPanel.add(self.comboListingType)
        self.leftPanel.add(uploadLabel)
        self.leftPanel.add(self.uploadTextField)
        self.leftPanel.add(uploadButton)

        # Right panel consisting of a text area for the URL list
        self.UrlPanelLabel = JLabel("URL List:")
        self.textArea = JTextArea()
        self.textArea.setEditable(True)
        self.textArea.setFont(Font("Default", Font.PLAIN, 14))
        if self.cookies:
            self.textArea.append('Cookies Found:\n')
            for cookie in self.cookies:
                if cookie.getDomain() in self.originalMsgHost:
                    self.cookie += cookie.getName() + '=' + cookie.getValue() + '; '
                    self.textArea.append(cookie.getName() + '=' + cookie.getValue() + '\n')
        scrollArea = JScrollPane(self.textArea)
        scrollArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
        scrollArea.setPreferredSize(Dimension(400, 200))
        self.rightPanel = JPanel()
        self.rightPanel.setLayout(BorderLayout(3, 3))
        self.rightPanel.add(self.UrlPanelLabel, BorderLayout.NORTH)
        self.rightPanel.add(scrollArea, BorderLayout.CENTER)
        
        # Panel for the generate URL list and import URL list buttons
        generatePanel = JPanel()
        generatePanel.layout = BorderLayout(3, 3)
        generateButton = JButton('Generate URL List', actionPerformed=self.generateUrlList)
        importButton = JButton('Import URL List to Burp Site Map', actionPerformed=self.confirmImport)
        generatePanel.add("North", generateButton)
        generatePanel.add("South", importButton)
        self.rightPanel.add("South", generatePanel)

        # Add the two main panels to the left and right sides
        self.window.contentPane.add("East", self.rightPanel)
        self.window.contentPane.add("West", self.leftPanel)

        # Create a panel to be used for the file chooser window
        self.uploadPanel = JPanel()
        
        self.window.pack()
        self.window.show()

    # JFileChooser and showDialog for the user to specify their directory listing input file
    def chooseFile(self, event):
        chooseFile = JFileChooser()
        filter = FileNameExtensionFilter("c files", ["c"])
        chooseFile.addChoosableFileFilter(filter)
        chooseFile.showDialog(self.uploadPanel, "Choose File")
        chosenFile = chooseFile.getSelectedFile()
        self.uploadTextField.text = str(chosenFile)

    # Set whether https is enabled.  Default is disabled (http)
    def radioSsl(self, event):
        if self.radioBtnSslEnabled.isSelected():
            self.SSL = 'https://'
        else:
            self.SSL = 'http://'

    # Create a parser object and pass the user's specified options.  Retrieve the results and print them to a text area
    def generateUrlList(self, event):
        fileListingType = self.comboListingType.selectedIndex
        self.listType = self.types[fileListingType]
        urlsMade = 0
        if os.path.isfile(self.uploadTextField.text):
            parser = ListingParser()
            parser.parse(self.hostnameTextField.getText(), self.dirPrefixField.getText().rstrip(), self.SSL, self.portTextField.getText(), self.listType, self.uploadTextField.getText())
            self.parsedList = parser.returnList()
            self.textArea.setText('')
            for item in self.parsedList:
                self.textArea.append(item + '\n')

            urlsMade = str(len(self.parsedList))
            if self.parsedList and urlsMade:
                self.textArea.append('\n' + 'Total Directories Found: ' + str(parser.directoryCount))
                self.textArea.append('\n' + 'Total URLs Created: ' + urlsMade)
            else:
                self.textArea.append('Error occurred during parsing.\n')
                self.textArea.append('Please make sure the directory listing is a valid format and all input is correct.\n')
                self.textArea.append('E-mail [email protected] with errors or for further help.')
        else:
            JOptionPane.showMessageDialog(None, 'ERROR: File is not valid file or not found!')

    def closeUI(self, event):
        self.window.setVisible(False)
        self.window.dispose()

    # This is initiated by the user selecting the 'import to burp' button.  Checks each generated URL for a valid response and adds it to the site map
    def importList(self):
        if self.parsedList:
            urlsAdded = 0
            # Loop through each URL and check the response.  If the response code is less than 404, add to site map
            for item in self.parsedList:
                # Pass exception if urlopen returns an http error if the URL is not reachable
                try:
                    code = urlopen(item).code
                    if code < 404:
                        javaURL = URL(item)
                        newRequest = self._helpers.buildHttpRequest(javaURL)
                        stringNewRequest = self._helpers.bytesToString(newRequest).rstrip()
                        if self.cookie:
                            stringNewRequest += '\nCookie: ' + self.cookie.rstrip('; ') + '\r\n\r\n'
                            requestResponse = self._callbacks.makeHttpRequest(self._helpers.buildHttpService(str(javaURL.getHost()), int(javaURL.getPort()), javaURL.getProtocol() == "https"), stringNewRequest)
                        else:
                            requestResponse = self._callbacks.makeHttpRequest(self._helpers.buildHttpService(str(javaURL.getHost()), int(javaURL.getPort()), javaURL.getProtocol() == "https"), newRequest)
                        self._callbacks.addToSiteMap(requestResponse)
                        urlsAdded += 1
                except Exception, e:
                    print e
                    pass
            JOptionPane.showMessageDialog(None, str(urlsAdded) + " URL(s) added to Burp site map.")
        else:
예제 #40
0
'''
Created on Sep 9, 2013

@author: ccole
'''

from javax.swing import JFrame
from src import MainPanel

f = JFrame('Python Image Game')
f.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)
f.setSize(300, 300)
f.setLocationRelativeTo(None)
f.setVisible(True)

f.add(MainPanel())
def doall(locations, fileobs,filerun1,filerun2,stime,etime,imageDir='d:/temp',weights=None,filter_type="AVE",normalize=False):
    obs=HecDss.open(fileobs,True)
    obs.setTimeWindow(stime,etime)
    run1=HecDss.open(filerun1,True)
    run1.setTimeWindow(stime,etime)
    if filerun2 != None:
        run2=HecDss.open(filerun2,True)
        run2.setTimeWindow(stime,etime)
    else:
        run2=None
    rms1=0
    rms1_min,rms1_max=0,0
    rms2=0
    rms2_min,rms2_max=0,0
    rmsmap={}
    #run2=None
    sumwts=0
    average_interval=None;
    for l in locations:
        data1=get_matching(obs,'A=%s C=%s E=15MIN'%(l,type))
        if data1 == None:
            data1=get_matching(obs,'A=%s C=%s E=1DAY'%(l,type))
        if data1 == None:
            data1=get_matching(obs,'A=%s C=%s E=IR-DAY'%(l,type))
        if data1 == None:
            data1=get_matching(obs,'A=%s C=%s E=1HOUR'%(l,type))
        drun1=get_matching(run1,'B=%s C=%s'%(l,type))
        if run2 != None:
            drun2=get_matching(run2, 'B=%s C=%s'%(l,type))
        else:
            drun2=None
        avg_intvl="1DAY"
        if data1 != None:
            if average_interval != None:
                dobsd=TimeSeriesMath(data1).transformTimeSeries(average_interval, None, filter_type, 0)
            else:
                dobsd=TimeSeriesMath(data1)
            if normalize:
                dobsd=dobsd.divide(TimeSeriesMath(data1).mean())
            dobsm=TimeSeriesMath(data1).transformTimeSeries(avg_intvl, None, filter_type, 0)
            dobsm_max=TimeSeriesMath(data1).transformTimeSeries(avg_intvl, None, "MAX", 0)
            dobsm_max.data.fullName=dobsm_max.data.fullName+"MAX"
            dobsm_min=TimeSeriesMath(data1).transformTimeSeries(avg_intvl, None, "MIN", 0)
            dobsm_min.data.fullName=dobsm_min.data.fullName+"MIN"
            if normalize:
                dobsm=dobsm.divide(TimeSeriesMath(data1).mean())
        if drun1==None:
            continue;
        else:
            if average_interval != None:
                drun1d=TimeSeriesMath(drun1).transformTimeSeries(average_interval, None, filter_type, 0)
            else:
                drun1d=TimeSeriesMath(drun1)
            if normalize:
                drun1d=drun1d.divide(TimeSeriesMath(drun1).mean())
            if drun2 != None:
                if average_interval != None:
                    drun2d=TimeSeriesMath(drun2).transformTimeSeries(average_interval, None, filter_type, 0)
                else:
                    drun2d=TimeSeriesMath(drun2)
                if normalize:
                    drun2d=drun2d.divide(TimeSeriesMath(drun2).mean())
            drun1m=TimeSeriesMath(drun1).transformTimeSeries(avg_intvl, None, filter_type, 0)
            drun1m_max=TimeSeriesMath(drun1).transformTimeSeries(avg_intvl, None, "MAX", 0)
            drun1m_min=TimeSeriesMath(drun1).transformTimeSeries(avg_intvl, None, "MIN", 0)
            if normalize:
                drun1m=drun1m.divide(TimeSeriesMath(drun1).mean())
            if drun2 != None:
                drun2m=TimeSeriesMath(drun2).transformTimeSeries(avg_intvl, None, filter_type, 0)
                drun2m_max=TimeSeriesMath(drun2).transformTimeSeries(avg_intvl, None, "MAX", 0)
                drun2m_min=TimeSeriesMath(drun2).transformTimeSeries(avg_intvl, None, "MIN", 0)
                if normalize:
                    drun2m=drun2m.divide(TimeSeriesMath(drun2).mean())
            else:
                drun2m=None
        if weights != None:
            sumwts=sumwts+weights[l]
            lrms1 = calculate_rms(drun1m.data, dobsm.data)*weights[l]
            lrms1_min=calculate_rms(drun1m_min.data,dobsm_min.data)*weights[l]
            lrms1_max=calculate_rms(drun1m_max.data,dobsm_max.data)*weights[l]
            rms1=rms1+lrms1
            rms1_min=rms1_min+lrms1_min
            rms1_max=rms1_max+lrms1_max
            lrms2 = calculate_rms(drun2m.data,dobsm.data)*weights[l]
            lrms2_min=calculate_rms(drun2m_min.data,dobsm_min.data)*weights[l]
            lrms2_max=calculate_rms(drun2m_max.data,dobsm_max.data)*weights[l]
            rmsmap[l] = lrms1,lrms2,lrms1_min,lrms2_min,lrms1_max,lrms2_max
            rms2=rms2+lrms2
            rms2_min=rms2_min+lrms2_min
            rms2_max=rms2_max+lrms2_max
        plotd = newPlot("Hist vs New Geom [%s]"%l)
        if data1 != None:
            plotd.addData(dobsd.data)
        plotd.addData(drun1d.data)
        if drun2 != None:
            plotd.addData(drun2d.data)
        plotd.showPlot()
        legend_label = plotd.getLegendLabel(drun1d.data)
        legend_label.setText(legend_label.getText()+" ["+str(int(lrms1*100)/100.)+","+str(int(lrms1_min*100)/100.)+","+str(int(lrms1_max*100)/100.)+"]")
        legend_label = plotd.getLegendLabel(drun2d.data)
        legend_label.setText(legend_label.getText()+" ["+str(int(lrms2*100)/100.)+","+str(int(lrms2_min*100)/100.)+","+str(int(lrms2_max*100)/100.)+"]")
        plotd.setVisible(False)
        xaxis=plotd.getViewport(0).getAxis("x1")
        vmin =xaxis.getViewMin()+261500. # hardwired to around july 1, 2008
        xaxis.setViewLimits(vmin,vmin+10000.)
        if data1 != None:
            pline = plotd.getCurve(dobsd.data)
            pline.setLineVisible(1)
            pline.setLineColor("blue")
            pline.setSymbolType(Symbol.SYMBOL_CIRCLE)
            pline.setSymbolsVisible(0)
            pline.setSymbolSize(3)
            pline.setSymbolSkipCount(0)
            pline.setSymbolFillColor(pline.getLineColorString())
            pline.setSymbolLineColor(pline.getLineColorString())
            g2dPanel = plotd.getPlotpanel()
            g2dPanel.revalidate();
            g2dPanel.paintGfx();
        plotm = newPlot("Hist vs New Geom Monthly [%s]"%l)
        plotm.setSize(1800,1200)
        if data1 != None:
            plotm.addData(dobsm.data)
           #plotm.addData(dobsm_max.data)
            #plotm.addData(dobsm_min.data)
        plotm.addData(drun1m.data)
        #plotm.addData(drun1m_max.data)
        #plotm.addData(drun1m_min.data)
        if drun2 != None:
            plotm.addData(drun2m.data)
            #plotm.addData(drun2m_max.data)
            #plotm.addData(drun2m_min.data)
        plotm.showPlot()
        if data1 != None:
            pline = plotm.getCurve(dobsm.data)
            pline.setLineVisible(1)
            pline.setLineColor("blue")
            pline.setSymbolType(Symbol.SYMBOL_CIRCLE)
            pline.setSymbolsVisible(0)
            pline.setSymbolSize(3)
            pline.setSymbolSkipCount(0)
            pline.setSymbolFillColor(pline.getLineColorString())
            pline.setSymbolLineColor(pline.getLineColorString())
        plotm.setVisible(False)
        if data1 != None:
            plots=do_regression_plots(dobsm,drun1m,drun2m)
            if plots != None:
                spanel = plots.getPlotpanel()
                removeToolbar(spanel)
        mpanel = plotm.getPlotpanel()
        removeToolbar(mpanel)
        dpanel = plotd.getPlotpanel()
        removeToolbar(dpanel)
        from javax.swing import JPanel,JFrame
        from java.awt import GridBagLayout, GridBagConstraints
        mainPanel = JPanel()
        mainPanel.setLayout(GridBagLayout())
        c=GridBagConstraints()
        c.fill=c.BOTH
        c.weightx,c.weighty=0.5,1
        c.gridx,c.gridy,c.gridwidth,c.gridheight=0,0,10,4
        if data1 != None:
            if plots != None:
                pass
                #mainPanel.add(spanel,c)
        c.gridx,c.gridy,c.gridwidth,c.gridheight=0,0,10,4
        c.weightx,c.weighty=1,1
        mainPanel.add(mpanel,c)
        c.gridx,c.gridy,c.gridwidth,c.gridheight=0,4,10,6
        mainPanel.add(dpanel,c)
        fr=JFrame()
        fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        fr.getContentPane().add(mainPanel)
        fr.setSize(1100,850);
        fr.show();
        mainPanel.setSize(1100,850);
        mainPanel.setBackground(Color.WHITE);
        #import time; time.sleep(5)
        saveToPNG(mainPanel,imageDir+l+".png")
    if weights != None:
        rms1=(rms1+rms1_min+rms1_max)/sumwts
        rms2=(rms2+rms2_min+rms2_max)/sumwts
        print 'RMS Run 1: %f'%rms1
        print 'RMS Run 2: %f'%rms2
        for loc in rmsmap.keys():
            print loc, rmsmap[loc] 
예제 #42
0
def makeEditorFrame(ldPath, compiler):
    mb = JMenuBar()
    
    file = JMenu("File")
    edit = JMenu("Edit")
    run = JMenu("Run")
    
    newMenu = menu_with_accelerator("New",(KeyEvent.VK_N,ActionEvent.META_MASK))
    file.add(newMenu)
           
    open = menu_with_accelerator("Open",(KeyEvent.VK_O,ActionEvent.META_MASK))
    file.add(open)
    
    save = menu_with_accelerator("Save",(KeyEvent.VK_S,ActionEvent.META_MASK))
    file.add(save)
    
    file.add(JSeparator());
    
    resetPipe = menu_with_accelerator("Reset Pipeline",(KeyEvent.VK_N,ActionEvent.META_MASK | ActionEvent.SHIFT_MASK))
    file.add(resetPipe)
            
    openPipe = menu_with_accelerator("Open Pipeline",(KeyEvent.VK_O,ActionEvent.META_MASK | ActionEvent.SHIFT_MASK))
    file.add(openPipe)
            
    compile = menu_with_accelerator("Compile",(KeyEvent.VK_ENTER, ActionEvent.META_MASK))
    run.add(compile)
            
    mb.add(file)
    mb.add(edit)
    mb.add(run)
            
    f = JFrame("SFGP Shader Editor")
    f.setJMenuBar(mb)
    c = f.getContentPane()
    c.setLayout(BorderLayout())
    editor = GLSLEditorPane("",ldPath,compiler)
    c.add(editor, BorderLayout.CENTER)
    c.doLayout()
    
    f.setSize(1000, 700);
    f.setVisible(True);
    f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            
    class EditorActionListener(ActionListener):
        def makeRelay(srcObj):
            return (lambda e: editor.actionPerformed(ActionEvent(srcObj, e.getID(), e.getActionCommand())))
        editorActions = {
            save : (lambda e: editor.saveCurrent()),
            compile : (lambda e: editor.compileCurrent()),
            open : makeRelay(editor.openShader),
            newMenu : makeRelay(editor.newShader),
            openPipe : makeRelay(editor.openPipeline),
            resetPipe : makeRelay(editor.resetPipeline)
                        }
        def actionPerformed(self, e):
            editorActions = EditorActionListener.editorActions
            evtSrc = e.getSource()
            if evtSrc in editorActions:
                editorActions[evtSrc](e)
            else:
                raise IllegalStateException("Imaginary menu item registered an ActionEvent: " + evtSrc)
    menuListener = EditorActionListener()
    compile.addActionListener(menuListener);
    newMenu.addActionListener(menuListener);
    open.addActionListener(menuListener);
    save.addActionListener(menuListener);
    resetPipe.addActionListener(menuListener);
    openPipe.addActionListener(menuListener);
예제 #43
0
class Window:
    def __init__(self, text):
        self.frame = JFrame()
        self.frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
        self.frame.getContentPane().setLayout(GridLayout(1, 1))
        self.settings = Settings()
        self.text = text
        self + text
        m = JMenuBar()
        self.menubar = m
        self.filemenu = self.menu()
        m.add(self.filemenu)
        self.frame.setJMenuBar(self.menubar)
        self.frame.setSize(1000, 600)
        self.frame.setVisible(1)

    def menu(self):
        f = JMenu("File")

        o = JMenuItem("Copy")
        o.addActionListener(ActionEventListener(self.opencopy))
        self.open = o
        f.add(o)

        o = JMenuItem("New")
        o.addActionListener(ActionEventListener(self.new))
        self.open = o
        f.add(o)

        o = JMenuItem("Open")
        o.addActionListener(ActionEventListener(self.opendialog))
        self.open = o
        f.add(o)

        o = JMenuItem("Save")
        o.addActionListener(ActionEventListener(self.save))
        self.open = o
        f.add(o)

        o = JMenuItem("Save As")
        o.addActionListener(ActionEventListener(self.saveas))
        self.open = o
        f.add(o)

        return f

    def __add__(self, c):
        self.frame.getContentPane().add(c)
        return self

    def opencopy(self, e):
        c = None
        if "lastcopy" in self.settings.keys():
            c = JFileChooser(self.settings["lastcopy"])
        else:
            c = JFileChooser()

        r = c.showOpenDialog(self.frame)

        if r == JFileChooser.APPROVE_OPTION:
            f = c.getSelectedFile()
            self.f = f
            s = f.getAbsolutePath()

            self.settings["lastcopy"] = f.getParent()
            self.settings.save()

            #            i = FileInputStream(s)
            self.text.setcopy(s)

    def opendialog(self, e):
        c = None
        if "lastdir" in self.settings.keys():
            c = JFileChooser(self.settings["lastdir"])
        else:
            c = JFileChooser()

        r = c.showOpenDialog(self.frame)

        if r == JFileChooser.APPROVE_OPTION:
            f = c.getSelectedFile()
            self.f = f
            s = f.getAbsolutePath()

            self.settings["lastdir"] = f.getParent()
            self.settings.save()

            i = FileInputStream(s)
            self.text.setinput(i)
            self.frame.pack()
            self.frame.setSize(800, 500)

    def new(self, e):
        self.text.createnew()
        self.frame.pack()
        self.frame.setSize(800, 500)

    def save(self, e):
        o = FileOutputStream(self.f)
        self.text.setoutput(o)

    def saveas(self, e):
        c = None
        if "lastdir" in self.settings.keys():
            c = JFileChooser(self.settings["lastdir"])
        else:
            c = JFileChooser()

        r = c.showOpenDialog(self.frame)

        if r == JFileChooser.APPROVE_OPTION:
            f = c.getSelectedFile()
            self.f = f
            s = f.getAbsolutePath()

            self.settings["lastdir"] = f.getParent()
            self.settings.save()

            o = FileOutputStream(s)
            self.text.setoutput(o)
class FilamentGame_ModelEditor(EditorExtension, JPanel, MouseListener, MouseMotionListener):
    def getExtensionName(self):
        return "Filament Model Tool"

    def initializeExtension(self, manager):
        self.manager = manager
        self.frame = JFrame(self.getExtensionName())
        self.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

        # instance setup
        self.state = State.NOTHING
        self.entity = Entity()

        # Setupgui
        self.setupGui()
        self.addMouseListener(self)
        self.addMouseMotionListener(self)
        self.setPreferredSize(Dimension(500, 500))
        self.frame.pack()
        self.frame.setResizable(False)
        self.frame.setVisible(True)
        self.cameraPos = [0, 0]

    def setupGui(self):

        cPanel = JPanel()

        # Draw Shape Button
        self.drawShapeButton = JButton("Draw", actionPerformed=self.drawShapeButtonAction)
        cPanel.add(self.drawShapeButton)

        drawShapeButton = JButton("Clear", actionPerformed=self.clearShapeButtonAction)
        cPanel.add(drawShapeButton)

        # Label
        self.infoLabel = JLabel("Shape Editor")
        cPanel.add(self.infoLabel)

        self.frame.add(BorderLayout.NORTH, cPanel)
        self.frame.add(BorderLayout.CENTER, self)

    def entitySelected(self, entity):
        self.entity = entity
        self.repaint()

    def sceneChanged(self, scene):
        self.scene = scene
        self.entity = Entity()
        self.repaint()

    # BUTTONS
    def drawShapeButtonAction(self, e):
        if self.state == State.NOTHING:
            self.state = State.DRAW_SHAPE
            self.infoLabel.setText("Click to Draw Shape")
            self.drawShapeButton.setText("Stop Drawing")
        elif self.state != State.NOTHING:
            self.state = State.NOTHING
            self.infoLabel.setText("")
            self.drawShapeButton.setText("Draw")
        self.revalidate()

    def clearShapeButtonAction(self, e):
        if self.state != State.NOTHING:
            self.drawShapeButtonAction(e)
        self.state = State.NOTHING
        polygon = self.entity.getModel().pol
        polygon.reset()
        self.repaint()

    # DRAWING
    def paintComponent(self, g):
        self.super__paintComponent(g)
        g.scale(1, -1)
        g.translate(-self.cameraPos[0] + self.getWidth() / 2, -self.cameraPos[1] - self.getHeight() / 2)
        self.drawGrid(g)
        polygon = self.entity.getModel().pol
        x = []
        y = []
        g.setColor(Color.BLACK)
        for i in range(polygon.npoints):
            x = x + [int(polygon.xpoints[i])]
            y = y + [int(polygon.ypoints[i])]
            g.drawRect(int(polygon.xpoints[i]) - 2, int(polygon.ypoints[i]) - 2, 4, 4)
        g.fillPolygon(x, y, polygon.npoints)

    def drawGrid(self, g):
        g.setColor(Color.RED)
        g.drawLine(50, 0, -50, 0)
        g.drawLine(0, 50, 0, -50)

    # MOUSE LISTENER
    def mouseCicked(self, e):
        return

    def mouseEntered(self, e):
        return

    def mouseExited(self, e):
        return

    def mousePressed(self, e):
        self.anchor = e.getPoint()
        self.oldCamPos = self.cameraPos

    def findMousePos(self, p):
        w = self.getWidth()
        h = self.getHeight()
        cX = self.cameraPos[0]
        cY = self.cameraPos[1]

        y = h - p.y

        x = p.x - w / 2 + cX
        y = y - h / 2 + cY

        return [x, y]

    def mouseReleased(self, e):
        if self.state == State.DRAW_SHAPE:
            try:
                p = self.findMousePos(e.getPoint())
                self.entity.getModel().pol.addPoint(p[0], p[1])
            except IllegalPathStateException:
                print "Error Building Polygon path!"
        self.repaint()

    def mouseMoved(self, e):
        return

    def mouseDragged(self, e):
        if self.state == State.NOTHING:
            self.cameraPos = [
                self.oldCamPos[0] + self.anchor.x - e.getX(),
                self.oldCamPos[1] - self.anchor.y + e.getY(),
            ]
            print str(self.cameraPos)
            self.repaint()

    def update(self, delta):
        return
class DemultiplexGUI(Runnable):

    global SampleSheet
    
    def __init__(self):

        self.f = JFrame("Demultiplex the data")
        self.f.setSize(1250, 1000)
        self.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        
        #Progress Monitor
        self.pm=JProgressBar(100,100)
        
        #Lane Area
        self.LaneAre=JPanel()
        self.lane1=JCheckBox("Lane 1", True)
        self.lane2=JCheckBox("Lane 2", True)
        self.lane3=JCheckBox("Lane 3", True)
        self.lane4=JCheckBox("Lane 4", True)
        self.lane5=JCheckBox("Lane 5", True)
        self.lane6=JCheckBox("Lane 6", True)
        self.lane7=JCheckBox("Lane 7", True)
        self.lane8=JCheckBox("Lane 8", True)
        self.LaneAre.add(self.lane1)
        self.LaneAre.add(self.lane2)
        self.LaneAre.add(self.lane3)
        self.LaneAre.add(self.lane4)
        self.LaneAre.add(self.lane5)
        self.LaneAre.add(self.lane6)
        self.LaneAre.add(self.lane7)
        self.LaneAre.add(self.lane8)
        
        self.txtArea = JPanel(GridLayout(15,0))
        #self.txtArea.setPreferredSize(Dimension(150, 150))
        self.textAreaForSheet = JTextField(30)
        self.textAreaInputForFolder = JTextField(30)
        self.textAreaOutPutFolder= JTextField(30)
        self.txtArea.add(self.textAreaForSheet)
        self.txtArea.add(self.textAreaInputForFolder)
        self.txtArea.add(self.textAreaOutPutFolder)
        self.txtArea.add(self.LaneAre)
        
        self.buttonArea = JPanel(GridLayout(15,0))
        #self.buttonArea.setPreferredSize(Dimension(150, 150))
        self.sampleSheetBtn = JButton("SampleSheet", actionPerformed=self.onClickSample)
        self.runOutPutFolder = JButton("RUN Folder",actionPerformed=self.onClickRun)
        self.DemultiplexOutPutFolder = JButton("Output Folder",actionPerformed=self.onClickOut)
        self.buttonArea.add(self.sampleSheetBtn)
        self.buttonArea.add(self.runOutPutFolder)
        self.buttonArea.add(self.DemultiplexOutPutFolder)
        
        self.CheckBox = JPanel(GridLayout(15,0))
        #self.buttonArea.setPreferredSize(Dimension(150, 150))
        self.Iter1 = JCheckBox("01_0M_NY", True,)
        self.Iter2 = JCheckBox("02_0M_N", True,)
        self.Iter3 = JCheckBox("03_1M_NY", True,)
        self.Iter4 = JCheckBox("04_1M_N", True,)
        
        self.CheckBox.add(self.Iter1)
        self.CheckBox.add(self.Iter2)
        self.CheckBox.add(self.Iter3)
        self.CheckBox.add(self.Iter4)

        self.ExecutePanel = JPanel()
        self.console=JTextArea(20,100)
        
        self.sp = JScrollPane(self.console);
        self.RunBtn = JButton("Demultiplex",actionPerformed= self.performDemultiplex)
        self.CanBtn = JButton("Cancel",actionPerformed= self.CancelJob)

        self.ExecutePanel.add(self.RunBtn)
        self.ExecutePanel.add(self.CanBtn)
        self.ExecutePanel.add(self.sp, BorderLayout.CENTER)

        self.f.add(self.txtArea, BorderLayout.CENTER)
        self.f.add(self.buttonArea, BorderLayout.WEST)
        self.f.add(self.CheckBox, BorderLayout.EAST)
        self.f.add(self.ExecutePanel, BorderLayout.NORTH)
        self.f.add(self.pm,BorderLayout.SOUTH)
        
    def run(self):
        self.f.setVisible(True)

    def onClickRun(self,event=""):
        self.DirName= FolderChooser(self.f)
        self.textAreaInputForFolder.setText(str(self.DirName))

    def onClickOut(self,event=""):
        self.OutDirName= FolderChooser(self.f)
        self.textAreaOutPutFolder.setText(str(self.OutDirName))
    
    def onClickSample(self,event):
        self.sampleSheet=FileChooser(self.f)
        self.textAreaForSheet.setText(str(self.sampleSheet))
        
    def performDemultiplex(self,event):
        NumberOfIterations=[self.Iter1.selected,self.Iter2.selected,self.Iter3.selected,self.Iter4.selected]
        LaneNumber=[self.lane1.selected,self.lane2.selected,self.lane3.selected,self.lane4.selected,self.lane5.selected,self.lane6.selected,self.lane7.selected,self.lane8.selected]
        selectedLanes = [str(i+1) for i, x in enumerate(LaneNumber) if x==True]
        lanes=','.join(selectedLanes)
        print LaneNumber,selectedLanes,lanes, lanes
        self.task = ET.Task(self,NumberOfIterations,str(self.sampleSheet),str(self.DirName),str(self.OutDirName), lanes)
        self.task.execute()

    def CancelJob(self,event):
        self.task.cancel(True)
예제 #46
0
def createStudentFeeForm(stFeeObj):
    
    global tfStudentId
    global tfStudentName
    global tfTotalAmount
    global tfPaidAmount
    global tfRemainingAmount 
    global frame
    
    frame = JFrame("Student Fee Form ")
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    frame.setSize(500,500)
    frame.setLocation(200,200)
    frame.setLayout(None)
    frame.setVisible(True)
    
    panel = JPanel()
    panel.setSize(500,500)
    panel.setLocation(0,0)
    panel.setLayout(None)
    panel.setVisible(True)
    panel.setBackground(Color.LIGHT_GRAY)
    
    heading = JLabel("STUDENT FEE")
    heading.setBounds(200,30,150,40)

    lbStudentId = JLabel(" Student id")
    lbStudentName = JLabel(" student name")
    lbTotalAmount = JLabel("Total Amount ")
    lbPaidAmount = JLabel("Paid Amount")
    lbRemainingAmount = JLabel("Remaining amount")
    
    studentId =getattr(stFeeObj,'studentId')
    studentName =getattr(stFeeObj,'studentName')
    totalAmount =getattr(stFeeObj,'totalAmount')
    paidAmount =getattr(stFeeObj,'paidAmount')
    remainingAmount =getattr(stFeeObj,'remainingAmount')
    
    
    tfStudentId = JTextField(str(studentId))
    tfStudentName = JTextField(str(studentName))
    tfTotalAmount = JTextField(str(totalAmount))
    tfPaidAmount = JTextField(str(paidAmount))
    tfRemainingAmount = JTextField(str(remainingAmount))
    
    tfStudentId.setEditable(False)
    tfStudentName.setEditable(False)
    tfTotalAmount.setEditable(False)
    tfRemainingAmount.setEditable(False)
    
    lbStudentId.setBounds(70,100,130,30)
    lbStudentName.setBounds(70,150,130,30)
    lbTotalAmount.setBounds(70,200,130,30)
    lbPaidAmount.setBounds(70,250,130,30)
    lbRemainingAmount.setBounds(70,300,130,30)
    
    tfStudentId.setBounds(220,100,130,30)
    tfStudentName.setBounds(220,150,130,30)
    tfTotalAmount.setBounds(220,200,130,30)
    tfPaidAmount.setBounds(220,250,130,30)
    tfRemainingAmount.setBounds(220,300,130,30)
    
    btnPay = JButton("Paid",actionPerformed=clickPay)
    btnPay.setBounds(350,410,100,40)
    
    btnCancel = JButton("Cancel",actionPerformed=clickbtnCancelForm)
    btnCancel.setBounds(50,410,100,40)
    
    panel.add(heading)
    panel.add(lbStudentId)
    panel.add(lbStudentName)
    panel.add(lbTotalAmount)
    panel.add(lbPaidAmount)
    panel.add(lbRemainingAmount)
    panel.add(tfStudentId)
    panel.add(tfStudentName)
    panel.add(tfTotalAmount)
    panel.add(tfPaidAmount)
    panel.add(tfRemainingAmount)
    panel.add(btnPay)
    panel.add(btnCancel)
    
    frame.add(panel)
예제 #47
0
파일: demo.py 프로젝트: fran-jo/SimuGUI
  def __init__(self):
    self.panel = JPanel()
    self.panel.setLayout(BorderLayout())
    frame = JFrame("GUI Development ")
    frame.setSize(800, 600)
    frame.setLayout(BorderLayout())

    splitPane = JSplitPane(JSplitPane.VERTICAL_SPLIT);

    self.textfield1 = JTextField('Type something here')
    self.textfield1.setColumns(40);
    #self.textfield1.setRows(5);
    #self.textfield2 = JTextField('Dont write anythong',30)
    label1 = JLabel("Command:")
    panel1 = JPanel()
    '''
    '''
    jMenuBar1 = JMenuBar()
    jMenu1 = JMenu()
    jMenu2 = JMenu()
    jMenuItem1 = JMenuItem('Open', actionPerformed=self.onClick)
    jMenuItem2 = JMenuItem()
    jMenu1.setText('File')
    jMenu2.setText('Simulation')
    
    #jMenuItem1.setText('Open')
    jMenuItem2.setText('Exit')
    jMenu1.add(jMenuItem1)
    jMenu1.add(jMenuItem2)
    jMenuBar1.add(jMenu1)
    
    jMenuItem21 = JMenuItem('Simulation Options',actionPerformed=self.writeText)
    jMenuItem22 = JMenuItem('Simulate',actionPerformed=self.writeText)
    jMenuItem23 = JMenuItem('Generate FMU',actionPerformed=self.writeText)
    
#     jMenuItem21.setText('Run Project')
#     jMenuItem22.setText('Generate FMU')
    jMenu2.add(jMenuItem21)
    jMenu2.add(jMenuItem22)
    jMenu2.add(jMenuItem23)
    jMenuBar1.add(jMenu2)
    frame.setJMenuBar(jMenuBar1)
    
    '''
    '''
    panel1.add(label1,BorderLayout.WEST)
    panel1.add(self.textfield1, BorderLayout.CENTER)
    copyButton = JButton('send',actionPerformed=self.copyText)
    panel1.add(copyButton, BorderLayout.EAST)
    #panel1.add(self.textfield2, BorderLayout.SOUTH)
    splitPane.setLeftComponent(panel1);
    '''
    
   image adding in the frame
    
    
    '''
    
    #imPanel.add(imPanel,BorderLayout.WEST)
    #imPanel.setBackground(Color(66, 66, 66))
    imPanel1 = JPanel()
    rot = ImageIcon("ballon.jpg")
    rotLabel = JLabel(rot)
    rotLabel.setBounds(0,0, rot.getIconWidth(), rot.getIconHeight())
    imPanel1.add(rotLabel, BorderLayout.SOUTH)
    frame.add(imPanel1, BorderLayout.SOUTH)
    
    '''
    panel for text area adding in split pan 
    
    '''
    tabPane = JTabbedPane(JTabbedPane.TOP)

    label = JLabel("<html><br>This is a tab1</html>")
    panel1 = JPanel()
    panel1.setBackground(Color.lightGray)
    panel23 = JPanel()
    panel23.setBackground(Color.black)
    panel1.add(panel23,BorderLayout.SOUTH)
    panel1.add(label,BorderLayout.NORTH)
    '''
    adding button in the panel1
    '''
    writeButton = JButton('write')
    panel1.add(writeButton, BorderLayout.WEST)
    tabPane.addTab("tab1", panel1)
    
    
    #frame.add(panel1,BorderLayout.EAST)
    #panel1.setBackground(Color(66, 66, 66))
#     rot1 = ImageIcon("ballon.jpg",BorderLayout.SOUTH)
#     rotLabel1 = JLabel(rot1)
#     rotLabel1.setBounds(0,0, rot.getIconWidth(), rot.getIconHeight())
#     panel1.add(rotLabel1)

    label2 = JLabel("This is a tab2")

    panel2 = JPanel()
    panel2.setBackground(Color.lightGray)
    panel2.add(label2)
    tabPane.addTab("tab2", panel2)

#     imPanel2 =JPanel()
    self.textarea = JTextArea('Write something from commandLine')
    self.textarea.setColumns(40);
    self.textarea.setRows(40);
 
    panel2.add(self.textarea, BorderLayout.NORTH)

    splitPane.setRightComponent(tabPane);
    splitPane.setDividerLocation(60);

    frame.add(splitPane)
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
    frame.setVisible(True)
예제 #48
0
파일: main.py 프로젝트: pavithra03/neofelis
  def getArguments(self):
    """
    This function brings up a window to retreive any required arguments.  It uses a window with fields for each argument, filled with any arguments already given.
    While this window is visible the program will wait, once it is no longer visible all the arguments will be filled with the entries in the fields.
    """

    class LocationAction(AbstractAction):
      """
      Action to set the text of a text field to a folder or directory.
      """
      def __init__(self, field):
        AbstractAction.__init__(self, "...")
        self.field = field

      def actionPerformed(self, event):
        fileChooser = JFileChooser()
        fileChooser.fileSelectionMode = JFileChooser.FILES_AND_DIRECTORIES
        if fileChooser.showOpenDialog(None) == JFileChooser.APPROVE_OPTION:
          self.field.text = fileChooser.selectedFile.absolutePath
    
    class HelpAction(AbstractAction):
      """
      Displays a help page in a web browser.
      """
      def __init__(self):
        AbstractAction.__init__(self, "Help")

      def actionPerformed(self, event):
        browsers = ["google-chrome", "firefox", "opera", "epiphany", "konqueror", "conkeror", "midori", "kazehakase", "mozilla"]
        osName = System.getProperty("os.name")
        helpHTML = ClassLoader.getSystemResource("help.html").toString()
        if osName.find("Mac OS") == 0:
          Class.forName("com.apple.eio.FileManager").getDeclaredMethod( "openURL", [String().getClass()]).invoke(None, [helpHTML])
        elif osName.find("Windows") == 0:
          Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + helpHTML)
        else:
          browser = None
          for b in browsers:
            if browser == None and Runtime.getRuntime().exec(["which", b]).getInputStream().read() != -1:
              browser = b
              Runtime.getRuntime().exec([browser, helpHTML])

    class OKAction(AbstractAction):
      """
      Action for starting the pipeline.  This action will simply make the window invisible.
      """
      def __init__(self):
        AbstractAction.__init__(self, "Ok")

      def actionPerformed(self, event):
        frame.setVisible(False)

    class CancelAction(AbstractAction):
      """
      Action for canceling the pipeline.  Exits the program.
      """
      def __init__(self):
        AbstractAction.__init__(self, "Cancel")

      def actionPerformed(self, event):
        sys.exit(0)

    frame = JFrame("Neofelis")
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    constraints = GridBagConstraints()
    contentPane = JPanel(GridBagLayout())
    frame.setContentPane(contentPane)
    blastField = JTextField(self.blastLocation)
    genemarkField = JTextField(self.genemarkLocation)
    transtermField = JTextField(self.transtermLocation)
    tRNAscanField = JTextField(self.tRNAscanLocation)
    databaseLocationField = JTextField(os.path.split(self.database)[0])
    databaseField = JTextField(os.path.split(self.database)[1])
    matrixField = JTextField(str(self.matrix))
    eValueField = JTextField(str(self.eValue))
    minLengthField = JTextField(str(self.minLength))
    scaffoldingDistanceField = JTextField(str(self.scaffoldingDistance))
    promoterScoreField = JTextField(str(self.promoterScoreCutoff))
    queryField = JTextField(self.sources[0])

    constraints.gridx = 0
    constraints.gridy = 0
    constraints.gridwidth = 1
    constraints.gridheight = 1
    constraints.fill = GridBagConstraints.HORIZONTAL
    constraints.weightx = 0
    constraints.weighty = 0
    contentPane.add(JLabel("Blast Location"), constraints)
    constraints.gridy = 1
    contentPane.add(JLabel("Genemark Location"), constraints)
    constraints.gridy = 2
    contentPane.add(JLabel("Transterm Location"), constraints)
    constraints.gridy = 3
    contentPane.add(JLabel("tRNAscan Location"), constraints)
    constraints.gridy = 4
    contentPane.add(JLabel("Databases Location"), constraints)
    constraints.gridy = 5
    contentPane.add(JLabel("Database"), constraints)
    constraints.gridy = 6
    contentPane.add(JLabel("Matrix(Leave blank to use heuristic matrix)"), constraints)
    constraints.gridy = 7
    contentPane.add(JLabel("E Value"), constraints)
    constraints.gridy = 8
    contentPane.add(JLabel("Minimum Intergenic Length"), constraints)
    constraints.gridy = 9
    contentPane.add(JLabel("Scaffold Distance"), constraints)
    constraints.gridy = 10
    contentPane.add(JLabel("Promoter Score Cutoff"), constraints)
    constraints.gridy = 11
    contentPane.add(JLabel("Query"), constraints)
    constraints.gridx = 1
    constraints.gridy = 0
    constraints.weightx = 1
    contentPane.add(blastField, constraints)
    constraints.gridy = 1
    contentPane.add(genemarkField, constraints)
    constraints.gridy = 2
    contentPane.add(transtermField, constraints)
    constraints.gridy = 3
    contentPane.add(tRNAscanField, constraints)
    constraints.gridy = 4
    contentPane.add(databaseLocationField, constraints)
    constraints.gridy = 5
    contentPane.add(databaseField, constraints)
    constraints.gridy = 6
    contentPane.add(matrixField, constraints)
    constraints.gridy = 7
    contentPane.add(eValueField, constraints)
    constraints.gridy = 8
    contentPane.add(minLengthField, constraints)
    constraints.gridy = 9
    contentPane.add(scaffoldingDistanceField, constraints)
    constraints.gridy = 10
    contentPane.add(promoterScoreField, constraints)
    constraints.gridy = 11
    contentPane.add(queryField, constraints)
    constraints.gridx = 2
    constraints.gridy = 0
    constraints.weightx = 0
    constraints.fill = GridBagConstraints.NONE
    constraints.anchor = GridBagConstraints.LINE_END
    contentPane.add(JButton(LocationAction(blastField)), constraints)
    constraints.gridy = 1
    contentPane.add(JButton(LocationAction(genemarkField)), constraints)
    constraints.gridy = 2
    contentPane.add(JButton(LocationAction(transtermField)), constraints)
    constraints.gridy = 3
    contentPane.add(JButton(LocationAction(tRNAscanField)), constraints)
    constraints.gridy = 4
    contentPane.add(JButton(LocationAction(databaseLocationField)), constraints)
    constraints.gridy = 11
    contentPane.add(JButton(LocationAction(queryField)), constraints)

    constraints.gridx = 0
    constraints.gridy = 12
    constraints.anchor = GridBagConstraints.LINE_START
    contentPane.add(JButton(HelpAction()), constraints)
    constraints.gridx = 1
    constraints.anchor = GridBagConstraints.LINE_END
    contentPane.add(JButton(OKAction()), constraints)
    constraints.gridx = 2
    contentPane.add(JButton(CancelAction()), constraints)

    frame.pack()
    frame.setLocationRelativeTo(None)
    frame.setVisible(True)

    while frame.isVisible():
      pass

    self.blastLocation = blastField.getText()
    self.genemarkLocation = genemarkField.getText()
    self.transtermLocation = transtermField.getText()
    self.database = databaseLocationField.getText() + "/" + databaseField.getText()
    self.matrix = matrixField.getText()
    self.eValue = float(eValueField.getText())
    self.minLength = int(minLengthField.getText())
    self.scaffoldingDistance = int(scaffoldingDistanceField.getText())
    self.promoterScoreCutoff = float(promoterScoreField.getText())
    self.sources = [queryField.getText()]
예제 #49
0
class Config(ITab):
    """Defines the Configuration tab"""

    def __init__(self, callbacks, parent):
        # Initialze self stuff
        self._callbacks = callbacks
        self.config = {}
        self.ext_stats = {}
        self.url_reqs = []
        self.parse_files = False
        self.tab = JPanel(GridBagLayout())
        self.view_port_text = JTextArea("===SpyDir===")
        self.delim = JTextField(30)
        self.ext_white_list = JTextField(30)
        # I'm not sure if these fields are necessary still
        # why not just use Burp func to handle this?
        # leaving them in case I need it for the HTTP handler later
        # self.cookies = JTextField(30)
        # self.headers = JTextField(30)
        self.url = JTextField(30)
        self.parent_window = parent
        self.plugins = {}
        self.loaded_p_list = set()
        self.loaded_plugins = False
        self.config['Plugin Folder'] = None
        self.double_click = False
        self.source_input = ""
        self.print_stats = True
        self.curr_conf = JLabel()
        self.window = JFrame("Select plugins",
                             preferredSize=(200, 250),
                             windowClosing=self.p_close)
        self.window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
        self.window.setVisible(False)
        self.path_vars = JTextField(30)


        # Initialize local stuff
        tab_constraints = GridBagConstraints()
        status_field = JScrollPane(self.view_port_text)

        # Configure view port
        self.view_port_text.setEditable(False)

        labels = self.build_ui()

        # Add things to rows
        tab_constraints.anchor = GridBagConstraints.FIRST_LINE_END
        tab_constraints.gridx = 1
        tab_constraints.gridy = 0
        tab_constraints.fill = GridBagConstraints.HORIZONTAL
        self.tab.add(JButton(
            "Resize screen", actionPerformed=self.resize),
                     tab_constraints)
        tab_constraints.gridx = 0
        tab_constraints.gridy = 1
        tab_constraints.anchor = GridBagConstraints.FIRST_LINE_START
        self.tab.add(labels, tab_constraints)

        tab_constraints.gridx = 1
        tab_constraints.gridy = 1
        tab_constraints.fill = GridBagConstraints.BOTH
        tab_constraints.weightx = 1.0
        tab_constraints.weighty = 1.0

        tab_constraints.anchor = GridBagConstraints.FIRST_LINE_END
        self.tab.add(status_field, tab_constraints)
        try:
            self._callbacks.customizeUiComponent(self.tab)
        except Exception:
            pass

    def build_ui(self):
        """Builds the configuration screen"""
        labels = JPanel(GridLayout(21, 1))
        checkbox = JCheckBox("Attempt to parse files for URL patterns?",
                             False, actionPerformed=self.set_parse)
        stats_box = JCheckBox("Show stats?", True,
                              actionPerformed=self.set_show_stats)
        # The two year old in me is laughing heartily
        plug_butt = JButton("Specify plugins location",
                            actionPerformed=self.set_plugin_loc)
        load_plug_butt = JButton("Select plugins",
                                 actionPerformed=self.p_build_ui)
        parse_butt = JButton("Parse directory", actionPerformed=self.parse)
        clear_butt = JButton("Clear text", actionPerformed=self.clear)
        spider_butt = JButton("Send to Spider", actionPerformed=self.scan)
        save_butt = JButton("Save config", actionPerformed=self.save)
        rest_butt = JButton("Restore config", actionPerformed=self.restore)
        source_butt = JButton("Input Source File/Directory",
                              actionPerformed=self.get_source_input)

        # Build grid
        labels.add(source_butt)
        labels.add(self.curr_conf)
        labels.add(JLabel("String Delimiter:"))
        labels.add(self.delim)
        labels.add(JLabel("Extension Whitelist:"))
        labels.add(self.ext_white_list)
        labels.add(JLabel("URL:"))
        labels.add(self.url)
        labels.add(JLabel("Path Variables"))
        labels.add(self.path_vars)
        # Leaving these here for now.
        # labels.add(JLabel("Cookies:"))
        # labels.add(self.cookies)
        # labels.add(JLabel("HTTP Headers:"))
        # labels.add(self.headers)
        labels.add(checkbox)
        labels.add(stats_box)
        labels.add(plug_butt)
        labels.add(parse_butt)
        labels.add(JButton("Show all endpoints",
                           actionPerformed=self.print_endpoints))
        labels.add(clear_butt)
        labels.add(spider_butt)
        labels.add(JLabel(""))
        labels.add(save_butt)
        labels.add(rest_butt)
        labels.add(load_plug_butt)
        # Tool tips!
        self.delim.setToolTipText("Use to manipulate the final URL. "
                                  "See About tab for example.")
        self.ext_white_list.setToolTipText("Define a comma delimited list of"
                                           " file extensions to parse. Use *"
                                           " to parse all files.")
        self.url.setToolTipText("Enter the target URL")
        checkbox.setToolTipText("Parse files line by line using plugins"
                                " to enumerate language/framework specific"
                                " endpoints")
        parse_butt.setToolTipText("Attempt to enumerate application endpoints")
        clear_butt.setToolTipText("Clear status window and the parse results")
        spider_butt.setToolTipText("Process discovered endpoints")
        save_butt.setToolTipText("Saves the current config settings")
        rest_butt.setToolTipText("<html>Restores previous config settings:"
                                 "<br/>-Input Directory<br/>-String Delim"
                                 "<br/>-Ext WL<br/>-URL<br/>-Plugins")
        source_butt.setToolTipText("Select the application's "
                                   "source directory or file to parse")
        self.path_vars.setToolTipText("Supply a JSON object with values"
                                      "for dynamically enumerated query"
                                      "string variables")

        return labels

    def set_url(self, menu_url):
        """Changes the configuration URL to the one from the menu event"""
        self.url.setText(menu_url)

    # Event functions
    def set_parse(self, event):
        """
        Handles the click event from the UI checkbox
        to attempt code level parsing
        """
        self.parse_files = not self.parse_files
        if self.parse_files:
            if not self.loaded_plugins:
                self._plugins_missing_warning()

    def restore(self, event):
        """Attempts to restore the previously saved configuration."""
        jdump = None
        try:
            jdump = loads(self._callbacks.loadExtensionSetting("config"))
        except Exception as exc:  # Generic exception thrown directly to user
            self.update_scroll(
                "[!!] Error during restore!\n\tException: %s" % str(exc))
        if jdump is not None:
            self.url.setText(jdump.get('URL'))
            # self.cookies.setText(jdump.get('Cookies'))
            # self.headers.setText(jdump.get("Headers"))
            ewl = ""
            for ext in jdump.get('Extension Whitelist'):
                ewl += ext + ", "
            self.ext_white_list.setText(ewl[:-2])
            self.delim.setText(jdump.get('String Delimiter'))
            self.source_input = jdump.get("Input Directory")
            self.config['Plugin Folder'] = jdump.get("Plugin Folder")
            if (self.config['Plugin Folder'] is not None and
                    (len(self.plugins.values()) < 1)):
                self._load_plugins(self.config['Plugin Folder'])
            self._update()
            self.update_scroll("[^] Restore complete!")
        else:
            self.update_scroll("[!!] Restore failed!")

    def save(self, event=None):
        """
        Saves the configuration details to a Burp Suite's persistent store.
        """
        self._update()
        try:
            if not self._callbacks.isInScope(URL(self.url.getText())):
                self.update_scroll("[!!] URL provided is NOT in Burp Scope!")
        except MalformedURLException:  # If url field is blank we'll
            pass                       # still save the settings.
        try:
            self._callbacks.saveExtensionSetting("config", dumps(self.config))
            self.update_scroll("[^] Settings saved!")
        except Exception:
            self.update_scroll("[!!] Error saving settings to Burp Suite!")

    def parse(self, event):
        """
        Handles the click event from the UI.
        Attempts to parse the given directory
            (and/or source files) for url endpoints
        Saves the items found within the url_reqs list
        """
        self._update()

        file_set = set()
        fcount = 0
        other_dirs = set()
        self.ext_stats = {}
        if self.loaded_plugins:
            self.update_scroll("[^] Attempting to parse files" +
                               " for URL patterns. This might take a minute.")
        if path.isdir(self.source_input):
            for dirname, _, filenames in walk(self.source_input):
                for filename in filenames:
                    fcount += 1
                    ext = path.splitext(filename)[1]
                    count = self.ext_stats.get(ext, 0) + 1
                    filename = "%s/%s" % (dirname, filename)
                    self.ext_stats.update({ext: count})
                    if self.parse_files and self._ext_test(ext):
                        # i can haz threading?
                        file_set.update(self._code_as_endpoints(filename, ext))
                    elif self._ext_test(ext):
                        r_files, oths = self._files_as_endpoints(filename, ext)
                        file_set.update(r_files)
                        other_dirs.update(oths)
        elif path.isfile(self.source_input):
            ext = path.splitext(self.source_input)[1]
            file_set.update(self._code_as_endpoints(self.source_input, ext))
        else:
            self.update_scroll("[!!] Input Directory is not valid!")
        if len(other_dirs) > 0:
            self.update_scroll("[*] Found files matching file extension in:\n")
            for other_dir in other_dirs:
                self.update_scroll(" " * 4 + "%s\n" % other_dir)
        self._handle_path_vars(file_set)
        self._print_parsed_status(fcount)
        return (other_dirs, self.url_reqs)

    def _handle_path_vars(self, file_set):
        proto = 'http://'
        for item in file_set:
            if item.startswith("http://") or item.startswith("https://"):
                proto = item.split("//")[0] + '//'
                item = item.replace(proto, "")
                item = self._path_vars(item)
            self.url_reqs.append(proto + item.replace('//', '/'))

    def _path_vars(self, item):
        p_vars = None
        if self.path_vars.getText():
            try:
                p_vars = loads(str(self.path_vars.getText()))
            except:
                self.update_scroll("[!] Error reading supplied Path Variables!")
        if p_vars is not None:
            rep_str = ""
            try:
                for k in p_vars.keys():
                    rep_str += "[^] Replacing %s with %s!\n" % (k, str(p_vars.get(k)))
                self.update_scroll(rep_str)
                for k in p_vars.keys():
                    if str(k) in item:
                        item = item.replace(k, str(p_vars.get(k)))
            except AttributeError:
                self.update_scroll("[!] Error reading supplied Path Variables! This needs to be a JSON dictionary!")
        return item
            
            
    def scan(self, event):
        """
        handles the click event from the UI.
        Adds the given URL to the burp scope and sends the requests
        to the burp spider
        """
        temp_url = self.url.getText()
        if not self._callbacks.isInScope(URL(temp_url)):
            if not self.double_click:
                self.update_scroll("[!!] URL is not in scope! Press Send to "
                                   "Spider again to add to scope and scan!")
                self.double_click = True
                return
            else:
                self._callbacks.sendToSpider(URL(temp_url))
        self.update_scroll(
            "[^] Sending %d requests to Spider" % len(self.url_reqs))
        for req in self.url_reqs:
            self._callbacks.sendToSpider(URL(req))

    def clear(self, event):
        """Clears the viewport and the current parse exts"""
        self.view_port_text.setText("===SpyDir===")
        self.ext_stats = {}

    def print_endpoints(self, event):
        """Prints the discovered endpoints to the status window."""
        req_str = ""
        if len(self.url_reqs) > 0:
            self.update_scroll("[*] Printing all discovered endpoints:")
            for req in sorted(self.url_reqs):
                req_str += "    %s\n" % req
        else:
            req_str = "[!!] No endpoints discovered"
        self.update_scroll(req_str)

    def set_show_stats(self, event):
        """Modifies the show stats setting"""
        self.print_stats = not self.print_stats

    def get_source_input(self, event):
        """Sets the source dir/file for parsing"""
        source_chooser = JFileChooser()
        source_chooser.setFileSelectionMode(
            JFileChooser.FILES_AND_DIRECTORIES)
        source_chooser.showDialog(self.tab, "Choose Source Location")
        chosen_source = source_chooser.getSelectedFile()
        try:
            self.source_input = chosen_source.getAbsolutePath()
        except AttributeError:
            pass
        if self.source_input is not None:
            self.update_scroll("[*] Source location: %s" % self.source_input)
            self.curr_conf.setText(self.source_input)

    # Plugin functions
    def _parse_file(self, filename, file_url):
        """
        Attempts to parse a file with the loaded plugins
        Returns set of endpoints
        """
        file_set = set()
        with open(filename, 'r') as plug_in:
            lines = plug_in.readlines()
        ext = path.splitext(filename)[1].upper()
        if ext in self.plugins.keys() and self._ext_test(ext):
            for plug in self.plugins.get(ext):
                if plug.enabled:
                    res = plug.run(lines)
                    if len(res) > 0:
                        for i in res:
                            i = file_url + i
                            file_set.add(i)
        elif ext == '.TXT' and self._ext_test(ext):
            for i in lines:
                i = file_url + i
                file_set.add(i.strip())
        return file_set

    def set_plugin_loc(self, event):
        """Attempts to load plugins from a specified location"""
        if self.config['Plugin Folder'] is not None:
            choose_plugin_location = JFileChooser(self.config['Plugin Folder'])
        else:
            choose_plugin_location = JFileChooser()
        choose_plugin_location.setFileSelectionMode(
            JFileChooser.DIRECTORIES_ONLY)
        choose_plugin_location.showDialog(self.tab, "Choose Folder")
        chosen_folder = choose_plugin_location.getSelectedFile()
        self.config['Plugin Folder'] = chosen_folder.getAbsolutePath()
        self._load_plugins(self.config['Plugin Folder'])

    def _load_plugins(self, folder):
        """
        Parses a local directory to get the plugins
            related to code level scanning
        """
        report = ""
        if len(self.plugins.keys()) > 0:
            report = "[^] Plugins reloaded!"
        for _, _, filenames in walk(folder):
            for p_name in filenames:
                n_e = path.splitext(p_name)  # n_e = name_extension
                if n_e[1] == ".py":
                    f_loc = "%s/%s" % (folder, p_name)
                    loaded_plug = self._validate_plugin(n_e[0], f_loc)
                    if loaded_plug:
                        for p in self.loaded_p_list:
                            if p.get_name() == loaded_plug.get_name():
                                self.loaded_p_list.discard(p)
                        self.loaded_p_list.add(loaded_plug)
                        if not report.startswith("[^]"):
                            report += "%s loaded\n" % loaded_plug.get_name()

        self._dictify(self.loaded_p_list)
        if len(self.plugins.keys()) > 0:
            self.loaded_plugins = True
        else:
            report = "[!!] Plugins load failure"
            self.loaded_plugins = False
        self.update_scroll(report)
        return report

    def _validate_plugin(self, p_name, f_loc):
        """
        Attempts to verify the manditory plugin functions to prevent broken
        plugins from loading.
        Generates an error message if plugin does not contain an appropriate
        function.
        """
        # Load the plugin
        try:
            plug = load_source(p_name, f_loc)
        except Exception as exc:  # this needs to be generic.
            self.update_scroll(
                "[!!] Error loading: %s\n\tType:%s Error: %s"
                % (f_loc, type(exc), str(exc)))
        # Verify the plugin's functions
        funcs = dir(plug)
        err = []
        if "get_name" not in funcs:
            err.append("get_name()")
        if "get_ext" not in funcs:
            err.append("get_ext()")
        if "run" not in funcs:
            err.append("run()")

        # Report errors & return
        if len(err) < 1:
            return Plugin(plug, True)
        for issue in err:
            self.update_scroll("[!!] %s is missing: %s func" %
                               (p_name, issue))
        return None

    def _dictify(self, plist):
        """Converts the list of loaded plugins (plist) into a dictionary"""
        for p in plist:
            exts = p.get_ext().upper()
            for ext in exts.split(","):
                prev_load = self.plugins.get(ext, [])
                prev_load.append(p)
                self.plugins[ext] = prev_load

    # Status window functions
    def _print_parsed_status(self, fcount):
        """Prints the parsed directory status information"""
        if self.parse_files and not self.loaded_plugins:
            self._plugins_missing_warning()
        if len(self.url_reqs) > 0:
            self.update_scroll("[*] Example URL: %s" % self.url_reqs[0])

        if self.print_stats:
            report = (("[*] Found: %r files to be requested.\n\n" +
                       "[*] Stats: \n    " +
                       "Found: %r files.\n") % (len(self.url_reqs), fcount))
            if len(self.ext_stats) > 0:
                report += ("[*] Extensions found: %s"
                           % str(dumps(self.ext_stats,
                                       sort_keys=True, indent=4)))
        else:
            report = ("[*] Found: %r files to be requested.\n" %
                      len(self.url_reqs))
        self.update_scroll(report)
        return report

    def _plugins_missing_warning(self):
        """Prints a warning message"""
        self.update_scroll("[!!] No plugins loaded!")

    def update_scroll(self, text):
        """Updates the view_port_text with the new information"""
        temp = self.view_port_text.getText().strip()
        if text not in temp or text[0:4] == "[!!]":
            self.view_port_text.setText("%s\n%s" % (temp, text))
        elif not temp.endswith("[^] Status unchanged"):
            self.view_port_text.setText("%s\n[^] Status unchanged" % temp)

    # Internal functions
    def _code_as_endpoints(self, filename, ext):
        file_set = set()
        file_url = self.config.get("URL")
        if self.loaded_plugins or ext == '.txt':
            if self._ext_test(ext):
                file_set.update(
                    self._parse_file(filename, file_url))
            else:
                file_set.update(
                    self._parse_file(filename, file_url))
        return file_set

    def _files_as_endpoints(self, filename, ext):
        """Generates endpoints via files with the appropriate extension(s)"""
        file_url = self.config.get("URL")
        broken_splt = ""
        other_dirs = set()  # directories outside of the String Delim.
        file_set = set()
        str_del = self.config.get("String Delimiter")
        if not str_del:
            self.update_scroll("[!!] No available String Delimiter!")
            return
        spl_str = filename.split(str_del)

        try:
            # Fix for index out of bounds exception while parsing
            # subfolders _not_ included by the split
            if len(spl_str) > 1:
                file_url += ((spl_str[1])
                             .replace('\\', '/'))
            else:
                broken_splt = filename.split(self.source_input)[1]
                other_dirs.add(broken_splt)
        except Exception as exc:  # Generic exception thrown directly to user
            self.update_scroll("[!!] Error parsing: " +
                               "%s\n\tException: %s"
                               % (filename, str(exc)))
        if self._ext_test(ext):
            if file_url != self.config.get("URL"):
                file_set.add(file_url)
        else:
            other_dirs.discard(broken_splt)
        return file_set, other_dirs

    def _ext_test(self, ext):
        """Litmus test for extension whitelist"""
        val = False
        if "*" in self.config.get("Extension Whitelist"):
            val = True
        else:
            val = (len(ext) > 0 and
                   (ext.strip().upper()
                    in self.config.get("Extension Whitelist")))
        return val

    def _update(self):
        """Updates internal data"""
        self.config["Input Directory"] = self.source_input
        self.config["String Delimiter"] = self.delim.getText()

        white_list_text = self.ext_white_list.getText()
        self.config["Extension Whitelist"] = white_list_text.upper().split(',')
        file_url = self.url.getText()
        if not (file_url.startswith('https://') or file_url.startswith('http://')):
            self.update_scroll("[!] Assuming protocol! Default value: 'http://'")
            file_url = 'http://' + file_url
            self.url.setText(file_url)

        if not file_url.endswith('/') and file_url != "":
            file_url += '/'

        self.config["URL"] = file_url
        # self.config["Cookies"] = self.cookies.getText()
        # self.config["Headers"] = self.headers.getText()
        del self.url_reqs[:]
        self.curr_conf.setText(self.source_input)

    # Window sizing functions
    def resize(self, event):
        """Resizes the window to better fit Burp"""
        if self.parent_window is not None:
            par_size = self.parent_window.getSize()
            par_size.setSize(par_size.getWidth() * .99,
                             par_size.getHeight() * .9)
            self.tab.setPreferredSize(par_size)
            self.parent_window.validate()
            self.parent_window.switch_focus()

    def p_close(self, event):
        """
        Handles the window close event.
        """
        self.window.setVisible(False)
        self.window.dispose()

    def p_build_ui(self, event):
        """
        Adds a list of checkboxes, one for each loaded plugin
        to the Selct plugins window
        """
        if not self.loaded_p_list:
            self.update_scroll("[!!] No plugins loaded!")
            return

        scroll_pane = JScrollPane()
        scroll_pane.setPreferredSize(Dimension(200, 250))
        check_frame = JPanel(GridBagLayout())
        constraints = GridBagConstraints()
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridy = 0
        constraints.anchor = GridBagConstraints.FIRST_LINE_START

        for plug in self.loaded_p_list:
            check_frame.add(JCheckBox(plug.get_name(), plug.enabled,
                                      actionPerformed=self.update_box),
                            constraints)
            constraints.gridy += 1

        vport = JViewport()
        vport.setView(check_frame)
        scroll_pane.setViewport(vport)
        self.window.contentPane.add(scroll_pane)
        self.window.pack()
        self.window.setVisible(True)

    def update_box(self, event):
        """
        Handles the check/uncheck event for the plugin's box.
        """
        for plug in self.loaded_p_list:
            if plug.get_name() == event.getActionCommand():
                plug.enabled = not plug.enabled
                if plug.enabled:
                    self.update_scroll("[^] Enabled: %s" %
                                       event.getActionCommand())
                else:
                    self.update_scroll("[^] Disabled: %s" %
                                       event.getActionCommand())

    # ITab required functions
    @staticmethod
    def getTabCaption():
        """Returns the name of the Burp Suite Tab"""
        return "SpyDir"

    def getUiComponent(self):
        """Returns the UI component for the Burp Suite tab"""
        return self.tab