Esempio n. 1
0
def updateProjections(projection):
    from com.raytheon.uf.common.dataplugin.gfe.config import ProjectionData
    # extract projection data
    projFmt = (
        str,
        "com.raytheon.uf.common.dataplugin.gfe.config.ProjectionData$ProjectionType",
        tuple, tuple, tuple, float, float, tuple, tuple, float, float, float)
    projID, ptype, pllll, pllur, pllo, pspo, pspt, pgpll, pgpur, pli, \
      plc, plo = check(projection, projFmt, "Format error in Projection")
    check(pllll, (float, float),
          "Format error lower left long/lat in Projection", projection)
    check(pllur, (float, float),
          "Format error upper right long/lat in Projection", projection)
    check(pllo, (float, float), "Format error long/lat origin in Projection",
          projection)
    check(pgpll, (int, int),
          "Format error lower left grid point in Projection", projection)
    check(pgpur, (int, int),
          "Format error upper right grid point in Projection", projection)

    if not Projections.has_key(projID):
        Projections[projID] = ProjectionData(projID, ptype,
                                             Coordinate(pllll[0], pllll[1]),
                                             Coordinate(pllur[0], pllur[1]),
                                             Coordinate(pllo[0],
                                                        pllo[1]), pspo, pspt,
                                             Point(pgpll[0], pgpll[1]),
                                             Point(pgpur[0], pgpur[1]), pli,
                                             plc, plo)
Esempio n. 2
0
 def stateChanged(self, ce):
     vPort = ce.getSource()
     table = self.table
     rect = vPort.getViewRect()
     first = table.rowAtPoint(Point(0, rect.y))
     last = table.rowAtPoint(Point(0, rect.y + rect.height - 1))
     print 'rows: %d..%d  isValid: %d' % (first, last, vPort.isValid())
Esempio n. 3
0
 def act(self):
     global xMap
     global dx
     xMap += dx
     if xMap == xMapStart or xMap == xMapEnd:
         dx = -dx
     tm.setPosition(Point(xMap, yMapStart))
Esempio n. 4
0
    def get_viewport_carets(self):
        '''
        Get the top left and bottom left caret position of the current viewport
        '''
        extent = self.container.getViewport().getExtentSize()
        top_left_position = self.container.getViewport().getViewPosition()
        top_left_char = self.edit_area.viewToModel(top_left_position)
        bottom_left_position = Point(top_left_position.x,
                                     top_left_position.y + extent.height)
        bottom_left_char = self.edit_area.viewToModel(bottom_left_position)

        # Something has gone wrong. Assume that top_left should be at the start
        # of the file
        if top_left_char >= bottom_left_char:
            top_left_char = 0

        # Get the text in the full edit area
        text = self.controller.edit_area.getText()

        # Pad the top of the viewport to capture up to the nearest header and
        # the bottom by 2 lines
        top_ch = self.controller.pad_top_viewport_caret(top_left_char, text)
        bottom_ch = self.controller.pad_bottom_viewport_caret(
            bottom_left_char, text)

        return top_ch, bottom_ch
