예제 #1
0
 def run(self):
     frame = JFrame('LayeredPaneDemo',
                    locationRelativeTo=None,
                    defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
     frame.setContentPane(self.createLayeredPane())
     frame.pack()
     frame.setVisible(1)
예제 #2
0
 def run(self):
     #-----------------------------------------------------------------------
     # First, we determine the size & location of the application frame
     #-----------------------------------------------------------------------
     screenSize = Toolkit.getDefaultToolkit().getScreenSize()
     w = screenSize.width >> 1  # 1/2 screen width
     h = screenSize.height >> 1  # 1/2 screen height
     x = (screenSize.width - w) >> 1
     y = (screenSize.height - h) >> 1
     frame = JFrame(
         'iFrameEvents2',
         bounds=(x, y, w, h),  # location & size
         defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
     #-----------------------------------------------------------------------
     # Next, we create, and add the menubar
     #-----------------------------------------------------------------------
     frame.setJMenuBar(self.menuBar())
     #-----------------------------------------------------------------------
     # Then, we replace the frame ContentPane with a JDesktopPane instance
     # for all of the inner frames, and populate it with our eventLogger
     # inner frame instance.
     #-----------------------------------------------------------------------
     self.desktop = desktop = JDesktopPane()
     self.logger = eventLogger()
     desktop.add(self.logger, 0, 0)
     frame.setContentPane(desktop)
     #-----------------------------------------------------------------------
     # Initialize the number of inner frames created
     #-----------------------------------------------------------------------
     self.iFrameCount = 0
     frame.setVisible(1)
예제 #3
0
class VacalcFrame(object):
    def __init__(self, employees):
        self._frame = JFrame('Vacation Calculator',
                             defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        self._frame.setContentPane(self._create_ui(employees))
        self._frame.pack()

    def _create_ui(self, employees):
        panel = JPanel(layout=FlowLayout())
        self._overview = EmployeeOverview(employees, self)
        self._details = EmployeeDetails(employees)
        self._welcome = Welcome()
        panel.add(self._overview)
        panel.add(self._welcome)
        return panel

    def show(self):
        self._frame.setVisible(True)

    def employee_selected(self, employee):
        self._ensure_details_shown()
        self._details.show_employee(employee)

    def edit_new_employee(self):
        self._ensure_details_shown()
        self._details.edit_new_employee()

    def _ensure_details_shown(self):
        if self._welcome:
            self._frame.contentPane.remove(self._welcome)
            self._frame.contentPane.add(self._details)
            self._frame.pack()
            self._welcome = None
예제 #4
0
class VacalcFrame(object):
    def __init__(self, employees, dateprovider):
        self._frame = JFrame("Vacation Calculator", defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        self._frame.setContentPane(self._create_ui(employees, dateprovider))
        self._frame.pack()

    def _create_ui(self, employees, dateprovider):
        panel = JPanel(layout=FlowLayout())
        self._overview = EmployeeOverview(employees, self)
        self._details = EmployeeDetails(employees, dateprovider)
        self._welcome = Welcome()
        panel.add(self._overview)
        panel.add(self._welcome)
        return panel

    def show(self):
        self._frame.setVisible(True)

    def employee_selected(self, employee):
        self._ensure_details_shown()
        self._details.show_employee(employee)

    def edit_new_employee(self):
        self._ensure_details_shown()
        self._details.edit_new_employee()

    def _ensure_details_shown(self):
        if self._welcome:
            self._frame.contentPane.remove(self._welcome)
            self._frame.contentPane.add(self._details)
            self._frame.pack()
            self._welcome = None
예제 #5
0
def startGui():
    frame = JFrame("MonkeyPySon")
    frame.setContentPane(getContentPane())
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    frame.pack()
    frame.setVisible(True)
    frame.addWindowFocusListener(GuiWindowFocusListener())
    startLookingDevices()
예제 #6
0
파일: ashdi.py 프로젝트: sjp38/ash
def start_ashdi():
    loadKeyLayout("data_2.0/ashdi_keylayout.xml")

    global frame
    frame = JFrame(FRAME_TITLE)
    frame.setContentPane(getContentPane())
    frame.windowClosing = lambda x: windowClosing()
    frame.pack()
    frame.setVisible(True)
    frame.addWindowFocusListener(GuiWindowFocusListener())
    start_android_waker()
    handleConnectedDevBtn(True)
    check_move_support()
예제 #7
0
    def show_pannel(self):
        # BP_STDOUT.println("Event code: %s" % self.contextMenuInvocation.getInputEvent())
        # self.scannerInstance.show_pannel.show()
        window = JFrame()
        window.setLayout(None)
        window.setTitle("Xcrpter")
        window.setSize(720, 540)
        window.setLocationRelativeTo(None)
        window.setResizable(True)
        window.setContentPane(self.scannerInstance.xpannel)
        window.setVisible(True)

        self.scannerInstance.xpannel.setPlain("")
        self.scannerInstance.xpannel.setVisible(True)
예제 #8
0
 def run(self):
     screenSize = Toolkit.getDefaultToolkit().getScreenSize()
     w = screenSize.width >> 1  # 1/2 screen width
     h = screenSize.height >> 1  # 1/2 screen height
     x = (screenSize.width - w) >> 1
     y = (screenSize.height - h) >> 1
     frame = JFrame(
         'iFrameEvents1',
         bounds=(x, y, w, h),  # location & size
         defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
     desktop = JDesktopPane()
     desktop.add(eventLogger(), 0, 0)
     frame.setContentPane(desktop)
     frame.setVisible(1)
예제 #9
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)
예제 #10
0
    def run(self):
        screenSize = Toolkit.getDefaultToolkit().getScreenSize()
        w = screenSize.width >> 1  # 1/2 screen width
        h = screenSize.height >> 1  # 1/2 screen height
        x = (screenSize.width - w) >> 1
        y = (screenSize.height - h) >> 1
        frame = JFrame(
            'iFrameDemo',
            bounds=(x, y, w, h),  # location & size
            defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        desktop = JDesktopPane()
        for i in range(3):
            inner = JInternalFrame(
                'Inner Frame #%d' % (i + 1),
                1,  # Resizeable
                1,  # Closeable
                1,  # Maximizable
                1,  # Iconifiable
                visible=1,  # setVisible( 1 )
                bounds=(i * 25 + 25, i * 25 + 25, 250, 250))
            desktop.add(inner)
#           desktop.add( inner, i, 0 )      # preferred add() method
        frame.setContentPane(desktop)
        frame.setVisible(1)
    "<html><font size=+1 color=#191970>vorhandene Lektionen:</font></html>")
uebersichtLabel2.setBounds(450, 200, 250, 50)
uebersicht2 = JTextArea()
uebersicht2.editable = False
uebersicht_scroll2 = JScrollPane(uebersicht2)
uebersicht_scroll2.viewport.view = uebersicht2
uebersicht_scroll2.setBounds(450, 250, 250, 410)
feld_feedback = JTextArea()
feld_feedback.editable = False
feld_feedback.setBounds(50, 50, 300, 600)
button_close = JButton('close window', actionPerformed=close2)
button_close.setBounds(50, 650, 300, 30)
hintergrund2 = ImageIcon("Hintergrund.jpg")
pnl2 = JPanel()
hintergrundlabel2 = JLabel(hintergrund2)
frame_feedback.setContentPane(hintergrundlabel2)
frame_feedback.add(button_close)
frame_feedback.add(uebersicht_scroll2)
frame_feedback.add(uebersichtLabel2)
frame_feedback.add(feld_feedback)
frame_feedback.setVisible(False)


class Main(Client):
    def __init__(self):
        pass

    def stateChanged(self, cs):
        print "new state: " + str(cs)

    def sessionStarted(self):
예제 #12
0
class Pipeline():
  def __init__(self):
    #If a swing interface is asked for this will be the JFrame.
    self.frame = None
    #Keeps track of the number of queries processed.
    self.jobCount = 0
    #Keeps track of the query currently being processed.
    self.currentJob = ""
    #Keeps track of the massage to be displayed.
    self.message = 0
    #Messages to be displayed at each stage in the processing of a single query.
    self.messages = ["Searching for genes via genemark",
                     "Extending genes found via genemark",
                     "Searching for intergenic genes",
                     "Removing overlapping genes",
                     "Searching for promoters",
                     "Using transterm to find terminators",
                     "Removing transcription signals which conflict with genes",
                     "Using tRNAscan to find transfer RNAs",
                     "Writing Artemis file",
                     "Writing summary .xml, .html, and .xls files"]
    self.exception = None

  def initializeDisplay(self, queries, swing):
    """
    queries: A list of the fasts files to be processed.
    swing:   If true then updates about progress will be displayed in a swing window, otherwise they will be written to stdout.
    
    Initializes the interface for telling the user about progress in the pipeline.  Queries is used to count the
    number of queries the pipeline will process and to size the swing display(if it is used) so that text
    isn't cutoff at the edge of the window.  The swing display is setup if swing is true.
    """
  
    self.numJobs = len(queries)
    if swing:
      self.frame = JFrame("Neofelis")
      self.frame.addWindowListener(PipelineWindowAdapter(self))
      contentPane = JPanel(GridBagLayout())
      self.frame.setContentPane(contentPane)
      self.globalLabel = JLabel(max(queries, key = len))
      self.globalProgress = JProgressBar(0, self.numJobs)
      self.currentLabel = JLabel(max(self.messages, key = len))
      self.currentProgress = JProgressBar(0, len(self.messages))
      self.doneButton = JButton(DoneAction(self.frame))
      self.doneButton.setEnabled(False)

      constraints = GridBagConstraints()
      
      constraints.gridx, constraints.gridy = 0, 0
      constraints.gridwidth, constraints.gridheight = 1, 1
      constraints.weightx = 1
      constraints.fill = GridBagConstraints.HORIZONTAL
      contentPane.add(self.globalLabel, constraints)
      constraints.gridy = 1
      contentPane.add(self.globalProgress, constraints)
      constraints.gridy = 2
      contentPane.add(self.currentLabel, constraints)
      constraints.gridy = 3
      contentPane.add(self.currentProgress, constraints)
      constraints.gridy = 4
      constraints.weightx = 0
      constraints.fill = GridBagConstraints.NONE
      constraints.anchor = GridBagConstraints.LINE_END
      contentPane.add(self.doneButton, constraints)
    
      self.frame.pack()
      self.frame.setResizable(False)
      self.globalLabel.setText(" ")
      self.currentLabel.setText(" ")
      self.frame.setLocationRelativeTo(None)
      self.frame.setVisible(True)

  def updateProgress(self, job):
    """
    query: Name of the query currently being processed.
    
    This function use used for updating the progress shown in the interface.  If job is not equal to currentJob then
    global progress is incremented and shown and the currentProgress is reset and shown.  If job is equal to currentJob
    then the globalProgress does not change and currentProgress is increased.
    """
    if self.exception:
      raise self.exception
    
    if self.frame:
      if job != self.currentJob:
        self.currentProgress.setValue(self.currentProgress.getMaximum())
        self.globalLabel.setText(job)
        self.globalProgress.setValue(self.jobCount)
        print "Processing %s, %.2f%% done" % (job, 100.0*self.jobCount/self.numJobs)
        self.jobCount += 1
        self.currentJob = job
        self.message = -1
      self.message += 1
      print "    %s, %.2f%% done" % (self.messages[self.message], 100.0*self.message/len(self.messages))
      self.currentProgress.setValue(self.message)
      self.currentLabel.setText(self.messages[self.message])
    else:
      if job != self.currentJob:
        print "Processing %s, %.2f%% done" % (job, 100.0*self.jobCount/self.numJobs)
        self.jobCount += 1
        self.currentJob = job
        self.message = -1
      self.message += 1
      print "    %s, %.2f%% done" % (self.messages[self.message], 100.0*self.message/len(self.messages))

  def finished(self):
    """
    This function is to be called at the end of the pipeline.  Informs the user that the pipeline is finished
    and if a swing interface is being used the Done button is enabled.
    """
    print "Processing 100.00% done"
    if self.frame:
      self.globalLabel.setText("Finished")
      self.globalProgress.setValue(self.globalProgress.getMaximum())
      self.currentLabel.setText(" ")
      self.currentProgress.setValue(self.currentProgress.getMaximum())
      self.doneButton.setEnabled(True)
      while self.frame.isVisible():
        pass

  def run(self, blastLocation, genemarkLocation, transtermLocation, tRNAscanLocation, database, eValue, matrix, minLength, scaffoldingDistance, promoterScoreCutoff, queries, swing = False, email = ""):
    """
    blastLocation:       Directory blast was installed in.
    genemarkLocation:    Directory genemark was installed in.
    transtermLocation:   Directory transterm was installed in.
    tRNAscanLocation:    Directory tRNAscan was installed in.
    database:            Name of the blast database to use.
    eValue:              The e value used whenever a blast search is done.
    matrix:              The matrix to use when running genemark.  If None then genemark is run heuristically.
    minLength:           Minimum length of any genes included in the resulting annotation.
    scaffoldingDistance: The maximum length allowed between genes when contiguous regions of genes are being identified
    promoterScoreCutoff: Minimum score allowed for any promoters included in the resulting annotation
    queries:             A list of faster files to process.
    swing:               If true a swing window will be used to updated the user about the pipeline's progress.
    email:               If this is a non-empty string an email will be sent to the address in the string when the pipeline is done.  This will be attempted with the sendmail command on the local computer.
    
    The main pipeline function.  For every query genemark is used to predict genes, these genes are then extended to any preferable starts.  Then the pipeline searches
    for any intergenic genes(genes between those found by genemark) and these are combined with the extended genemark genes.  Then the genes are pruned to remove
    any undesirable genes found in the intergenic stage.  BPROM and Transterm are used to find promoters and terminators, which are then pruned to remove any
    signals which are inside or too far away from any genes.  Next, tRNAscan is used to find any transfer RNAs in the genome.  Finally, all the remaining genes,
    promoters, and terminators are written to an artemis file in the directory of the query with the same name but with a .art extension, and .xml, .html, and
    .xls files will be generating describing the blast results of the final genes.
    """
    self.initializeDisplay(queries, swing)

    try:
      for query in queries:
        name = os.path.splitext(query)[0]
        queryDirectory, name = os.path.split(name)
        
        genome = utils.loadGenome(query)
        swapFileName = "query" + str(id(self)) + ".fas"
        queryFile = open(swapFileName, "w")
        queryFile.write(">" + name + "\n")
        for i in range(0, len(genome), 50):
          queryFile.write(genome[i:min(i+50, len(genome))] + "\n")
        queryFile.close()

        self.updateProgress(query)
        initialGenes = genemark.findGenes(swapFileName, name, blastLocation, database, eValue, genemarkLocation, matrix, self)
      
        self.updateProgress(query)
        extendedGenes = extend.extendGenes(swapFileName, initialGenes, name, blastLocation, database, eValue, self)
    
        self.updateProgress(query)
        intergenicGenes = intergenic.findIntergenics(swapFileName, extendedGenes, name, minLength, blastLocation, database, eValue, self)

        genes = {}
        for k, v in extendedGenes.items() + intergenicGenes.items():
          genes[k] = v
        
        self.updateProgress(query)
        scaffolded = scaffolds.refineScaffolds(genes, scaffoldingDistance)
 
        self.updateProgress(query)
        initialPromoters = promoters.findPromoters(swapFileName, name, promoterScoreCutoff, self.frame)
    
        self.updateProgress(query)
        initialTerminators = terminators.findTerminators(swapFileName, name, genes.values(), transtermLocation)
      
        self.updateProgress(query)
        filteredSignals = signals.filterSignals(scaffolded.values(), initialPromoters + initialTerminators)
        filteredPromoters = filter(lambda x: isinstance(x, promoters.Promoter), filteredSignals)
        filteredTerminators = filter(lambda x: isinstance(x, terminators.Terminator), filteredSignals)

        self.updateProgress(query)
        transferRNAs = rna.findtRNAs(tRNAscanLocation, swapFileName)

        os.remove(swapFileName)

        self.updateProgress(query)
        artemis.writeArtemisFile(os.path.splitext(query)[0] + ".art", genome, scaffolded.values(), filteredPromoters, filteredTerminators, transferRNAs)

        self.updateProgress(query)
        report.report(name, scaffolded, os.path.splitext(query)[0])

      if email:
        if not os.path.isfile("EMAIL_MESSAGE"):
          message = open("EMAIL_MESSAGE", "w")
          message.write("Subject: Annotation Complete\nYour genome has been annotated.\n")
          message.close()
        
        sent = False
        while not sent:
          message = open("EMAIL_MESSAGE", "r")
          sendmailProcess = subprocess.Popen(["/usr/sbin/sendmail", "-F", "Neofelis", "-f", "*****@*****.**", email],
                                             stdin = message,
                                             stdout = subprocess.PIPE)
          result = ""
          nextRead = sendmailProcess.stdout.read()
          while nextRead:
            result += nextRead
            nextRead = sendmailProcess.stdout.read()
          sent = not result.strip()
          message.close()
    
      self.finished()
    except PipelineException:
      return
예제 #13
0
plainText = TextArea("n/a")
plainText.setSize(300, 400)
plainText.setLocation(642, 114)
plainText.setFont(subSpecialFont)

# All Labels Belongs Here

hackingHeader = JLabel("<html><center>Hacker Form<html>", JLabel.CENTER)
hackingHeader.setSize(924, 55)
hackingHeader.setFont(formHeaderFont)
hackingHeader.setAlignmentY(34)
hackingHeader.setLocation(21, 21)

# All Form Belong Here
mainForm.setContentPane(myPanel)
mainForm.locationByPlatform = True

# Put Objects Altogether on Panel
myPanel.add(alphaTextField)
myPanel.add(hackButton)
myPanel.add(alphaLabel)
myPanel.add(betaLabel)
myPanel.add(primaLabel)
myPanel.add(betaTextField)
myPanel.add(primaTextField)
myPanel.add(hackingHeader)
#myPanel.add(dekomposisiLabel)
#myPanel.add(dekomposisiList)
myPanel.add(FBSizeLabel)
myPanel.add(FBSize)
예제 #14
0
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)

        # remember that this image has been created and is active (so that it can be stopped/terminated by JEM, if desired)
        _ActiveImages_.append(self)

    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)
예제 #15
0
try:
    finaleReport.text = string3
except:
    print "Gagal melaporkan tahap 3"
finaleReport.setSize(363, 341)
finaleReport.setLocation(5, 5)
finaleReport.setBackground(Color.GRAY)

p3.add(finaleReport)
tabbedPane.addTab("Tahap ke-3", p3)

#panel3.setLocation(0, 0)

##

myNewPanel = JPanel()
myNewPanel.setLocation(0, 0)
myNewPanel.setOpaque(True)
myNewPanel.setBackground(Color.WHITE)
myNewPanel.setLayout(None)


myNewForm = JFrame("Laporan", size=(425, 425)) #(377, 377)
myNewForm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)

myNewForm.locationByPlatform = True
#myNewForm.setVisible(True)
myNewForm.setContentPane(myNewPanel)
myNewForm.add(tabbedPane)
예제 #16
0
class Pipeline():
    def __init__(self):
        #If a swing interface is asked for this will be the JFrame.
        self.frame = None
        #Keeps track of the number of queries processed.
        self.jobCount = 0
        #Keeps track of the query currently being processed.
        self.currentJob = ""
        #Keeps track of the massage to be displayed.
        self.message = 0
        #Messages to be displayed at each stage in the processing of a single query.
        self.messages = [
            "Searching for genes via genemark",
            "Extending genes found via genemark",
            "Searching for intergenic genes", "Removing overlapping genes",
            "Searching for promoters", "Using transterm to find terminators",
            "Removing transcription signals which conflict with genes",
            "Writing Artemis file", "Writing summary file"
        ]
        self.exception = None

    def initializeDisplay(self, queries, swing):
        """
    queries: A list of the fasts files to be processed.
    swing:   If true then updates about progress will be displayed in a swing window, otherwise they will be written to stdout.
    
    Initializes the interface for telling the user about progress in the pipeline.  Queries is used to count the
    number of queries the pipeline will process and to size the swing display(if it is used) so that text
    isn't cutoff at the edge of the window.  The swing display is setup if swing is true.
    """

        self.numJobs = len(queries)
        if swing:
            self.frame = JFrame("Neofelis")
            self.frame.addWindowListener(PipelineWindowAdapter(self))
            contentPane = JPanel(GridBagLayout())
            self.frame.setContentPane(contentPane)
            self.globalLabel = JLabel(max(queries, key=len))
            self.globalProgress = JProgressBar(0, self.numJobs)
            self.currentLabel = JLabel(max(self.messages, key=len))
            self.currentProgress = JProgressBar(0, len(self.messages))
            self.doneButton = JButton(DoneAction(self.frame))
            self.doneButton.setEnabled(False)

            constraints = GridBagConstraints()

            constraints.gridx, constraints.gridy = 0, 0
            constraints.gridwidth, constraints.gridheight = 1, 1
            constraints.weightx = 1
            constraints.fill = GridBagConstraints.HORIZONTAL
            contentPane.add(self.globalLabel, constraints)
            constraints.gridy = 1
            contentPane.add(self.globalProgress, constraints)
            constraints.gridy = 2
            contentPane.add(self.currentLabel, constraints)
            constraints.gridy = 3
            contentPane.add(self.currentProgress, constraints)
            constraints.gridy = 4
            constraints.weightx = 0
            constraints.fill = GridBagConstraints.NONE
            constraints.anchor = GridBagConstraints.LINE_END
            contentPane.add(self.doneButton, constraints)

            self.frame.pack()
            self.frame.setResizable(False)
            self.globalLabel.setText(" ")
            self.currentLabel.setText(" ")
            self.frame.setLocationRelativeTo(None)
            self.frame.setVisible(True)

    def updateProgress(self, job):
        """
    query: Name of the query currently being processed.
    
    This function use used for updating the progress shown in the interface.  If job is not equal to currentJob then
    global progress is incremented and shown and the currentProgress is reset and shown.  If job is equal to currentJob
    then the globalProgress does not change and currentProgress is incremented.
    """
        if self.exception:
            raise self.exception

        if self.frame:
            if job != self.currentJob:
                self.currentProgress.setValue(
                    self.currentProgress.getMaximum())
                self.globalLabel.setText(job)
                self.globalProgress.setValue(self.jobCount)
                print "Processing %s, %.2f%% done" % (
                    job, 100.0 * self.jobCount / self.numJobs)
                self.jobCount += 1
                self.currentJob = job
                self.message = -1
            self.message += 1
            print "    %s, %.2f%% done" % (self.messages[self.message], 100.0 *
                                           self.message / len(self.messages))
            self.currentProgress.setValue(self.message)
            self.currentLabel.setText(self.messages[self.message])
        else:
            if job != self.currentJob:
                print "Processing %s, %.2f%% done" % (
                    job, 100.0 * self.jobCount / self.numJobs)
                self.jobCount += 1
                self.currentJob = job
                self.message = -1
            self.message += 1
            print "    %s, %.2f%% done" % (self.messages[self.message], 100.0 *
                                           self.message / len(self.messages))

    def finished(self):
        """
    This function is to be called at the end of the pipeline.  Informs the user that the pipeline is finished
    and if a swing interface is being used the Done button is enabled.
    """
        print "Processing 100.00% done"
        if self.frame:
            self.globalLabel.setText("Finished")
            self.globalProgress.setValue(self.globalProgress.getMaximum())
            self.currentLabel.setText(" ")
            self.currentProgress.setValue(self.currentProgress.getMaximum())
            self.doneButton.setEnabled(True)
            while self.frame.isVisible():
                pass

    def run(self,
            blastLocation,
            genemarkLocation,
            transtermLocation,
            database,
            eValue,
            matrix,
            minLength,
            scaffoldingDistance,
            ldfCutoff,
            queries,
            swing=False,
            email=""):
        """
    blastLocation:       Directory blast was installed in.
    genemarkLocation:    Directory genemark was installed in.
    transtermLocation:   Directory transterm was installed in.
    database:            Name of the blast database to use.
    eValue:              The e value used whenever a blast search is done.
    matrix:              The matrix to use when running genemark.  If None then genemark is run heuristically.
    minLength:           Minimum length of any genes included in the resulting annotation.
    scaffoldingDistance: The maximum length allowed between genes when contiguous regions of genes are being identified
    ldfCutoff:           Minimum LDF allowed for any promoters included in the resulting annotation
    queries:             A list of faster files to process.
    swing:               If true a swing window will be used to updated the user about the pipeline's progress.
    email:               If this is a non-empty string an email will be sent to the address in the string when the pipeline is done.  The local machine will be used as
                         an SMTP server and this will not work if it isn't.
    
    The main pipeline function.  For every query genemark is used to predict genes, these genes are then extended to any preferable starts.  Then the pipeline searches
    for any intergenic genes(genes between those found by genemark) and these are combined with the extended genemark genes.  Then the genes are pruned to remove
    any undesirable genes found in the intergenic stage.  BPROM and Transterm are used to find promoters and terminators, which are then pruned to remove any
    signals which are inside or too far away from any genes.  Finally, all the remaining genes, promoters, and terminators ar written to an artemis file in the directory
    of the query with the same name but with a .art extension, and .dat and .xls files will be generating describing the blast results of the final genes.
    """
        self.initializeDisplay(queries, swing)

        try:
            for query in queries:
                name = os.path.splitext(query)[0]
                queryDirectory, name = os.path.split(name)

                genome = utils.loadGenome(query)
                swapFileName = "query" + str(id(self)) + ".fas"
                queryFile = open(swapFileName, "w")
                queryFile.write(">" + name + "\n")
                for i in range(0, len(genome), 50):
                    queryFile.write(genome[i:min(i + 50, len(genome))] + "\n")
                queryFile.close()

                self.updateProgress(query)
                initialGenes = genemark.findGenes(swapFileName, name,
                                                  blastLocation, database,
                                                  eValue, genemarkLocation,
                                                  matrix, self)
                #artemis.writeArtemisFile(os.path.splitext(query)[0] + ".genemark.art", genome, initialGenes.values())

                self.updateProgress(query)
                extendedGenes = extend.extendGenes(swapFileName, initialGenes,
                                                   name, blastLocation,
                                                   database, eValue, self)
                #artemis.writeArtemisFile(os.path.splitext(query)[0] + ".extended.art", genome, extendedGenes.values())

                self.updateProgress(query)
                intergenicGenes = intergenic.findIntergenics(
                    swapFileName, extendedGenes, name, minLength,
                    blastLocation, database, eValue, self)
                #artemis.writeArtemisFile(os.path.splitext(query)[0] + ".intergenic.art", genome, intergenicGenes.values())
                genes = {}
                for k, v in extendedGenes.items() + intergenicGenes.items():
                    genes[k] = v

                self.updateProgress(query)
                scaffolded = scaffolds.refineScaffolds(genes,
                                                       scaffoldingDistance)

                self.updateProgress(query)
                initialPromoters = promoters.findPromoters(swapFileName, name)

                self.updateProgress(query)
                initialTerminators = terminators.findTerminators(
                    swapFileName, name, genes.values(), transtermLocation)

                self.updateProgress(query)
                filteredSignals = signals.filterSignals(
                    scaffolded.values(), initialPromoters + initialTerminators)
                filteredPromoters = filter(
                    lambda x: isinstance(x, promoters.Promoter),
                    filteredSignals)
                filteredTerminators = filter(
                    lambda x: isinstance(x, terminators.Terminator),
                    filteredSignals)

                self.updateProgress(query)
                artemis.writeArtemisFile(
                    os.path.splitext(query)[0] + ".art", genome,
                    scaffolded.values(), filteredPromoters,
                    filteredTerminators)

                self.updateProgress(query)
                report.report(name, scaffolded, os.path.splitext(query)[0])

            if email:
                message = MIMEText("Your genome has been annotated.")
                message["Subject"] = "Annotation complete"
                message["From"] = "Neofelis"
                message["To"] = email

                smtp = smtplib.SMTP("tmpl.arizona.edu", 587)
                smtp.ehlo()
                smtp.starttls()
                smtp.ehlo
                smtp.sendmail("Neofelis", [email], message.as_string())
                smtp.close()

            self.finished()
        except PipelineException:
            return
예제 #17
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)
    def output(self, value):
        eingabe = value.getString()
        if eingabe == "Lexikon":
            # Falls "Lexikon" an den Clienten übergeben wird, wird die GUI geöffnet,
            # in der man deutsche Wörter eingeben kann, die einem dann auf Englisch
            # vorgelesen werden.
            def change_text(event):
                text = feld.getText()
                x = suche(text)
                self.send(x)
                frame.visible = False

            frame = JFrame(
                'Woerterbuch',
                defaultCloseOperation=JFrame.EXIT_ON_CLOSE,
                size=(380, 350),
            )
            frame.setLayout(None)
            frame.visible = True
            hintergrund = ImageIcon("Hintergrund.jpg")
            hintergrundlabel = JLabel(hintergrund)
            frame.setContentPane(hintergrundlabel)

            uebersetzerlabel = JLabel()
            uebersetzerlabel.setForeground(Color(025, 025, 112))
            uebersetzerlabel.setText(
                "<html><font size=+1>Welches Wort soll ich uebersetzen?</font></html>"
            )
            uebersetzerlabel.setBounds(10, 20, 500, 50)
            frame.add(uebersetzerlabel)

            feld = JTextField()
            feld.setText("")
            feld.setBounds(20, 80, 300, 25)
            frame.add(feld)

            button = JButton('Uebersetzen',
                             actionPerformed=change_text,
                             size=(10, 20))
            button.setBounds(20, 110, 300, 30)
            frame.add(button)

        if eingabe == "neue Lektion":
            # Falls dem Clienten "neue Lektion" übergeben wird, öffnet er er die
            # GUI für das Verwalten der Lektionen
            frame = JFrame('Lektion erstellen',
                           defaultCloseOperation=JFrame.EXIT_ON_CLOSE,
                           size=(1000, 1000))
            frame.setLayout(None)

            def auflisten_in(ort):
                font = Font("Verdana", Font.BOLD, 15)
                liste_mit_Lektionen = []
                with open(pfad, "r") as f:
                    for line in f:
                        liste_mit_Lektionen.append(line.strip())
                liste_mit_Lektionen.sort()
                text = ""
                for lektion in liste_mit_Lektionen:
                    text += lektion
                    text += "\n"
                ort.setText(text)
                ort.setFont(font)
                frame.setLayout(None)
                uebersichtLabel = JLabel()

            def uebersetzen(event):
                frage = feld_frage.getText()
                x = suche(frage)
                feld_frage.setText(x)
                liste = []
                with open(pfad, "r") as lektionen:
                    for lektion in lektionen:
                        if "nachgeschlagen" in lektion:
                            liste.append(lektion)
                if liste:
                    name = liste[-1]
                    words = []
                    sql = "SELECT deutsch, englisch, symbol FROM " + name
                    zeile = stmt.executeQuery(sql)
                    while zeile.next():
                        d = zeile.getString("deutsch")
                        e = zeile.getString("englisch")
                        symb = zeile.getString("symbol")
                        words.append((d, e, symb))
                    if len(words) < 50:
                        sql = "INSERT INTO " + name + " (deutsch, englisch, symbol)  VALUES(?,?,?);"
                        pstmt = conn.prepareStatement(sql)
                        pstmt.setString(1, frage)
                        pstmt.setString(2, x)
                        pstmt.setString(3, "X")
                        pstmt.executeUpdate()
                    else:
                        namensteile = name.split("_")
                        nummer = int(namensteile[1].strip()) + 1
                        name = "nachgeschlagen_" + str(nummer)
                        test = ""
                        with open(pfad, "r") as f:
                            for line in f:
                                test += line
                        if not name in test:
                            with open(pfad, "a") as f:
                                f.write(name + "\n")
                        sql = "CREATE TABLE " + name + " (deutsch text, englisch text, symbol text);"
                        stmt.execute(sql)
                        sql = "INSERT INTO " + name + " (deutsch, englisch, symbol)  VALUES(?,?,?);"
                        pstmt = conn.prepareStatement(sql)
                        pstmt.setString(1, frage)
                        pstmt.setString(2, x)
                        pstmt.setString(3, "X")
                        pstmt.executeUpdate()
                else:
                    name = "nachgeschlagen_1"
                    test = ""
                    with open(pfad, "r") as f:
                        for line in f:
                            test += line
                    if not name in test:
                        with open(pfad, "a") as f:
                            f.write(name + "\n")
                    sql = "CREATE TABLE " + name + " (deutsch text, englisch text, symbol text);"
                    stmt.execute(sql)
                    sql = "INSERT INTO " + name + " (deutsch, englisch, symbol)  VALUES(?,?,?);"
                    pstmt = conn.prepareStatement(sql)
                    pstmt.setString(1, frage)
                    pstmt.setString(2, x)
                    pstmt.setString(3, "X")
                    pstmt.executeUpdate()
                auflisten_in(uebersicht)

            def delete(event):
                name = feld.getText()
                print name
                print self.geladen
                if name == self.geladen:
                    count = 0
                    while tabelle.getValueAt(count, 0) != None:
                        tabelle.setValueAt(None, count, 0)
                        tabelle.setValueAt(None, count, 1)
                        count += 1
                stmt.execute("DROP TABLE " + name + ";")
                lektionen = []
                with open(pfad, "r") as f:
                    for line in f:
                        lektion = line.strip()
                        if not name == lektion:
                            lektionen.append(lektion)
                with open(pfad, "w") as f:
                    for lektion in lektionen:
                        f.write(lektion + "\n")
                auflisten_in(uebersicht)

            def laden(event):
                name = feld.getText()
                self.geladen = name
                sql = "SELECT deutsch, englisch FROM " + name
                results = stmt.executeQuery(sql)
                count = 0
                while results.next():
                    d = results.getString("deutsch")
                    e = results.getString("englisch")
                    tabelle.setValueAt(d, count, 0)
                    tabelle.setValueAt(e, count, 1)
                    count += 1
                while tabelle.getValueAt(count, 0) != None:
                    tabelle.setValueAt(None, count, 0)
                    tabelle.setValueAt(None, count, 1)
                    count += 1

            def erstelle_Lektionstabelle(event):
                reihen = []
                for i in range(0, 50):
                    deutsch = tabelle.getValueAt(i, 0)
                    englisch = tabelle.getValueAt(i, 1)
                    if deutsch != None:
                        symbol = "X"
                        reihen.append([deutsch, englisch, symbol])
                    else:
                        break
                z = 0
                name = feld.getText()
                sql = "CREATE TABLE " + name + " (deutsch text, englisch text, symbol text);"
                try:
                    stmt.execute(sql)
                except SQLError:
                    stmt.execute("DROP TABLE " + name + ";")
                    stmt.execute(sql)
                for reihe in reihen:
                    print(reihe)
                    deutsch = reihe[0]
                    englisch = reihe[1]
                    symbol = reihe[2]
                    sql = "INSERT INTO " + name + " (deutsch, englisch, symbol)  VALUES(?,?,?);"
                    pstmt = conn.prepareStatement(sql)
                    pstmt.setString(1, deutsch)
                    pstmt.setString(2, englisch)
                    pstmt.setString(3, symbol)
                    pstmt.executeUpdate()
                test = ""
                with open(pfad, "r") as f:
                    for line in f:
                        test += line
                if not name in test:
                    with open(pfad, "a") as f:
                        f.write(name + "\n")
                self.send(name)
                frame.setVisible(False)

            frame = JFrame('Vokabel Listen',
                           defaultCloseOperation=JFrame.EXIT_ON_CLOSE,
                           size=(1000, 1000))
            frame.setLayout(None)
            label_enter = JLabel()
            label_enter.setText(
                "<html><font size=+0.5 color = 000000>Bitte vor dem Speichern<br>die Entertaste bedienen</font></html>"
            )
            label_enter.setBounds(20, 720, 250, 50)
            uebersichtLabel = JLabel()
            uebersichtLabel.setText(
                "<html><font size=+1 color=#191970>Bereits vorhandene Lektionen:</font></html>"
            )
            uebersichtLabel.setBounds(450, 230, 250, 50)
            uebersicht = JTextArea()
            uebersicht.editable = False
            uebersicht_scroll = JScrollPane(uebersicht)
            uebersicht_scroll.viewport.view = uebersicht
            uebersicht_scroll.setBounds(450, 300, 250, 380)
            auflisten_in(uebersicht)
            button = JButton('Lektion speichern/Lektion reseten',
                             actionPerformed=erstelle_Lektionstabelle,
                             size=(10, 20))
            button.setBounds(20, 700, 300, 30)
            button_laden = JButton('vorhandene Lektion laden',
                                   actionPerformed=laden,
                                   size=(10, 20))
            button_laden.setBounds(20, 110, 210, 30)
            button_delete = JButton("Lektion entfernen",
                                    actionPerformed=delete)
            button_delete.setBounds(20, 140, 210, 30)
            hintergrund = ImageIcon("Hintergrund.jpg")
            pnl = JPanel()
            hintergrundlabel = JLabel(hintergrund)
            frame.setContentPane(hintergrundlabel)
            lektionsnamensLabel = JLabel()
            lektionsnamensLabel.setForeground(Color(025, 025, 112))
            lektionsnamensLabel.setText(
                "<html><font size=+1>Hier bitte Namen der Lektion eingeben<br>(Nur ein Wort lang)</font></html>"
            )
            lektionsnamensLabel.setBounds(10, 20, 500, 50)
            frame.add(lektionsnamensLabel)
            feld = JTextField()
            feld.setText("")
            feld.setBounds(20, 80, 210, 25)
            frame.add(feld)
            column_names = [
                "<html><font size=+1 color=#191970><b>Deutsch</b></font></html>",
                "<html><font size=+1 color=#191970><b>Englisch</b></font></html>"
            ]
            table_model = DefaultTableModel(column_names, 50)
            tabelle = JTable(table_model)
            lektionsnamensLabel.setForeground(Color(025, 025, 112))
            scrollbar = JScrollPane(tabelle)
            scrollbar.viewport.view = tabelle
            scrollbar.setVerticalScrollBarPolicy(
                scrollbar.VERTICAL_SCROLLBAR_ALWAYS)
            scrollbar.setVisible(True)
            tabelle.setVisible(True)
            scrollbar.setBounds(20, 190, 300, 490)
            feld_frage = JTextField()
            feld_frage.setText("")
            feld_frage.setBounds(450, 30, 300, 50)
            uebersetzerlabel = JLabel()
            uebersetzerlabel.setForeground(Color(025, 025, 112))
            uebersetzerlabel.setText(
                "<html><font size=+1>Hier kannst Du ein deutsches Wort eintragen,<br>dass ich fuer Dich nachschlage</font></html>"
            )
            uebersetzerlabel.setBounds(450, 80, 500, 50)
            button_uebersetzen = JButton('Uebersetzen',
                                         actionPerformed=uebersetzen,
                                         size=(10, 20))
            button_uebersetzen.setBounds(450, 130, 300, 30)
            frame.add(button_uebersetzen)
            frame.add(uebersetzerlabel)
            frame.add(feld_frage)
            frame.add(feld)
            frame.add(scrollbar)
            frame.add(button)
            frame.add(button_laden)
            frame.setVisible(True)
            frame.add(uebersicht_scroll)
            frame.add(uebersichtLabel)
            frame.add(button_delete)
            frame.add(label_enter)
        elif eingabe == "alle Lektionen auflisten":
            # Hier erstellt der Client eine dynamische Grammatik
            # mit den vorhandenen Lektionen, die man sich abfragen lassen kann
            # und gibt diese wieder an DialogOS zurück.
            # Außerdem wird der Feedback Frame geöffnet.
            def auflisten_in2(ort):
                font = Font("Verdana", Font.BOLD, 15)
                liste_mit_Lektionen = []
                with open(pfad, "r") as f:
                    for line in f:
                        liste_mit_Lektionen.append(line.strip())
                        liste_mit_Lektionen.sort()
                text = ""
                for lektion in liste_mit_Lektionen:
                    text += lektion
                    text += "\n"
                ort.setText(text)
                ort.setFont(font)

            frame_feedback.setVisible(True)
            auflisten_in2(uebersicht2)
            grammatik = ""
            grammatik = "root $NamevonLektion;\n"
            grammatik += "$NamevonLektion = "
            with open(pfad, "r") as f:
                z = 0
                for line in f:
                    if z == 0:
                        if not "_" in line:
                            grammatik += line
                        else:
                            zeile = line.split("_")
                            grammatik += zeile[0] + " "
                            grammatik += zeile[1].strip()
                    else:
                        if not "_" in line:
                            grammatik += "|" + line
                        else:
                            zeile = line.split("_")
                            grammatik += "|" + zeile[0] + " "
                            grammatik += zeile[1].strip()
                    if line != "\n":
                        z += 1
            grammatik += ";"
            self.send(grammatik)
        elif "sende" in eingabe:
            # DialogOS sagt dem Clienten, welche Lektion der User abgefragt
            # werden möchte. Der Client ließt dann die entsprechende Lektion
            # aus der Datenbank aus und gibt eine Liste mit 2 Listen zurück.
            # In der ersten Liste befinden sich die deutschen Bedeutungen, der
            # noch nicht gewussten Wörter, in der 2. Liste die englsichen Bedeutungen.
            # Falls alle Wörter bereits gekonnt wurden, wird stattdessen eine entsprechende
            # Anmerkung an DialogOS geschickt und DialogOS informiert den User darüber.
            z = 0
            if "nachgeschlagen" in eingabe:
                bestandteile = eingabe.split()
                name = bestandteile[1] + "_" + bestandteile[2]
            else:
                name = eingabe.split()[1]
            sql = "SELECT deutsch, englisch, symbol FROM " + name
            vokabelliste = stmt.executeQuery(sql)
            deutsch = []
            englisch = []
            symbol = []
            while (vokabelliste.next()):
                deutsch.append(vokabelliste.getString("deutsch"))
                englisch.append(vokabelliste.getString("englisch"))
                symbol.append(vokabelliste.getString("symbol"))

            indices = range(0, len(deutsch))
            random.shuffle(indices)
            vokabeln = [[], []]
            for index in indices:
                d = deutsch[index]
                e = englisch[index]
                s = symbol[index]
                if s == "X":
                    vokabeln[0].append(d)
                    vokabeln[1].append(e)
            if vokabeln[0]:
                self.send(vokabeln)
            else:
                self.send([
                    "Du kannst diese Lektion schon komplett. Wenn Du sie wieder abgefragt werden willst, resete sie bitte unter Wokabeln verwalten."
                ])
        else:
            # Dieser Teil des Codes wird während der Abfrage ausgeführt.
            # Nach jeder neuen Vokabel wird dann in ein Feld im Feedback
            # Frame die deutsche, die englische Vokabel und ein Symbol angezeigt,
            # welches einen darüber informiert, ob man die Vokabel wusste, oder nicht.
            # (O für gewusst und X für nicht gewusst)
            nametext = eingabe.split(":")
            name = nametext[0]
            text = nametext[1]
            feld_feedback.setText(text)
            zeilen = text.split("\n")
            symb = zeilen[-2].split("\t")[-1]
            d = zeilen[-2].split("\t")[-3]
            print d
            sql = "UPDATE " + name + " SET symbol = ? WHERE deutsch = ?"
            pstmt = conn.prepareStatement(sql)
            pstmt.setString(1, symb)
            pstmt.setString(2, d)
            pstmt.executeUpdate()
