예제 #1
0
def complex_console():
    global frame
    #generates frame
    frame = JFrame("[BETA] Game Master\'s Bot - Console Log")
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
    frame.setResizable(False)
    frame.setAlwaysOnTop(True)
    frame.setBounds(8,545,600,130)
    frame.contentPane.layout = FlowLayout()
    
    #add QUIT button
    quitButton = JButton("QUIT", actionPerformed = closeFrame)
    quitButton.setForeground(Color.RED)
    quitButton.setPreferredSize(Dimension(100,100))
    frame.contentPane.add(quitButton)
    
    #add text message
    global textArea
    textArea = JTextArea(6,38)
    textArea.setEditable(False)
    frame.contentPane.add(textArea)
    scrollPane = JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)
    frame.contentPane.add(scrollPane)
    
    #show frame
    frame.pack()
    frame.setVisible(True)
    log("Welcome to Game Master\'s Bot!")
예제 #2
0
    def onInfo(self, e):
        info = JFrame()
        info.setTitle("Info")
        info.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)
        info.setSize(410, 400)
        info.setLocationRelativeTo(None)
        info.setResizable(False)
        info.setVisible(True)

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

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

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

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

        info.getContentPane().add(panel)
        info.add(panel)
예제 #3
0
    def bg(self, panel2, e):
        bground = JFrame()
        bground.setTitle("Change Background")
        bground.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)
        bground.setSize(350, 100)
        bground.setLocationRelativeTo(None)
        bground.setVisible(True)
        bground.setResizable(False)

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

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

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

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

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

        bground.add(panel)
예제 #4
0
파일: Main.py 프로젝트: sedjrodonan/lositan
def createFrame():
    global isDominant
    manager = doAction()
    if isTemporal:
        frame = JFrame("LosiTemp - LOoking for Selection In TEMPoral datasets")
    elif isDominant:
        frame = JFrame("Mcheza - Dominant Selection Workbench")
    else:
        frame = JFrame("LOSITAN - Selection Workbench")
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    doPrettyType(frame, manager)
    frame.setVisible(1)
    frame.setResizable(0)
    return frame
예제 #5
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)
예제 #6
0
    def onExit(self, e):
        exit = JFrame()
        exit.setTitle("Exit Stylus")
        exit.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)
        exit.setSize(250, 225)
        exit.setLocationRelativeTo(None)
        exit.setVisible(True)
        exit.setResizable(False)

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

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

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

        exit.add(panel)
예제 #7
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)
예제 #8
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
class FilamentGame_ModelEditor(EditorExtension, JPanel, MouseListener, MouseMotionListener):
    def getExtensionName(self):
        return "Filament Model Tool"

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

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

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

    def setupGui(self):

        cPanel = JPanel()

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

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

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

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

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

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

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

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

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

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

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

    def mouseEntered(self, e):
        return

    def mouseExited(self, e):
        return

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

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

        y = h - p.y

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

        return [x, y]

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

    def mouseMoved(self, e):
        return

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

    def update(self, delta):
        return
예제 #10
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)
예제 #11
0
    def guiFrame(self):

        frame = JFrame("PyNews")
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        frame.setLocationRelativeTo(None)
        frame.setSize(600, 200)
        frame.setResizable(False)

        frame.setLayout(GridLayout(5, 3, 10, 10))

        # logo
        self.logo = JLabel("  PyNews")

        # query input
        self.input_field = JTextField(30)

        # search button
        self.src_button = JButton("Search!", actionPerformed=self.pyNewsSearch)

        # expand button
        self.exp_button = JButton("Expand!", actionPerformed=self.expandNews)
        self.exp_button.setEnabled(False)

        # open button
        self.opn_button = JButton("Open!", actionPerformed=self.openNews)
        self.opn_button.setEnabled(False)

        # open html button
        self.htm_button = JButton("HTML-Open!", actionPerformed=self.openHTML)
        self.htm_button.setEnabled(False)

        # write to file button
        self.wrt_button = JButton("CSV-Write!",
                                  actionPerformed=self.writeToCSV)
        self.wrt_button.setEnabled(False)

        # checkboxes
        self.categories = [
            "authors", "publish_date", "top_image", "movies", "text",
            "article_html", "summary", "keywords"
        ]
        self.checkboxes = []

        for cat in self.categories:
            self.checkboxes.append(JCheckBox(cat))

        # add to frame

        frame.add(self.logo)
        frame.add(self.input_field)
        frame.add(self.src_button)
        frame.add(self.exp_button)
        for cb in self.checkboxes[:2]:
            frame.add(cb)
        frame.add(self.opn_button)
        for cb in self.checkboxes[2:4]:
            frame.add(cb)
        frame.add(self.htm_button)
        for cb in self.checkboxes[4:6]:
            frame.add(cb)
        frame.add(self.wrt_button)
        for cb in self.checkboxes[6:8]:
            frame.add(cb)
        print("got to end ")
        frame.setVisible(True)
예제 #12
0
        while results.next():
            i += 1
            #logger.debug("%s" % results)

            logger.debug("%s : %s" % (results.getString("TABLE_NAME"), results.getString("TABLE_TEXT")))

            #logger.debug("%s : %s [%s]" % (results.getString("COLUMN_NAME"), results.getString("COLUMN_TEXT"), results.getString("TYPE_NAME")))

            if i == 1000:
                exit()

        logger.debug("Success!")

def exit_all(event):
    exit

if __name__ == "__main__":
    f = JFrame('Hello, Jython!', defaultCloseOperation = JFrame.EXIT_ON_CLOSE, size = (550, 200))

    f.setResizable(True)

    b = JButton('Connect!', actionPerformed=change_text)
    #d = JButton('Exit!!', actionPerformed=exit_all)

    c = f.getContentPane()
    c.setBackground(Color.DARK_GRAY)
    c.add(b)
    #c.add(d)

    f.setVisible(True)
예제 #13
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
예제 #14
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)
예제 #15
0
# Ensure we have an APIKEY
elif APIKEY == "":
    show_error_message("VirusTotal API key must be set.")
# Initial checks good, lets run the script
else:
    global cancelled
    cancelled = False

    # Do some UI setup here to keep the main() method a little easier to read
    jframe = JFrame("VirusTotal Integration",
                    defaultCloseOperation=JFrame.DISPOSE_ON_CLOSE,
                    size=(300, 100),
                    locationRelativeTo=None)
    jframe.setUndecorated(True)
    statusLabel = JLabel("", JLabel.CENTER)
    jframe.setResizable(False)
    jframe.setLayout(GridLayout(3, 1))
    statusLabel.setSize(300, 50)
    jframe.getContentPane().add(statusLabel)
    jbutton = JButton('Cancel')
    jbutton.addActionListener(cancel)

    # Run the main code function
    result = main()

    # Clean up jframe and show the result message
    jframe.setVisible(False)
    jframe.dispose()
    if result:
        JOptionPane.showMessageDialog(None, result)