Esempio n. 5
0
    def run(self):

        #-----------------------------------------------------------------------
        # Starting width, height & location of the application frame
        #-----------------------------------------------------------------------
        screenSize = Toolkit.getDefaultToolkit().getScreenSize()
        w = screenSize.width >> 1  # Use 1/2 screen width
        h = screenSize.height >> 1  # and 1/2 screen height
        x = (screenSize.width - w) >> 1  # Top left corner of frame
        y = (screenSize.height - h) >> 1

        #-----------------------------------------------------------------------
        # Center the application frame in the window
        #-----------------------------------------------------------------------
        frame = self.frame = JFrame('WASports_02',
                                    bounds=(x, y, w, h),
                                    defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        #-----------------------------------------------------------------------
        # Internal frames require us to use a JDesktopPane()
        #-----------------------------------------------------------------------
        desktop = JDesktopPane()

        #-----------------------------------------------------------------------
        # Create our initial internal frame, and add it to the desktop
        #-----------------------------------------------------------------------
        internal = InternalFrame('InternalFrame',
                                 size=Dimension(w >> 1, h >> 1),
                                 location=Point(5, 5))
        desktop.add(internal)

        frame.setContentPane(desktop)
        frame.setVisible(1)
Esempio n. 6
0
    def __init__(self, migLayoutSettings=""):
        self.setLayout(MigLayout(migLayoutSettings))

        self.initialClick = Point(0, 0)
        self.setOpaque(False)
        self.setBackground(Color(0, 30, 0, 40))
        #self.setBorder(BorderFactory.createLineBorder(Color.RED))

        self.initUI()
        self.addUI()

        class MouseAdap(MouseAdapter):
            def mousePressed(ms, m):
                self.initialClick = m.getPoint()

        class MouseMotionAdap(MouseMotionAdapter):
            def mouseDragged(ms, m):
                window = SwingUtilities.getWindowAncestor(self)
                x = window.getLocation().x
                y = window.getLocation().y
                xm = (x + m.getX()) - (x + self.initialClick.x)
                ym = (y + m.getY()) - (y + self.initialClick.y)
                window.setLocation(x + xm, y + ym)

        self.addMouseListener(MouseAdap())
        self.addMouseMotionListener(MouseMotionAdap())

        self.setVisible(True)
Esempio n. 7
0
 def select(e):
     rowAtPoint = self.resultTable.rowAtPoint(
         SwingUtilities.convertPoint(self.resultTablePopupMenu,
                                     Point(0, 0), self.resultTable))
     if rowAtPoint > -1:
         self.resultTable.setRowSelectionInterval(
             rowAtPoint, rowAtPoint)
 def actionPerformed( self, actionEvent ) :
     table = self.table
     self.original.actionPerformed( actionEvent )
     #-----------------------------------------------------------------------
     # Unfortunately, tables with variable row heights don't reposition to
     # the end of table correctly the first time, especially from top row.
     #-----------------------------------------------------------------------
     if self.action == 'selectLastRow' :
         self.original.actionPerformed( actionEvent )
     #-----------------------------------------------------------------------
     # Since the JTable() is within a JScrollPane, its parent is a JViewport
     # Determine which table rows are currently visible in that viewport.
     #-----------------------------------------------------------------------
     vPort = table.getParent()
     rect  = vPort.getViewRect()
     #-----------------------------------------------------------------------
     # We don't want to realign the viewport if the selected row is already
     # completely visible in the viewport.  So, check for this first.
     #-----------------------------------------------------------------------
     row = table.getSelectedRow()
     if row > -1 :
         cRect = table.getCellRect( row, 0, 1 )
         if rect.y <= cRect.y and rect.y + rect.height >= cRect.y + cRect.height :
             return
     #-----------------------------------------------------------------------
     # Partial rows are likely, so we want to realign the table, within the
     # viewport, to align either the top row with the top of the viewport, or
     # the bottom row with the bottom of the viewport, depending upon the
     # kind of direction key (i.e., Up, or Down) that was pressed.
     #-----------------------------------------------------------------------
     if self.up :
         first = table.rowAtPoint( Point( 0, rect.y ) )
         cell  = table.getCellRect( first, 0, 1 )
         diff  = rect.y - cell.y
     else :
         if row > -1 :
             cell  = table.getCellRect( row, 0, 1 )
         else :
             last  = table.rowAtPoint( Point( 0, rect.y + rect.height - 1 ) )
             cell  = table.getCellRect( last, 0, 1 )
         bot   = rect.y + rect.height
         end   = cell.y + cell.height
         diff  = end - bot
     point = vPort.getViewPosition() 
     vPort.setViewPosition(
         Point( point.x, point.y + diff )
     )
Esempio n. 9
0
def roiPoints(roi):
    """ Return the list of 2D coordinates for pixels inside the ROI. """
    if isinstance(roi, PointRoi):
        return roi.getContainedPoints()
    # Else, one Point per non-zero pixel in the mask
    bounds = roi.getBounds()
    mask = roi.getMask()
    x, y, width, height = bounds.x, bounds.y, bounds.width, bounds.height
    if mask:
        return [
            Point(x + i % width, y + i / width)
            for i, v in enumerate(mask.getPixels()) if 0 != v
        ]
    # Else, e.g. Rectangle ROI
    return [
        Point(x + i % width, y + i / width) for i in xrange(width * height)
    ]
Esempio n. 10
0
    def getDisplayPoint(self):
        """Get the point where the popup window should be displayed"""
        screenPoint = self.output.getLocationOnScreen()
        caretPoint = self.output.caret.getMagicCaretPosition()

        # TODO use SwingUtils to do this translation
        x = screenPoint.getX() + caretPoint.getX() + self.dotWidth
        y = screenPoint.getY() + caretPoint.getY() + self.textHeight
        return Point(int(x), int(y))
Esempio n. 11
0
def parseGridLocation(domain):
    from com.raytheon.edex.plugin.gfe.config import SimpleGridLocation

    #if office type is present:
    if len(domain) == 6:
        domainFmt = (list, tuple, tuple, str, tuple, str)
        gridSize, origin, extent, tz, proj, officeType = check(
            domain, domainFmt, "Format error in SITES line")
    #if office type is not present:
    else:
        domainFmt = (list, tuple, tuple, str, tuple)
        gridSize, origin, extent, tz, proj = check(
            domain, domainFmt, "Format error in SITES line")
    check(gridSize, (int, int), "GridSize format error from SITES", domain)
    check(origin, (float, float), "Origin format error from SITES", domain)
    check(extent, (float, float), "Extent format error from SITES", domain)

    projFmt = (
        str,
        "com.raytheon.uf.common.dataplugin.gfe.config.ProjectionData$ProjectionType",
        tuple, tuple, tuple, float, float, tuple, tuple, float, float, float)
    projID, projType, llll, llur, llo, sp1, sp2, gpll, gpur, li, lc, lo = \
        check(proj, projFmt, "Format error in Projection")
    check(llll, (float, float),
          "Format error lower left long/lat in Projection", proj)
    check(llur, (float, float),
          "Format error upper right long/lat in Projection", proj)
    check(llo, (float, float), "Format error long/lat origin in Projection",
          proj)
    check(gpll, (int, int), "Format error lower left grid point in Projection",
          proj)
    check(gpur, (int, int),
          "Format error upper right grid point in Projection", proj)

    gloc = SimpleGridLocation(Point(gridSize[0], gridSize[1]),
                              Coordinate(origin[0], origin[1]),
                              Coordinate(extent[0],
                                         extent[1]), projID, projType,
                              Coordinate(llll[0], llll[1]),
                              Coordinate(llur[0], llur[1]),
                              Coordinate(llo[0], llo[1]), sp1, sp2,
                              Point(gpll[0], gpll[1]), Point(gpur[0], gpur[1]),
                              li, lc, lo)
    return gloc
Esempio n. 12
0
    def getDisplayPoint(self):
        """Get the point where the popup window should be displayed"""
        screenPoint = self.text_pane.getLocationOnScreen()
        caretPoint = self.text_pane.caret.getMagicCaretPosition()

        # BUG: sometimes caretPoint is None
        # To duplicate type "java.aw" and hit '.' to complete selection while popup is visible

        x = screenPoint.getX() + caretPoint.getX() + self.dotWidth
        y = screenPoint.getY() + caretPoint.getY() + self.textHeight
        return Point(int(x), int(y))
Esempio n. 13
0
 def mouseClicked(self, event):
     table = event.getSource()
     p = Point(event.getX(), event.getY())
     row = table.rowAtPoint(p)
     owner = table.getValueAt(row, 0)
     if -1 == row : return
     if event.getClickCount() != 1: return
     if event.getButton() != MouseEvent.BUTTON3: return
     tc = self.__extractTestcase(owner)
     n = self.__extractNode(owner)
     TreePopup(tc, n).show(table, event.getX(), event.getY())
Esempio n. 14
0
 def noWSAS(self):
     frame = InternalFrame('Notice',
                           outer=self,
                           size=(400, 125),
                           location=Point(5, 5))
     html = '<html>This application requires WebSphere Application '
     html += 'Server<br><br>See Help -> About for details.'
     frame.text = JLabel(html)
     frame.add(frame.text)
     frame.setVisible(1)
     return frame
Esempio n. 15
0
 def __init__(self, outer):
     InternalFrame.__init__(self,
                            'TextField',
                            outer,
                            size=(180, 85),
                            location=Point(5, 5))
     self.add(JLabel('Timeout (minutes):'))
     self.text = self.add(JTextField(3, actionPerformed=outer.update))
     self.message = self.add(JLabel())
     self.setVisible(1)
     self.text.requestFocusInWindow()
Esempio n. 16
0
def setCustomCursor(*args):
   isPlaygroundValid()
   if len(args) == 1:
      dim = __g.setCustomCursor(args[0])
   elif len(args) == 2:
      dim = __g.setCustomCursor(args[0], Point(args[1][0], args[1][1]))
      if dim != None:
         return [dim.height, dim.width]
      else:   
         return None
   else:
      raise ValueError("Illegal number of arguments")
Esempio n. 17
0
 def __init__(self, outer):
     InternalFrame.__init__(self,
                            'TextField and Button',
                            outer,
                            size=(180, 125),
                            location=Point(5, 95))
     self.add(JLabel('Timeout: (minutes)'))
     self.text = self.add(JTextField(3, actionPerformed=outer.update))
     self.button = self.add(JButton('Update', actionPerformed=outer.update))
     self.message = self.add(JLabel())
     self.setVisible(1)
     self.text.requestFocusInWindow()
Esempio n. 18
0
 def set_cursor(self, *cursor):
     """
     Set mouse cursor.
     Alternative arguments:
     * JVM system cursor or cursor object
     * image or surface, hotspot (x,y), and optional name
     * size, hotspot, data, mask, and optional name
     Refer to pyj2d.cursors for details.
     """
     args = len(cursor)
     if len(cursor) == 1:
         if isinstance(cursor[0], int):
             self._cursor = Cursor(cursor[0])
         else:
             self._cursor = cursor[0]
     elif args in (2,3):
         image = cursor[0]
         hotspot = Point(*cursor[1])
         if args == 2:
             name = 'Custom Cursor'
         else:
             name = cursor[2]
         tk = Toolkit.getDefaultToolkit()
         self._cursor = tk.createCustomCursor(image, hotspot, name)
     elif args in (4,5):
         size = cursor[0]
         hotspot = Point(*cursor[1])
         data = cursor[2]
         mask = cursor[3]
         if args == 4:
             name = 'Custom Cursor'
         else:
             name = cursor[4]
         surface = cursors.create_cursor(size, data, mask)
         tk = Toolkit.getDefaultToolkit()
         self._cursor = tk.createCustomCursor(surface, hotspot, name)
     else:
         self._cursor = Cursor(Cursor.DEFAULT_CURSOR)
     if self._cursorVisible:
         env.jframe.getContentPane().setCursor(self._cursor)
Esempio n. 19
0
 def __init__(self, title, outer, size, location=None, layout=None):
     if location == None:
         location = Point(0, 0)
     if layout == None:
         layout = FlowLayout()
     JInternalFrame.__init__(
         self,
         title,
         0,  # resizeable = false
         0,  # closable  = false
         size=size,
         internalFrameListener=self,
         layout=layout)
     self.setLocation(location)  # keyword parm doesn't exist
     self.outer = outer  # application object
Esempio n. 20
0
def getContentPane():
    global contentPane
    global REMAP_WIDTH
    global REMAP_HEIGHT
    global MARGIN
    if not contentPane:
        global mainScreen
        global mainScreenImg
        mainScreen = JLabel()

        cursorImg = BufferedImage(16,16,BufferedImage.TYPE_INT_ARGB)
        blankCursor = Toolkit.getDefaultToolkit().createCustomCursor(cursorImg, Point(0,0), "blank cursor")
        mainScreen.setCursor(blankCursor)
        mainScreen.setPreferredSize(
                Dimension(REMAP_WIDTH + MARGIN, REMAP_HEIGHT + MARGIN))
        mainScreen.setText("main screen!")
        image = BufferedImage(REMAP_WIDTH + MARGIN, REMAP_HEIGHT + MARGIN
                , BufferedImage.TYPE_INT_ARGB)
        g = image.createGraphics()
        g.setColor(Color.BLACK)
        g.fillRect(0, 0, REMAP_WIDTH + MARGIN, REMAP_HEIGHT + MARGIN)
        g.setColor(Color.WHITE)
        g.setFont(Font("Serif", Font.BOLD, 20))
        g.drawString("Cursor will display on your device.", 50, 30)
        mainScreenImg = image
        mainScreen.setIcon(swing.ImageIcon(image))

        mouseListener = ScrMouseListener()
        mainScreen.addMouseListener(mouseListener)
        mainScreen.addMouseMotionListener(mouseListener)
        mainScreen.addMouseWheelListener(mouseListener)

        keyListener = ScrKeyListener()
        mainScreen.addKeyListener(keyListener)
        
        mainScreen.setFocusable(True)

        scrPanel = JPanel()
        scrPanel.setLayout(BoxLayout(scrPanel, BoxLayout.Y_AXIS))
        scrPanel.add(mainScreen)


        contentPane = JPanel()
        contentPane.setLayout(BorderLayout())
        contentPane.add(scrPanel, BorderLayout.WEST)
#        contentPAne.add(controlPanel(). BorderLayout.EAST)

    return contentPane
Esempio n. 21
0
    def run(self):
        frame = JFrame('KeyBindings',
                       locationRelativeTo=None,
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        headings = ('KeyStroke,Unmodified,Ctrl,Shift,Shift-Ctrl').split(',')
        table = JTable(myTM(self.data(), headings), columnSelectionAllowed=1)
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF)
        setColumnWidths(table)
        frame.add(JScrollPane(table))
        frame.pack()
        size = frame.getSize()
        loc = frame.getLocation()
        frame.setLocation(
            Point(loc.x - (size.width >> 1), loc.y - (size.height >> 1)))

        frame.setVisible(1)
Esempio n. 22
0
 def createLayeredPane(self):
     colors = [('Red', Color.red), ('Orange', Color.orange),
               ('Yellow', Color.yellow), ('Green', Color.green),
               ('Blue', Color.blue), ('Indigo', Color(75, 0, 130)),
               ('Violet', Color(143, 0, 255))]
     result = JLayeredPane(
         border=BorderFactory.createTitledBorder('Layered Pane'),
         preferredSize=Dimension(290, 280))
     position, level = Point(10, 20), 0
     for name, color in colors:
         label = self.createColoredLabel('Layer %d = %s' % (level, name),
                                         color)
         label.setLocation(position)
         position.x += 20
         position.y += 20
         result.add(label, level, 0)
         #           result.add( label, level )
         #           print level, result.getLayer( label ), result.getPosition( label )
         level += 1
     return result
Esempio n. 23
0
    def __init__( self, outer ) :
        InternalFrame.__init__(
            self,
            'RadioButtons',
            outer,
            size = ( 400, 85 ),
            location = Point( 5, 225 )
        )

        self.add( JLabel( 'Timeout (minutes):' ) )
        buttons = {}
        self.bg = ButtonGroup()
        for name in '0,15,30,60,Other'.split( ',' ) :
            button = JRadioButton(
                name,
                itemStateChanged = self.stateChange
            )
            self.bg.add( button )
            self.add( button )
            buttons[ name ] = button
        
        self.r00  = buttons[ '0'  ]
        self.r15  = buttons[ '15' ]
        self.r30  = buttons[ '30' ]
        self.r60  = buttons[ '60' ]
        self.rot  = buttons[ 'Other' ]

        self.text = self.add( 
            JTextField(
                '',
                3,
                actionPerformed = outer.update
            )
        )
        self.message = self.add( JLabel() )

        self.setting = 0         # see stateChange() and setValue()

        self.setVisible( 1 )
Esempio n. 24
0
    def run(self):

        #-----------------------------------------------------------------------
        # Starting width, height & location of the application frame
        #-----------------------------------------------------------------------
        screenSize = Toolkit.getDefaultToolkit().getScreenSize()
        w = screenSize.width >> 1  # Use 1/2 screen width
        h = screenSize.height >> 1  # and 1/2 screen height
        x = (screenSize.width - w) >> 1  # Top left corner of frame
        y = (screenSize.height - h) >> 1

        #-----------------------------------------------------------------------
        # Center the application frame in the window
        #-----------------------------------------------------------------------
        frame = self.frame = JFrame('WASports_08',
                                    bounds=(x, y, w, h),
                                    defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        #-----------------------------------------------------------------------
        # Add our menu bar to the frame, keeping a reference to the object
        #-----------------------------------------------------------------------
        frame.setJMenuBar(self.MenuBar())

        #-----------------------------------------------------------------------
        # Internal frames require us to use a JDesktopPane()
        #-----------------------------------------------------------------------
        desktop = JDesktopPane()

        cellName = AdminConfig.showAttribute(AdminConfig.list('Cell'), 'name')
        #-----------------------------------------------------------------------
        # Create our initial internal frame, and add it to the desktop
        #-----------------------------------------------------------------------
        internal = InternalFrame(cellName, Dimension(w >> 1, h >> 1),
                                 Point(5, 5), self.cellData)
        desktop.add(internal)

        frame.setContentPane(desktop)
        frame.setVisible(1)
Esempio n. 25
0
 def set_visible(self, visible):
     """
     Set mouse cursor visibility according to visible bool argument.
     Return previous cursor visibility state.
     """
     visible_pre = self._cursorVisible
     if visible:
         if not self._cursor:
             self._cursor = Cursor(Cursor.DEFAULT_CURSOR)
         env.jframe.getContentPane().setCursor(self._cursor)
         self._cursorVisible = True
     else:
         if not self._cursorBlank:
             image = BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB)
             hotspot = Point(0,0)
             name = 'Blank Cursor'
             try:
                 tk = Toolkit.getDefaultToolkit()
                 self._cursorBlank = tk.createCustomCursor(image, hotspot, name)
             except AWTError:
                 return visible_pre
         env.jframe.getContentPane().setCursor(self._cursorBlank)
         self._cursorVisible = False
     return visible_pre
Esempio n. 26
0
def executeIscExtract(parmNames, databaseName, startTime, endTime,
                      irtTableAddressA, irtTableAddressB, transmitScript, ourServerHost,
                      ourServerPort, ourServerProtocol, ourMHSid, ourSiteID, destinations=None):
    
    startT = time.time()
    parms = parmNames
    dbid = databaseName
    startTR = startTime
    endTR = endTime
    xmlDestinations = destinations
    ancf = irtTableAddressA
    bncf = irtTableAddressB
    xmtScript = transmitScript
    serverHost = ourServerHost
    serverPort = ourServerPort
    serverProtocol = ourServerProtocol
    mhsid = ourMHSid
    siteID = ourSiteID
    
    myOfficeType = IFPServerConfigManager.getServerConfig(siteID).officeType()
    
    
    #--------------------------------------------------------------------
    # determine the list of destination servers
    #--------------------------------------------------------------------
    try:
        nowT = time.time()   #current time
        useUntilTime = None  #cached use until time
        cacheFilename = "/tmp/" + serverHost + serverPort + ".iscExtract"
        cachedXmlDestinations = None
        #if xmlDestinations is None:    #destinations not on command line
        #    # check the cache 
        #    try:
        #        fd = open(cacheFilename, 'rb')
        #        buf = fd.read()
        #        fd.close()
        #        useUntilTime, cachedXmlDestinations = cPickle.loads(buf)
        #        nowT = time.time()   #current time
        #        if nowT > useUntilTime:
        #            xmlDestinations = None   #cache is too old
        #            useUntilTime = None
        #        else:
        #            logEvent('Using xmlDestinations cache')
        #            xmlDestinations = cachedXmlDestinations
        #    except:
        #        pass
            
            
        # need to contact IRT to get destinations
        irt = IrtAccess.IrtAccess(ancf, bncf)
        if xmlDestinations is None:
            logEvent('contacting IRT to get destinations')
            count = 1
            while True:
                status, xmlDestinations = irt.getSendAddrs(siteID)
                logEvent('IRT getSendAddrs status:', status)
                if status:
                    # if we obtained XML destinations from IRT, then decode
                    # the useUntilTime field
                    try:
                        d = ElementTree.ElementTree(ElementTree.XML(xmlDestinations))
                        dE = d.getroot()
                        for e in dE:
                            if e.tag == "useuntil":
                                isoTimeStr = e.text
                                idx = isoTimeStr.find(".") 
                                if idx != - 1:
                                    isoTimeStr = isoTimeStr[0:idx]  #eliminate subseconds
                                useUntilTime = time.mktime(time.strptime(isoTimeStr,
                                  "%Y-%m-%dT%H:%M:%S"))
                                logEvent("Use Until: ", isoTimeStr)
                    except:
                        logProblem("Malformed XML on getSendAddrs()")
                        logProblem("XML=", xmlDestinations)
                        return
                    if useUntilTime is None:
                        useUntilTime = time.time() + 180.0   #3 minutes default
                        logEvent("Using default 180 second useUntilTime")
    
                    # write the cache
                    fd = open(cacheFilename, 'wb')
                    buf = cPickle.dumps((useUntilTime, xmlDestinations))
                    fd.write(buf)
                    fd.close()
                    break   #success from the irt
                else:
                    # try again and again for 10 minutes, then use cache
                    # if available and alert GFE users
                    if time.time() - nowT > 600.00: 
                        logProblem("Unable to access IRT for send addrs")
                        if cachedXmlDestinations is None:
                            s = "Unable to access IRT for send addrs. Previous" + \
                              " cache not available."
                            logProblem(s)
                            return
                        # use cached value, even if out of date
                        else:
                            xmlDestinations = cachedXmlDestinations
                            if useUntilTime is not None:
                                s = time.asctime(time.gmtime(useUntilTime))
                            else:
                                s = "Unknown"
                            logProblem("Using expired cache. Date=", s)
    
                            #determine when we issued our last GFE alert
                            #we alert every 30 minutes.
                            try:
                                fd = open(cacheFilename + "-warn", 'rb')
                                buf = fd.read()
                                fd.close()
                                lastAlertTime = cPickle.loads(buf)
                            except:
                                lastAlertTime = 0  #for way long ago
                            if time.time() - lastAlertTime > 1800.0:
                                logProblem("Sending GFE notification")
                                msg = """
    Contact NCF. ifpServer is unable to contact IRT central server.  ISC
    traffic routing information is old and possibly incorrect."""
                                os.system("sendGfeMessage -u -c GFE -m '" + \
                                  msg + "'")
                                fd = open(cacheFilename + "-warn", 'wb')
                                fd.write(cPickle.dumps(time.time()))
                                fd.close()
                            break
    
                    time.sleep(15.0)   #sleep awhile and then try again
                    count = count + 1
                    logProblem("Retrying to getSendAddrs()", count)
        # qc the XML
        try:
            destTree = ElementTree.ElementTree(ElementTree.XML(xmlDestinations))
            destE = destTree.getroot()
        except:
            logProblem("Malformed XML on getSendAddrs() or provided xmlDest")
            logProblem("XML=", xmlDestinations)
            return
        #--------------------------------------------------------------------
        # determine how many transmissions are necessary
        #--------------------------------------------------------------------
        xmt = []

        logEvent("XML dest:", xmlDestinations)
        if destE.tag != "destinations":
            logProblem("Destinations packet missing from web service")
            return
            
        # create list of individual transmissions (before attempting to combine
        doClip = 1  #0 to send entire domain, 1 to do destination clipping (default)
        destStr = "Destination Servers:\n"
        for addressE in destE:
            if addressE.tag == "doclip":
                for name, value in addressE.items():
                    if name == "clip":
                        if value == "1":
                            doClip = 1
                        elif value == "0":
                            doClip = 0
    
        logEvent("Clipping State: ", doClip)
        
        for addressE in destE:

            if addressE.tag != "address":
                continue
            
            # find destination server info and domain information
            serverInfo = irt.decodeXMLAddress(addressE)
            
            if doClip == 0:
                serverInfo['domain'] = None
            keycheckfail = False
            for key in ['mhsid', 'host', 'port', 'protocol', 'site']:
                if not serverInfo.has_key(key):
                    logProblem("Fail to decode XML. Skipping serverInfo:",
                      serverInfo)
                    keycheckfail = True
                    continue
            if keycheckfail:
                continue   #skipping this destination due to insufficient info
           
            # get the destination office type
            try: 
                siteIndex = IFPServerConfigManager.getServerConfig(siteID).allSites().indexOf(serverInfo['site'])
                destOfficeType = str(IFPServerConfigManager.getServerConfig(siteID).officeTypes().get(siteIndex))
            except:
                logProblem("Unknown site id to get office type. ",
                  "Skipping serverInfo:", serverInfo)
                continue   #skipping this destination due to unknown site id

            # find weather elements that remote ifpServer wants
            # that is available in our server and in the -p parm switches
            any = False
            for parm in serverInfo['parms']:
                p1 = string.replace(parm, "_SFC", "")  #remove _SFC if exists

                # translation of parm name needed, also if no office type, then
                # not wanted from this office.
                #   example: changes QPFwfo to QPF if we are wfo
                #   example: discards T if we are wfo and site is non-wfo
                if myOfficeType != destOfficeType:
                    if p1.find(myOfficeType) != - 1:
                        p1 = string.replace(p1, myOfficeType, "") #remove type
                    else:
                        continue   #no type, so not intended for our type
                # see if parm was listed in the command line switches
                if parms.contains(p1):
                    xmt.append({'serverInfo':[serverInfo], 'parms':[p1],
                      'domain': serverInfo['domain'], 'area': serverInfo['area']})
                    if not any:
                        destStr += irt.printServerInfo(serverInfo) + "\n"
                        any = True
    
        logEvent(destStr)
        
        # now combine transmissions
        # find same domains, same parms, to combine servers/destinations
        i = 0
        while i < len(xmt):
            j = i + 1
            while j < len(xmt):
                if xmt[i]['domain'] == xmt[j]['domain'] and \
                  xmt[i]['area'] == xmt[j]['area'] and \
                  xmt[i]['parms'] == xmt[j]['parms']:
                    for si in xmt[j]['serverInfo']:
                        if si not in xmt[i]['serverInfo']:
                            dests = xmt[i]['serverInfo']
                            dests.append(si)
                            xmt[j]['serverInfo'] = dests
                    del xmt[j] #delete the entry
                    j = j - 1  #redo this entry index next loop
                j = j + 1
            i = i + 1
    
        # now try to combine common parm lists (same domain, same servers/destinations)
        i = 0
        while i < len(xmt):
            j = i + 1
            while j < len(xmt):
                if xmt[i]['domain'] == xmt[j]['domain'] and \
                  xmt[i]['area'] == xmt[j]['area'] and \
                  xmt[i]['serverInfo'] == xmt[j]['serverInfo'] :
                    iparms = xmt[i]['parms']
                    for p in xmt[j]['parms']:
                        if p not in iparms:
                            iparms.append(p)
                    xmt[i]['parms'] = iparms 
                    del xmt[j]  #delete the entry
                    j = j - 1  #redo this entry index for next loop
                j = j + 1
            i = i + 1

        # if doClip, gather some required information
        if doClip:
            #get the isc send area and grid domain from the ifpServer
            iscSendAreaGrid = iscUtil.getEditArea("ISC_Send_Area",siteID)           
            sourceDomain = IFPServerConfigManager.getServerConfig(siteID).dbDomain()
            
            iscSendAreaGrid.setGloc(sourceDomain)
            iscSendAreaGrid = iscSendAreaGrid.getGrid()

        
        #--------------------------------------------------------------------
        # prepare output files
        #--------------------------------------------------------------------
        for dest in xmt:
            s = "Processing Xmt Pass:\n"
            for sv in dest['serverInfo']:
                s += irt.printServerInfo(sv) + '\n'
            s += "Domain:" + `dest['domain']` + '\n'
            s += "Area:" + `dest['area']` + '\n'
            s += "Parms:" + `dest['parms']` + '\n\n'
            logEvent(s)
            # extract the data using ifpnetCDF
            if os.path.exists(siteConfig.GFESUITE_HOME + "/products/ISC") == False:
                os.makedirs(siteConfig.GFESUITE_HOME + "/products/ISC")
                
            tempfile.tempdir = siteConfig.GFESUITE_HOME + "/products/ISC" 
            fname = tempfile.mktemp(".isc") 
    
            # Determine domain edit area.
            
            if doClip == 1 and dest['domain'] is not None and \
              dest['domain']['proj'] == sourceDomain.getProjection().getProjectionID():
                #make a GridLocation for our domain
                gridSize = Coordinate(float(str(sourceDomain.getNx())), float(str(sourceDomain.getNy())))
                origin = sourceDomain.getOrigin()
                extent = sourceDomain.getExtent()
                domain = CartDomain2D(origin, extent)
                gloc = sourceDomain
                
                #make a GridLocation covering the area for the destination, expanded
                #by 1/2 grid cell 
                dd = dest['domain']
                da = dest['area']
                cellsizeX = float(dd['extx']) / (float(da['xdim']) - 1.0)
                cellsizeY = float(dd['exty']) / (float(da['ydim']) - 1.0)
                originD = Coordinate(float(dd['origx']) - cellsizeX / 2.0,
                  float(dd['origy']) - cellsizeY / 2.0)
                extentD = Coordinate(float(dd['extx']) + cellsizeX,
                  float(dd['exty']) + cellsizeY)
                domainD = CartDomain2D(originD, extentD) 

                #check for overlap
                if not domainD.overlaps(domain):
                    logEvent("No intersection of domain box, skipping....")
                    continue   #no bits set in the resulting mask, no intersect
    
                domainD.trim(domain)   #trim it to just the overlapping section
                
                
                gridSize  = Point(int(da['xdim']),int(da['ydim']))
                destGridLocation = GridLocation("Dest",sourceDomain.getProjection(),
                                                gridSize,domainD.getOrigin(),domainD.getExtent(),"GMT")
                                            
                # make a Reference Set
                refid = ReferenceID("jibberish")
                refSet = ReferenceData(gloc, refid, destGridLocation.getGeometry(), CoordinateType.LATLON)

                # convert destination site's domain to gridpoints
                iscMask = refSet.getGrid()
                
                # "and" it with our ISC_Send_Area
                iscMask.andEquals(iscSendAreaGrid)

                if not iscMask.isAnyBitsSet():
                    logEvent("No intersection of domain points, skipping....")
                    continue   #no bits set in the resulting mask, no intersect
    
                # store the grid back into the ifpServer
                maskName = "iscExtract" + `time.time()`
                refSet.setGrid(iscMask)
                iscUtil.saveEditAreaGrid(maskName, refSet, siteID)

            else:  #no clipping, or different projection
                maskName = "ISC_Send_Area"
    
            # Run ifpnetCDF for the data
            argv = {"outputFilename": fname, 
                    "parmList": dest['parms'],
                    "databaseID": dbid, 
                    "startTime": startTR,
                    "endTime": endTR, 
                    "mask": maskName, 
                    "geoInfo": False, 
                    "compressFileFlag": True, 
                    "configFileName": "iscSendSampleDef", 
                    "compressFileFactor": 6, 
                    "trim": True, 
                    "krunch": True, 
                    "userID": "iscExtract",
                    "logFileName": None,
                    "siteIdOverride": None}
            ifpnetCDF.main(**argv)
            
            fname = fname + '.gz'
            size = os.stat(fname)[stat.ST_SIZE]
            endT = time.time()
            logEvent('File Size: ', size)
            logEvent('After ifpnetCDF, ,wctime:', "%-6.2f" % (endT - startT),
                                   ',cputime:', "%-6.2f" % time.clock())
    
            # create XML destinations file for this output
            iscE = Element('isc')  #create the XML tree root
            sourceServer = {'mhsid': mhsid, 'host': serverHost, 'port': serverPort,
              'protocol': serverProtocol, 'site': siteID}
            irt.addSourceXML(iscE, sourceServer)
            irt.addDestinationXML(iscE, dest['serverInfo']) 
    
            #get the unique list of mhs sites 
            mhsSites = []
            for si in dest['serverInfo']:
                if si['mhsid'] not in mhsSites: 
                    mhsSites.append(si['mhsid']) 
    
            # create the XML file
            fnameXML = tempfile.mktemp(".xml")
            fd = open(fnameXML, 'wb')
            fd.write(ElementTree.tostring(iscE))   
            fd.close()
    
            # Transmit files - do string substitution
            irt.transmitFiles("ISCGRIDS2", mhsSites, mhsid, [fname,fnameXML], xmtScript)
            # Delete temporary files
            if maskName != "ISC_Send_Area": 
               iscUtil.deleteEditArea(maskName,siteID)
    
            endT = time.time() 
            logEvent('After transmission pass, ,wctime:',
              "%-6.2f" % (endT - startT), ',cputime:', "%-6.2f" % time.clock())
    
    except:
        logProblem("Failure", traceback.format_exc()) 
        
Esempio n. 27
0
        for i in range(w):
            if s.charAt(k * w + i) == 'x':
                showBrick(x + i, k)


def showBrick(i, k):
    tm.setImage("sprites/brick.gif", i, k)
    for n in range(4):
        balls[n].addCollisionTile(Location(i, k))


gg = GameGrid(620, 180, 1, False)
gg.setBgColor(X11Color("darkblue"))
gg.setSimulationPeriod(50)
gg.addActListener(MyActListener())
tm = gg.createTileMap(nbHorzTiles, nbVertTiles, tileSize, tileSize)
tm.setPosition(Point(xMapStart, yMapStart))

for n in range(4):
    ball = Ball()
    gg.addActor(ball, gg.getRandomLocation(), gg.getRandomDirection())
    ball.setCollisionCircle(Point(0, 0), 8)
    ball.addTileCollisionListener(MyTileCollisionListener())
    if n == 2 or n == 3:
        ball.show(1)
    balls.append(ball)

createText()
gg.show()
gg.doRun()
Esempio n. 28
0
def insertInHand(actor):
    actor.removeSelf()
    card = actor.getCard()
    hand.insert(card, False)
    hand.sort(SortType.RANKPRIORITY, True)
    takeFromTalon()


def addActor(cardActor):
    cg.addActor(cardActor, Location(talonLocation))
    cardActor.addMouseTouchListener(
        MyMouseTouchListener(),
        GGMouse.lPress | GGMouse.lDrag | GGMouse.lRelease, True)


# ------------------------ main --------------------------------------------
handLocation = Location(250, 100)
talonLocation = Location(250, 300)
hotSpot = Point(0, 0)

cg = CardGame(500, 400, 30)
hands = deck.dealingOut(1, 2)  # only two cards in hand
hand = hands[0]
hand.setView(cg, RowLayout(handLocation, 400))
talon = hands[1]
talon.setView(cg, StackLayout(talonLocation))
hand.draw()
talon.draw()
takeFromTalon()
cg.setStatusText("Drag cards from card talon to the hand")
Esempio n. 29
0
def setFramePosition(x, y):
    global __framePosition
    try:
        _turtleFrame.setScreenLocation(Point(x, y))
    except:
        __framePosition = (x, y)  # deferred
Esempio n. 30
0
def floodFill(bm, x, y, oldColor, newColor):
   return GBitmap.floodFill(bm, Point(x, y), oldColor, newColor)