예제 #19
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()]
예제 #20
0
logo.setLocation(0, 145)
#logo.setOpaque(True)

namaLabel = JLabel(
    "<html><center>ERWIN M H SINAGA<br>111401067</center></html>",
    JLabel.CENTER)
namaLabel.setFont(theFont)
namaLabel.setSize(610, 50)
namaLabel.setLocation(0, 360)
#namaLabel.setOpaque(True)

prodiLabel = JLabel(
    "<html><center>PROGRAM STUDI S1 ILMU KOMPUTER<br> \
                    FAKULTAS ILMU KOMPUTER DAN TEKNOLOGI INFORMASI<br> \
                    UNIVERSITAS SUMATERA UTARA<br> \
                    MEDAN<br> \
                    2017</center></html>", JLabel.CENTER)
prodiLabel.setFont(theFont)
prodiLabel.setSize(610, 162)
prodiLabel.setLocation(0, 410)
#prodiLabel.setOpaque(True)

aboutForm.locationByPlatform = True
aboutPanel.add(judul1Label)
aboutPanel.add(skripsiLabel)
aboutPanel.add(logo)
aboutPanel.add(namaLabel)
aboutPanel.add(prodiLabel)
#aboutPanel.setOpaque(True)
aboutForm.setContentPane(aboutPanel)  # add(aboutPanel)
aboutForm.visible = True
예제 #21
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
scrollPanePTx = JScrollPane(pesanAsli)
pesanAsli.setColumns(100)
pesanAsli.setRows(200)

pesanTerenkripsi = awt.TextArea("n/a", 5, 30)
pesanTerenkripsi.setLocation(647, 114)
pesanTerenkripsi.setSize(258, 400)
pesanTerenkripsi.setBackground(Color.GRAY)
pesanTerenkripsi.setFont(subSpecialFont)
pesanTerenkripsi.setEditable(False)
scrollPaneCTx = JScrollPane(pesanTerenkripsi)
pesanTerenkripsi.setColumns(100)
pesanTerenkripsi.setRows(200)

# All Form Belong Here
naiveForm.setContentPane(naiveFormPanel)
naiveForm.locationByPlatform = True

# Put Objects Altogether on Panel
naiveFormPanel.add(naiveHeader, BorderLayout.CENTER)
naiveForm.add(myTabbedPane)
naiveFormPanel.add(primaLabel)
naiveFormPanel.add(aphaLabel)
naiveFormPanel.add(bitPrimaLabel)
naiveFormPanel.add(label1)
naiveFormPanel.add(betaLabel)
naiveFormPanel.add(bitPrima)
naiveFormPanel.add(genPrima)
naiveFormPanel.add(alpha)

alpha.text = "20135"