Esempio n. 1
0
def main( installDir, isUpdate, is_development, platforms, selectedVersion="CURRENT", isWindows=False ):
    info("Running getbirch installer process")

    if (not os.path.lexists(installDir)):
        os.mkdir(installDir)

    if (check_depends()):
        if ( os.path.lexists(installDir) ):
            info('Fetching archives')
            os.chdir(installDir)

            valid = True

            if ( isWindows ):
                from cyglib import setupCygwin
                valid = valid and setupCygwin(installDir)
            valid = valid and getFramework(installDir, is_development)
            valid = valid and getBinaries(installDir, is_development, platforms)
            valid = valid and getInstallScripts( installDir )
            valid = valid and extractInstallScripts( installDir )

            if not valid:
                message = "An error has occurred in fetching the latest version of BIRCH - installion aborted! Please report this problem and email the install log."
                error(mesage)
                JOptionPane.showMessageDialog(None,message );


            #perform the actual install here
    
    shutdown()
 def actionPerformed(self, event):
     if _num.getValue() > 8:
         JOptionPane.showMessageDialog(None, "Max value reached. Resetting to zero.")
         _num.setValue(0)
     else:
         _num.increment()
     otText.setText(str(_num))
Esempio n. 3
0
def move_script_warning():
    """Warn the user to move qat_script directory into Scripting Plugin
       directory
    """
    scriptingPluginDir = PluginHandler.getPlugin("scripting").getPluginDir()
    pane = JPanel(GridLayout(3, 1, 5, 5))
    warningTitle = "Warning: qat_script directory not found"
    pane.add(JLabel("Please, move qat_script directory to the following location and start the script again:\n"))
    defaultPathTextField = JTextField(scriptingPluginDir,
                                      editable=0,
                                      border=None,
                                      background=None)
    pane.add(defaultPathTextField)

    if not Desktop.isDesktopSupported():
        JOptionPane.showMessageDialog(
            Main.parent,
            pane,
            warningTitle,
            JOptionPane.WARNING_MESSAGE)
    else:
        #add a button to open default path with the files manager
        pane.add(JLabel("Do you want to open this folder?"))
        options = ["No", "Yes"]
        answer = JOptionPane.showOptionDialog(
            Main.parent,
            pane,
            warningTitle,
            JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            None,
            options,
            options[1])
        if answer == 1:
            Desktop.getDesktop().open(File(scriptingPluginDir))
def main():
    b=BuildingInBuilding()

    if Main.main and Main.main.map:
        mv= Main.main.map.mapView
        print mv.editLayer

        if mv.editLayer and mv.editLayer.data :
            selectedNodes = mv.editLayer.data.getSelectedNodes()
            selectedWays = mv.editLayer.data.getSelectedWays()
            if not(selectedWays):
                JOptionPane.showMessageDialog(Main.parent, "Please select a set of ways")
            else:
                print "going to output ways";
                for way in selectedWays:
                    #is there a 
                    housenumber=way.get('addr:housenumber')
                    street=way.get('addr:street')
                    if(housenumber):
                         b.visitw(way)
        #                print 'house box:', street, housenumber

                for node in selectedNodes:
                    housenumber=node.get('addr:housenumber')
                    street=node.get('addr:street')
                    if(housenumber):
                         b.visitn(node)
                         l.showNode(node)
        #                print 'house box:', street, housenumber
        

        b.endTest()
Esempio n. 5
0
def getJavaFX():
    ver = jsys.getProperty("java.version")
    ver = ver.split(".")
    ver[-1] = float(ver[-1].replace("_", "."))
    ver[0] = float(str(ver[0]) + "." + str(ver[1]))
    ver.pop(1)

    print  ver

    if ver[0] <= 1.6:
        mess()

    elif ver[0] == 1.7:
        if ver[1] <= 0.11:
            mess()
            home = jsys.getProperty("java.home")

            try:
                jfxrt = os.path.join(home, "lib", "jfxrt.jar")
                sys.path.insert(0, jfxrt)

            except:
                part01 = "Nie można odnalesc biblioteki JavaFX(jfxrt.jar).\n"
                message = part01 + "Unable to find JavaFX lib (jfxrt.jar)."
                jop.showMessageDialog(None, message)
                sys.exit()

    else:
        pass
Esempio n. 6
0
    def actionPerformed(self, event):
        content, message, info, parameter = self.tab._current

        try:
            body = content[info.getBodyOffset():].tostring()

            if parameter is not None:
                param = self.tab.helpers.getRequestParameter(
                        content, parameter.getName())

                if param is not None:
                    rules = self.tab.extender.table.getParameterRules().get(parameter.getName(), {})
                    body = param.getValue().encode('utf-8')

                    for rule in rules.get('before', []):
                        body = rule(body)

            message = parse_message(self.descriptor, body)

            self.tab.editor.setText(str(message))
            self.tab.editor.setEditable(True)
            self.tab._current = (content, message, info, parameter)

        except Exception as error:
            title = "Error parsing message as %s!" % (self.descriptor.name, )
            JOptionPane.showMessageDialog(self.tab.getUiComponent(),
                error.message, title, JOptionPane.ERROR_MESSAGE)

        return
Esempio n. 7
0
 def on_downloadBoundariesBtn_clicked(self, e):
     """Download puter ways of administrative boundaries from
        Overpass API
     """
     adminLevel = self.adminLevelTagTextField.getText()
     name = self.nameTagTextField.getText()
     optional = self.optionalTagTextField.getText()
     if (adminLevel, name, optional) == ("", "", ""):
         JOptionPane.showMessageDialog(self,
                                       self.app.strings.getString("enter_a_tag_msg"),
                                       self.app.strings.getString("Warning"),
                                       JOptionPane.WARNING_MESSAGE)
         return
     optTag = ""
     if optional.find("=") != -1:
         if len(optional.split("=")) == 2:
             key, value = optional.split("=")
             optTag = '["%s"="%s"]' % (URLEncoder.encode(key, "UTF-8"),
                                       URLEncoder.encode(value.replace(" ", "%20"), "UTF-8"))
     self.create_new_zone_editing_layer()
     overpassurl = 'http://127.0.0.1:8111/import?url='
     overpassurl += 'http://overpass-api.de/api/interpreter?data='
     overpassquery = 'relation["admin_level"="%s"]' % adminLevel
     overpassquery += '["name"="%s"]' % URLEncoder.encode(name, "UTF-8")
     overpassquery += '%s;(way(r:"outer");node(w););out meta;' % optTag
     overpassurl += overpassquery.replace(" ", "%20")
     print overpassurl
     self.app.send_to_josm(overpassurl)
Esempio n. 8
0
    def _validate_form(self):
        error_message = ''

        try:
            original_hash = hex_to_raw(self._textfields["original_hash"].getText())
        except Exception:
            error_message += "Original hash doesn't look right.\n"

        try:
            max_key_len = int(self._textfields["max_key_len"].getText())
        except Exception:
            error_message += "Max key length needs to be an integer.\n"

        original_msg = self._textfields["original_msg"].getText().encode()
        append_msg = self._textfields["append_msg"].getText().encode()

        if not original_msg:
            error_message += "Missing original message.\n"
        if not append_msg:
            error_message += "Missing message to append.\n"

        if error_message:
            JOptionPane.showMessageDialog(self._tab, error_message, "Form Validation Error", JOptionPane.WARNING_MESSAGE)
            return False
        return True
Esempio n. 9
0
def purge_old_birch():
	
	print_label("Purging old BIRCH")	
	os.chdir(ARGS.install_dir)
	contents=os.listdir(os.getcwd())
	
	
	if  "install-birch" in contents:
		for each in birch_files:
			
			if (each!="local" and each.count("birch_backup")!=1 and os.path.lexists(ARGS.install_dir+"/"+each)):
				print_console("Removing old BIRCH component: "+each)
				filename=ARGS.install_dir+"/"+each
				
				
				if (os.path.isdir(filename)):
					try:
						shutil.rmtree(filename)
						if (os.path.isdir(filename)):
							os.remove(filename)
					except:
						err=traceback.format_exc()
						print_console(err)
						JOptionPane.showMessageDialog(None, "An error occurred deleting file: "+filename)
	else:
		pass
def getFirstSymbol():
	color_alpha_width = {}
	activeLayers=getActiveLayers()
	if (len(activeLayers)>0):
		lyr=activeLayers[0]
		if lyr.getClass().getCanonicalName() == "com.iver.cit.gvsig.fmap.layers.FLyrVect":
			legend=lyr.getLegend()
			print legend
			if legend.getClassName() == 'com.iver.cit.gvsig.fmap.rendering.SingleSymbolLegend':
				sym = legend.getDefaultSymbol()
				color_alpha_width["color"] = sym.getColor()
				color_alpha_width["alpha"] = sym.getAlpha()
				if (sym.getClassName() == 'com.iver.cit.gvsig.fmap.core.symbols.SimpleLineSymbol'):
					color_alpha_width["width"] = sym.getLineWidth()
			elif legend.getClassName() == 'com.iver.cit.gvsig.fmap.rendering.VectorialUniqueValueLegend':
				sym = legend.getSymbol(0)
				if (sym.getClassName() == 'com.iver.cit.gvsig.fmap.core.symbols.SimpleFillSymbol'):
					color_alpha_width["color"] = sym.getOutline().getColor()
					color_alpha_width["width"] = sym.getOutline().getLineWidth()
					color_alpha_width["alpha"] = sym.getOutline().getAlpha()
			else:
				try:
					color_alpha_width["color"] = sym.getOutline().getColor()
					color_alpha_width["width"] = sym.getOutline().getLineWidth()
					color_alpha_width["alpha"] = sym.getOutline().getAlpha()
				except Exception, e:
					JOptionPane.showMessageDialog(None, legend.getClassName() + " not yet implemented!", 
								      "Border Symbology", JOptionPane.WARNING_MESSAGE)
					close(e)
Esempio n. 11
0
    def update(self,button=None): #human triggered
        print 'current1', self.current_player

        if(button!=None):
            #human
            cell = str(button.row) + str(button.col)
            if cell in self.empty_cells and self.current_player.level=='human':
                self.current_player.turn(button)
                self.update_state()
                if (self.state == 'next'):
                    self.switch_turn()

        print 'current2', self.current_player
        if self.current_player.level != 'human':
            #ai!
            print "before ai's turn", self.current_player, self.board, self.empty_cells

            self.current_player.turn()
            self.update_state()
            if (self.state == 'next'):
                self.switch_turn()

            print "after ai's turn", self.current_player, self.board, self.empty_cells

        print 'update', self.state, self.turn

        if self.state == 'over':
            JOptionPane.showMessageDialog(self.ui.panel,
                "Game Over! Player: " + self.current_player.name + " Wins!!",
                "Winner", JOptionPane.INFORMATION_MESSAGE)
        elif self.state == 'draw':
                JOptionPane.showMessageDialog(self.ui.panel,
                    "Its a draw!",
                    "Draw", JOptionPane.INFORMATION_MESSAGE)
Esempio n. 12
0
 def printDB(self, e):
     out = ""
     for a in self._db.arrayOfUsers:
         out += str(a._index)+" "+a._name+" : "+str(a._roles)+"\n"
     for b in self._db.arrayOfMessages:
         out += str(b._index)+" "+str(b._roles)+"\n"
     JOptionPane.showMessageDialog(self._splitpane,out)
Esempio n. 13
0
 def promptInfoPane(self, text):
     '''
     1. Show popup with given information text
     '''
     JOptionPane.showMessageDialog( \
             self.view.getContentPane(), text, "Information", \
             JOptionPane.INFORMATION_MESSAGE)
Esempio n. 14
0
 def play_event(self, x1, y1, x2, y2):
       status = self.puzzle.play(x1, y1, x2, y2)
       self.draw_board()
       if status == SimplePyzzle.END_GAME:
           JOptionPane.showMessageDialog (None, \
                               "Grats! You solved the puzzle", \
                               "Puzzle solved!", \
                                JOptionPane.INFORMATION_MESSAGE);
Esempio n. 15
0
    def aboutAction(self, e):
        aboutText = """Induction Applet v. 0.1

        (c) 2007 University of Düsseldorf

        Authors: Gerhard Schurz, Eckhart Arnold
        """
        aboutText = re_sub(" +", " ", aboutText)
        JOptionPane.showMessageDialog(self.getContentPane(), aboutText)
Esempio n. 16
0
 def instructions(event):
     instr = '''
     The program can just recognise capital English characters.
     See Info -> Available Words... for available word corrections.
     
     Good Luck with the writing!'''
     JOptionPane.showMessageDialog(self, instr, 
                   "Instructions", 
                   JOptionPane.INFORMATION_MESSAGE)
def getActiveLayers():
	view=gvSIG.getActiveDocument()
	if view.getClass().getCanonicalName() <> 'com.iver.cit.gvsig.project.documents.view.gui.View':
		JOptionPane.showMessageDialog(None, 
			"The active document is not a view.", "Border Symbology", JOptionPane.WARNING_MESSAGE)
		return
	else:
		mctrl=view.getMapControl()
		mctxt=mctrl.getMapContext()
		layers=mctxt.getLayers()
		activeLayers=layers.getActives()
		return activeLayers
Esempio n. 18
0
 def itemStateChanged(self, e):
     """A ttol has been activated/deactivated.
        Check if at least one tool is on.
     """
     if all(not button.isSelected() for button in self.toolsCBtns):
         JOptionPane.showMessageDialog(
             Main.parent,
             self.app.strings.getString("tools_disabled_warning"),
             self.app.strings.getString("tools_disabled_warning_title"),
             JOptionPane.WARNING_MESSAGE)
         source = e.getItemSelectable()
         source.setSelected(True)
Esempio n. 19
0
 def menuAddToES(e):
     progress = ProgressMonitor(component, "Feeding ElasticSearch", "", 0, len(msgs))
     i = 0
     docs = list()
     for msg in msgs:
         if not Burp_onlyResponses or msg.getResponse():
             docs.append(self.genESDoc(msg, timeStampFromResponse=True).to_dict(True))
         i += 1
         progress.setProgress(i)
     success, failed = bulk(self.es, docs, True, raise_on_error=False)
     progress.close()
     JOptionPane.showMessageDialog(self.panel, "<html><p style='width: 300px'>Successful imported %d messages, %d messages failed.</p></html>" % (success, failed), "Finished", JOptionPane.INFORMATION_MESSAGE)
Esempio n. 20
0
    def managePlugins(self):
        try:
            self.installer.checkPluginDirectory()
            plugins = self.installer.getAllPluginInfo()

            if not plugins:
                JOptionPane.showMessageDialog(self.parentWindow,
                    "No plugins are installed.\n"
                    "If you have a plugin that you wish to install, "
                    "select \"Install Plugin...\" from the \"File\" menu.",
                    TITLE, JOptionPane.ERROR_MESSAGE
                )
                return

            pluginsByDisplay = dict((info['display'] + ' - ' + info['status'], info)
                                    for info in plugins.values())
            pluginNames = pluginsByDisplay.keys()
            pluginNames.sort()

            while True:
                name = JOptionPane.showInputDialog(self.parentWindow,
                    "Here are the installed plugins.\n"
                    "Select a plugin to see its description or uninstall it.",
                    TITLE, JOptionPane.QUESTION_MESSAGE, None,
                    pluginNames, pluginNames[0]
                )

                if name is None or name not in pluginsByDisplay:
                    return
                info = pluginsByDisplay[name]
                message = info['longDescription'] + '\n' + info['note']

                if info['isInstalled']:
                    choice = JOptionPane.showOptionDialog(self.parentWindow,
                        message, TITLE, JOptionPane.YES_NO_OPTION,
                        JOptionPane.INFORMATION_MESSAGE, None,
                        ["OK", "Uninstall"], "OK"
                    )

                    if choice == JOptionPane.NO_OPTION:
                        if not self.confirm("Are you sure you want to uninstall\n%s?" % info['display']):
                            return

                        self.installer.uninstall(info)
                        self.notifyDone("%s was removed." % info['title'])
                        return
                else:
                    JOptionPane.showMessageDialog(self.parentWindow,
                        message, TITLE, JOptionPane.INFORMATION_MESSAGE
                    )
        except (EnvironmentError, InvalidPluginError), exc:
            self.showErrorMessage(exc)
Esempio n. 21
0
 def applyConfig(self):
     try:
         print("Connecting to '%s', index '%s'" % (self.confESHost, self.confESIndex))
         res = connections.create_connection(hosts=[self.confESHost])
         idx = Index(self.confESIndex)
         idx.doc_type(DocHTTPRequestResponse)
         DocHTTPRequestResponse.init()
         try:
             idx.create()
         except:
             pass
     except Exception as e:
         JOptionPane.showMessageDialog(self.panel, "<html><p style='width: 300px'>Error while initializing ElasticSearch: %s</p></html>" % (str(e)), "Error", JOptionPane.ERROR_MESSAGE)
Esempio n. 22
0
def messageBox(msg, title="", type="normal"):
    from javax.swing import JOptionPane

    if type == "normal": 
       JOptionPane.showMessageDialog(getIDEInstance(), msg, title, JOptionPane.INFORMATION_MESSAGE)
    elif type == "warning":
       JOptionPane.showMessageDialog(getIDEInstance(), msg, title, JOptionPane.WARNING_MESSAGE)
    elif type == "warn":
       JOptionPane.showMessageDialog(getIDEInstance(), msg, title, JOptionPane.WARNING_MESSAGE)
    elif type == "error":
       JOptionPane.showMessageDialog(getIDEInstance(), msg, title, JOptionPane.ERROR_MESSAGE)
    else:
       JOptionPane.showMessageDialog(getIDEInstance(), msg, title, JOptionPane.INFORMATION_MESSAGE)
Esempio n. 23
0
 def unwatchVariable(self):
     """
     Opens a dialog, asking the user to remove a variable from the watcher.
     """
     allVars = self.watcher.variablesToTrack
     if len(allVars) > 0:
         var = JOptionPane.showInputDialog(self.gui,
             "Choose a variable to stop watching.", "Watcher",
             JOptionPane.INFORMATION_MESSAGE, None, allVars, allVars[0])
         if var is not None:
             self.watcher.removeVariable(var)
     else:
         JOptionPane.showMessageDialog(self.gui,
             "There are no variables being watched.", "Watcher",
             JOptionPane.ERROR_MESSAGE)
Esempio n. 24
0
def openGVL():
    from javax.swing import JFileChooser
    GUIUtil=PluginServices.getPluginServices("com.iver.cit.gvsig.cad").getClassLoader().loadClass("com.iver.cit.gvsig.gui.GUIUtil")
    chooser = JFileChooser()
    chooser.setFileFilter(GUIUtil().createFileFilter("GVL Legend File",["gvl"]))
    from java.util.prefs import Preferences
    lastPath = Preferences.userRoot().node("gvsig.foldering").get("DataFolder", "null")
    chooser.setCurrentDirectory(File(lastPath))
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY)
    returnVal = chooser.showOpenDialog(None)
    if returnVal == chooser.APPROVE_OPTION:
        gvlPath = chooser.getSelectedFile().getPath()
    elif returnVal == chooser.CANCEL_OPTION:
        JOptionPane.showMessageDialog(None, "You have to open a .gvl file. Retry!","Batch Legend",JOptionPane.WARNING_MESSAGE)
        gvlPath = ""
    return gvlPath
Esempio n. 25
0
 def applyConfig(self):
     try:
         print("Connecting to '%s', index '%s'" % (self.confESHost, self.confESIndex))
         self.es = connections.create_connection(hosts=[self.confESHost])
         self.idx = Index(self.confESIndex)
         self.idx.doc_type(DocHTTPRequestResponse)
         if self.idx.exists():
             self.idx.open()
         else:
             self.idx.create()
         self.callbacks.saveExtensionSetting("elasticburp.host", self.confESHost)
         self.callbacks.saveExtensionSetting("elasticburp.index", self.confESIndex)
         self.callbacks.saveExtensionSetting("elasticburp.tools", str(self.confBurpTools))
         self.callbacks.saveExtensionSetting("elasticburp.onlyresp", str(int(self.confBurpOnlyResp)))
     except Exception as e:
         JOptionPane.showMessageDialog(self.panel, "<html><p style='width: 300px'>Error while initializing ElasticSearch: %s</p></html>" % (str(e)), "Error", JOptionPane.ERROR_MESSAGE)
def main():
	
	activeLayers=getActiveLayers()

	if len(activeLayers)==0:
		JOptionPane.showMessageDialog(None, 
			"Add and activate at least one vector layer in the view. Retry!",
			"Batch Transparency", JOptionPane.WARNING_MESSAGE)
		return
	else:
		numFLyrVect=0
		for i in range(len(activeLayers)):
			if activeLayers[i].getClass().getCanonicalName()=="com.iver.cit.gvsig.fmap.layers.FLyrVect":
				numFLyrVect=numFLyrVect+1
		if numFLyrVect==0:
			JOptionPane.showMessageDialog(None, 
				"You have to add and activate at least one vector layer in the view. Retry!", 
				"Batch Transparency", JOptionPane.WARNING_MESSAGE)
			return
		else:
			global frame, outCheckbox, fillCheckbox, slider
			frame = JFrame("Batch Transparency", defaultCloseOperation=JFrame.DISPOSE_ON_CLOSE, 
				bounds=(100, 100, 450, 80), layout=FlowLayout(), resizable=0)

			outCheckbox = JCheckBox("outline", 1)
			fillCheckbox = JCheckBox("fill", 1)

			# Create a horizontal slider with min=0, max=100, value=50
			slider = JSlider()
			slider.setPreferredSize(Dimension(200, 50))
			slider.setValue(100)
			slider.setMajorTickSpacing(25)
			slider.setMinorTickSpacing(5)
			slider.setPaintTicks(1)
			slider.setPaintLabels(1)

			applyButton = JButton("Apply", actionPerformed=action)
			acceptButton = JButton("Accept", actionPerformed=accept)
			
			frame.add(outCheckbox)
			frame.add(fillCheckbox)
			frame.add(slider)
			frame.add(applyButton)
			frame.add(acceptButton)
			
			frame.show()
	return
def main():
    if Main.main and Main.main.map:
        mv = Main.main.map.mapView
        print mv.editLayer

        if mv.editLayer and mv.editLayer.data:
            selectedWays = mv.editLayer.data.getSelectedWays()
            if not (selectedWays):
                JOptionPane.showMessageDialog(Main.parent, "Please select a set of ways")
            else:
                print "going to output ways"
                for way in selectedWays:
                    # is there a
                    housenumber = way.get("addr:housenumber")
                    street = way.get("addr:street")
                    if housenumber:
                        print "house box:", street, housenumber
Esempio n. 28
0
    def approveSelection(self):
        filePath = self.getSelectedFile().getPath()
        fileName = String(self.getSelectedFile().getName())

        if fileName.matches('[_a-zA-Z0-9()~#.]+'):
            if os.path.exists(filePath):
                message = 'File "' + str(fileName) + ' exists. Overwrite?'
                result = JOptionPane.showConfirmDialog(self, message,
                                                       'Confirm Overwrite',
                                                       JOptionPane.YES_NO_OPTION)
                if result == JOptionPane.YES_OPTION:
                    JFileChooser.approveSelection(self)
            else:
                JFileChooser.approveSelection(self)
        else:
            message = 'The file name contains illegal characters. Please rename.'
            JOptionPane.showMessageDialog(self, message, 'Error', JOptionPane.ERROR_MESSAGE)
Esempio n. 29
0
 def actionPerformed(self, e):
     """ generated source for method actionPerformed """
     if e.getSource() == self:
         if self.theServer != None:
             if not self.theServer.getMatch().getGame().getRepositoryURL().contains("127.0.0.1"):
                 if theMatchKey != None:
                     print "Publishing to: " + theURL
                     if nChoice == JOptionPane.YES_OPTION:
                         try:
                             java.awt.Desktop.getDesktop().browse(java.net.URI.create(theURL))
                         except Exception as ee:
                             ee.printStackTrace()
                 else:
                     JOptionPane.showMessageDialog(self, "Unknown problem when publishing match.", "Publishing Match Online", JOptionPane.ERROR_MESSAGE)
             else:
                 JOptionPane.showMessageDialog(self, "Could not publish a game that is only stored locally.", "Publishing Match Online", JOptionPane.ERROR_MESSAGE)
             setEnabled(False)
Esempio n. 30
0
 def space_and_correct(event):
     text = self.text_area.getText()
     words = text.split(" ")
     string = words[-1]
     try:
         word = self.word_classifier.classify(string.lower())
         words[-1] = word.upper()
     except:
         JOptionPane.showMessageDialog(self, "Have you entered a character which is not in the alphabet?", 
                       "Could not Correct", 
                       JOptionPane.ERROR_MESSAGE)
         self.text_area.setText(text + " ")
         return
     newText = ""
     for w in words:
         newText = newText + w + " "
     self.text_area.setText(newText)
Esempio n. 31
0
    def installPlugin(self):
        try:
            self.installer.checkPluginDirectory()

            chooser = FileChooser()
            chooser.setExtensionFilter("jar", "Java archives")
            path = chooser.chooseFileToOpen(self.parentWindow)
            if path is None:
                return

            jarInfo = self.installer.data.getPluginInfo(path)

            replace = False
            conflicts = self.installer.findConflicts(jarInfo)
            if len(conflicts) == 1 and conflicts[0]['isInstalled']:
                replace = True
                message = ("Do you want to install the plugin\n%s?\n"
                           "It will replace %s!\n\n\n%s" %
                           (jarInfo['display'], conflicts[0]['display'],
                            jarInfo['description']))
            elif len(conflicts) > 0:
                message = (
                    "This plugin cannot be installed, because it conflicts with\n"
                    + "\n".join(p['display'] for p in conflicts))
                JOptionPane.showMessageDialog(self.parentWindow, message,
                                              TITLE, JOptionPane.ERROR_MESSAGE)
                return
            else:
                message = ("Do you want to install the plugin\n%s?\n\n%s" %
                           (jarInfo['display'], jarInfo['description']))

            if self.confirm(message):
                self.installer.install(jarInfo)
                self.notifyDone("%s was installed!" % jarInfo['title'])
        except (EnvironmentError, InvalidPluginError), exc:
            self.showErrorMessage(exc)
Esempio n. 32
0
def clickTakeStudentAttendence(event):
    global table
    global heading
   
    
    studentIdList =getStudentIdsOfThatTeacher()
    if(len(studentIdList) == 0):
        JOptionPane.showMessageDialog(None,'No any student List')
    else:    
        todayDate  = ex.getDate()
        datas = srv.getTodayStudentAttendence(todayDate,studentIdList)
        if(datas == False):
            # some  problem to get the data
            JOptionPane.showMessageDialog(None,"Failed to get the  Student attendence list ")
        elif(len(datas) == 0): # list is emp
            # means no datas is available, so we have to show thw attendence list for today
            takeTodayStudentAttendence(todayDate)

        elif(len(datas) != 0):
            # means we  had done the attendence  on today
            showStudentAttendenceSheetTeacherLogin()
            heading.setText("Update Attendence")
            tableModel = MyTableModel13(datas) # object has been created  ,the class is avialable in gui package and in showtable module
            table.setModel(tableModel) # in table we set the model
Esempio n. 33
0
    def on_zone_edited(self):
        """Read ways that delimit the favourite area and convert them to
           jts geometry
        """
        if self.modesComboBox.getSelectedIndex() == 0:
            mode = "rectangle"
        elif self.modesComboBox.getSelectedIndex() == 1:
            mode = "polygon"
        elif self.modesComboBox.getSelectedIndex() == 2:
            mode = "boundary"

        if mode in ("polygon", "boundary"):
            layer = self.get_new_zone_editing_layer()
            if layer is not None:
                self.app.mv.setActiveLayer(layer)
            else:
                if mode == "polygon":
                    msg = self.app.strings.getString("polygon_fav_layer_missing_msg")
                else:
                    msg = self.app.strings.getString("boundary_fav_layer_missing_msg")
                JOptionPane.showMessageDialog(self,
                                              msg,
                                              self.app.strings.getString("Warning"),
                                              JOptionPane.WARNING_MESSAGE)
                return

            dataset = self.app.mv.editLayer.data
            areaWKT = self.read_area_from_osm_ways(mode, dataset)
            if areaWKT is None:
                print "I could not read the new favourite area."
            else:
                if mode == "polygon":
                    self.polygonAsString = areaWKT
                else:
                    self.boundaryAsString = areaWKT
        return mode
def clickShowAllStudent(event):
    global table
    global heading
    global panel
    global btnUpdate

    datas = srv.showAllStudentList()
    print datas
    if (datas == False):
        # some  problem to get the data
        JOptionPane.showMessageDialog(None,
                                      "Failed to get the All student list ")
    elif (len(datas) == 0):
        # means no datas is available
        JOptionPane.showMessageDialog(None, "No student has been added ")
    elif (len(datas) != 0):
        # means we  get some data
        heading.setText("Student List")
        panel.add(heading)
        btnUpdate.setVisible(True)
        tableModel = MyTableModel3(
            datas
        )  # object has been created  ,the class is avialable in gui package and in showtable module
        table.setModel(tableModel)  # in table we set the model
Esempio n. 35
0
 def applyConfig(self):
     try:
         print("Connecting to '%s', index '%s'" %
               (self.confESHost, self.confESIndex))
         self.es = connections.create_connection(hosts=[self.confESHost])
         self.idx = Index(self.confESIndex)
         self.idx.doc_type(DocHTTPRequestResponse)
         if self.idx.exists():
             self.idx.open()
         else:
             self.idx.create()
         self.callbacks.saveExtensionSetting("elasticburp.host",
                                             self.confESHost)
         self.callbacks.saveExtensionSetting("elasticburp.index",
                                             self.confESIndex)
         self.callbacks.saveExtensionSetting("elasticburp.tools",
                                             str(self.confBurpTools))
         self.callbacks.saveExtensionSetting(
             "elasticburp.onlyresp", str(int(self.confBurpOnlyResp)))
     except Exception as e:
         JOptionPane.showMessageDialog(
             self.panel,
             "<html><p style='width: 300px'>Error while initializing ElasticSearch: %s</p></html>"
             % (str(e)), "Error", JOptionPane.ERROR_MESSAGE)
Esempio n. 36
0
def react(event):
    myAlpha = int(alphaTextField.text)
    myBeta = int(betaTextField.text)
    myPrima = int(primaTextField.text)
    myS = int(FBSize.text)
    global gP
    gP = myPrima
    global gB
    gB = myBeta

    try:
        hackTimer0 = timeit.default_timer()
        hckd = 0
        hckd = IndexCalculusFinale(myBeta, myPrima, myAlpha, myS)

        hackTimer1 = timeit.default_timer()
        timeReporter = "berhasil memecahkan kunci"
        timeReporter += "\n"
        timeReporter += "runtime ="
        timeReporter += str(hackTimer1 - hackTimer0)
        timeReporter += " s"
        print "ez = ", hckd
        jack = ceil(hckd)
        print "jack =", jack
        jack = int(jack)
        print "jack2 =", jack

        witness = IOController.expTester(myAlpha, jack, myPrima)
        print "witness = ", witness
        from IndexCalculus.step1 import gFB
        print "len =", len(gFB)
        #leng = len(gFB)
        #FBSize.text = str(leng)
        hckd = round(hckd, 3)

        print "hckd =", str(hckd)
        if (witness == myBeta):
            JOptionPane.showMessageDialog(mainForm, timeReporter, "info",
                                          JOptionPane.INFORMATION_MESSAGE)
            hckd = floor(hckd)
            hckd = int(hckd)
            myKey.text = str(hckd)
        else:
            myKey.text = str(hckd)
            timeReporter = "Kunci yang ditemukan tidak sesuai"
            timeReporter += "\n"
            timeReporter += "Runtime = "
            timeReporter += str(hackTimer1 - hackTimer0)
            timeReporter += " s"
            JOptionPane.showMessageDialog(mainForm, timeReporter,
                                          "Pemberitahuan",
                                          JOptionPane.ERROR_MESSAGE)
    except:
        JOptionPane.showMessageDialog(mainForm, "Gagal memecahkan kunci",
                                      "Pemberitahuan",
                                      JOptionPane.ERROR_MESSAGE)
Esempio n. 37
0
    def getMessage(self):
        """Transform the JSON format back to the binary protobuf message"""
        try:
            if self.message_type is None or not self.isModified():
                return self._original_content

            json_data = self._text_editor.getText().tostring()

            protobuf_data = blackboxprotobuf.protobuf_from_json(
                json_data, self.message_type
            )

            protobuf_data = self.encodePayload(protobuf_data)
            if "set_protobuf_data" in dir(user_funcs):
                result = user_funcs.set_protobuf_data(
                    protobuf_data,
                    self._original_content,
                    self._is_request,
                    self._content_info,
                    self._helpers,
                    self._request,
                    self._request_content_info,
                )
                if result is not None:
                    return result

            headers = self._content_info.getHeaders()
            return self._helpers.buildHttpMessage(headers, str(protobuf_data))

        except Exception as exc:
            self._callbacks.printError(traceback.format_exc())
            JOptionPane.showMessageDialog(
                self._component, "Error encoding protobuf: " + str(exc)
            )
            # Resets state
            return self._original_content
Esempio n. 38
0
    def actionPerformed(self, event):
        content, message, info, parameter = self.tab._current

        try:
            body = content[info.getBodyOffset():].tostring()

            if parameter is not None:
                param = self.tab.helpers.getRequestParameter(
                    content, parameter.getName())

                if param is not None:
                    rules = self.tab.extender.table.getParameterRules().get(
                        parameter.getName(), {})
                    body = param.getValue().encode('utf-8')

                    for rule in rules.get('before', []):
                        try:
                            body = rule(body)
                        except Exception as error:
                            traceback.print_exc(
                                file=self.tab.callbacks.getStderr())
                            raise error

            message = parse_message(self.descriptor, body)

            self.tab.editor.setText(str(message))
            self.tab.editor.setEditable(True)
            self.tab._current = (content, message, info, parameter)

        except Exception as error:
            title = "Error parsing message as %s!" % (self.descriptor.name, )
            JOptionPane.showMessageDialog(self.tab.getUiComponent(),
                                          error.message, title,
                                          JOptionPane.ERROR_MESSAGE)

        return
Esempio n. 39
0
    def _minimize(self, replace):
        try:
            self._fix_classloader_problems()
            seen_json = seen_xml = False
            request_info = self._helpers.analyzeRequest(self._request)
            current_req = self._request.getRequest()
            etalon = self._cb.makeHttpRequest(self._httpServ,
                                              current_req).getResponse()
            etalon2 = self._cb.makeHttpRequest(self._httpServ,
                                               current_req).getResponse()
            invariants = set(
                self._helpers.analyzeResponseVariations(
                    [etalon, etalon2]).getInvariantAttributes())
            invariants -= IGNORED_INVARIANTS
            print("Request invariants", invariants)

            current_req = self.minimize_headers(current_req, etalon,
                                                invariants, replace)
            current_req, seen_json, seen_xml = self.minimize_params(
                current_req, etalon, invariants, replace)

            if seen_json or seen_xml:
                current_req = self.minimize_json_or_xml(
                    current_req, etalon, invariants, seen_json, seen_xml,
                    replace)

            if replace:
                self.replace_live(current_req, True)
                JOptionPane.showMessageDialog(None, "Minimized request")
            else:
                self._cb.sendToRepeater(
                    self._httpServ.getHost(), self._httpServ.getPort(),
                    self._httpServ.getProtocol() == 'https', current_req,
                    "minimized")
        except:
            print traceback.format_exc()
Esempio n. 40
0
def getUserCheckboxSelections(title, message, selectionElements):
    elementStrings = [e.getName() for e in selectionElements]
    checkboxes = [JCheckBox(e) for e in elementStrings]
    l = [message]
    l.extend(checkboxes)

    input = JOptionPane.showMessageDialog(None, array(l, Object), title,
                                          JOptionPane.QUESTION_MESSAGE)
    checked = [e.isSelected() for e in checkboxes]
    res = []
    i = 0
    for check in checked:
        if check:
            res.append(selectionElements[i])
        i = i + 1
    return res
Esempio n. 41
0
def plotStation(standx, tw_all):
    good_plot = None
    xdelta = None
    # model group
    path_mdl = paths_mdl[standx]
    label = labels[standx]
    if label == 'X-Delta':  # special cross-delta flow case
        xdelta = 1
    #
    gsm = group_mdl.clone()  # start with a copy of model data
    gsm.filterBy(path_mdl)  # reduce to just this station
    if len(gsm) == 0:  # check there is data for this station
        JOptionPane.showMessageDialog(
            None, "Couldn't find model data for " + path_mdl)
        return
    # observed group
    path_obs = paths_obs[standx]
    if path_obs == 'X-Delta':  # special cross-delta flow case
        path_obs = 'rsac128|rsac121'
    #
    gso = group_obs.clone()
    gso.filterBy(path_obs)
    if len(gso) == 0:
        JOptionPane.showMessageDialog(
            None, "Couldn't find observed data for " + path_obs)
        return
    # check with time window field to see if it has a ok time window string
    # or says to use all intersecting data
    if tw_all:  # use intersection of obs and model data
        tw = TimeWindow.intersection(gsm[0].getTimeWindow(),
                                     gso[0].getTimeWindow())
        if tw == None:
            JOptionPane.showMessageDialog(None, "No overlapping data.")
            return
        else:
            twf.setText(repr(tw))
            return
        #
    #
    else:  # not all data, use time window
        try:
            tw = timeWindow(twf.getText())
        except Exception, e:
            JOptionPane.showMessageDialog(None, e.getMessage())
            twf.setText(repr(tw))
Esempio n. 42
0
 def help(self):
     if self.source:
         message = """   Teclas:
         'h' para esta ajuda
         'p' para salvar uma imagem
         'g' para salvar um GIF
         Tombe a lousa para lousa para limpar o desenho!"""
     else:
         message = """    Teclas:
         'h' para esta ajuda
         'p' para salvar uma imagem
         'g' para salvar um GIF
         'a' (-) ou 'd' (+) para o slider 1
         's' (-) ou 'w' (+) para o slider 2
          ←(-) ou  → (+) para o slider 3
          ↓  (-) ou  ↑  (+) para o slider 4
         [barra de espaço] para limpar o desenho"""
     ok = JOptionPane.showMessageDialog(None, message)
Esempio n. 43
0
    def create_new_zone(self, mode):
        """Read data entered on gui and create a new zone
        """
        name = self.nameTextField.getText()
        country = self.countryTextField.getText().upper()

        #error: name
        if name.replace(" ", "") == "":
            JOptionPane.showMessageDialog(self,
                                          self.app.strings.getString("missing_name_warning"),
                                          self.app.strings.getString("missing_name_warning_title"),
                                          JOptionPane.WARNING_MESSAGE)
            return False
        if name in [z.name for z in self.app.tempZones]:
            JOptionPane.showMessageDialog(self,
                                          self.app.strings.getString("duplicate_name_warning"),
                                          self.app.strings.getString("duplicate_name_warning_title"),
                                          JOptionPane.WARNING_MESSAGE)
            return False

        #zone type
        zType = mode
        #error: geometry type not defined
        if zType == "polygon" and self.polygonAsString == ""\
            or zType == "boundary" and self.boundaryAsString == "":
            JOptionPane.showMessageDialog(self,
                                          self.app.strings.getString("zone_not_correctly_build_warning"),
                                          self.app.strings.getString("zone_not_correctly_build_warning_title"),
                                          JOptionPane.WARNING_MESSAGE)
            return False

        #geometry string
        if zType == "rectangle":
            geomString = self.bboxPreviewTextField.getText()
        elif zType == "polygon":
            geomString = self.polygonAsString
        else:
            geomString = self.boundaryAsString

        self.app.newZone = Zone(self.app, name, zType, geomString, country)
        #self.app.newZone.print_info()
        return True
def clickShowStudents(event):
    global table
    global heading

    studentIds = getStudentIdsOfThatTeacher()
    if (len(studentIds) == 0):
        JOptionPane.showMessageDialog(None, "No student id")
    else:
        datas = srv.getStudentDeatailsByStudentIds(studentIds)
        if (datas == False):
            JOptionPane.showMessageDialog(
                None, "Failed to get the student details ")
        elif (len(datas) == 0):
            # means no any attendence is mained for that teacherId
            JOptionPane.showMessageDialog(None,
                                          "No any student is study to you ")
        elif (len(datas) != 0):
            heading.setText(" Student Details")
            tableModel = MyTableModel10(datas)
            table.setModel(tableModel)
Esempio n. 45
0
def  takeMonthYearForTeacherLoginedStudentAttendenceStatisticsInMonth(month,year):   
    
    idList = getStudentIdsOfThatTeacher()
    if(len(idList)== 0):
        JOptionPane.showMessageDialog(None,"Failed to get student for you")
    else:
        datas =srv.getStudentsAttendenceStatisticsByStudentIdInMonth(idList,month,year) 
        if(datas == False):
            # some  problem to get the data
            JOptionPane.showMessageDialog(None,"Failed to get the  student  attendence statistics ")
        elif(len(datas) == 0):
            # means no datas is available, so we have to show thw attendence list for today
            JOptionPane.showMessageDialog(None,"There is no any student to that teacher  ")
        elif(len(datas) != 0):
            # means we  get some data
            showStudentAttendenceSheetTeacherLogin()
            adjustFrame()
            
            tableModel = MyTableModel9(datas) # object has been created  ,the class is avialable in gui package and in showtable module
            table.setModel(tableModel) # in table we set the model
Esempio n. 46
0
    def onLogin(self, event):
        username = self.inputUsername.text
        password = self.inputPassowrd.text

        if (username == "" or password == ""):
            JOptionPane.showMessageDialog(self.frame,
                                          "Provide Input For All Fields",
                                          "Alert", JOptionPane.WARNING_MESSAGE)
        else:
            SELECT_SMT = "SELECT * from `accounts` WHERE `username` = ? AND `password` = ?"
            self.connection.executemany(SELECT_SMT, [username, password])
            if self.connection.fetchone() is None:
                JOptionPane.showMessageDialog(self.frame, "Wrong Credentials",
                                              "Alert",
                                              JOptionPane.ERROR_MESSAGE)
            else:
                user = User(username, password)
                user.print()
                JOptionPane.showMessageDialog(self.frame, "Login Sucessfull",
                                              "Success",
                                              JOptionPane.PLAIN_MESSAGE)
Esempio n. 47
0
 def error(self):
     JOptionPane.showMessageDialog(self.panel,
                                   "Debes introducir una URL o un fichero",
                                   "Error", JOptionPane.ERROR_MESSAGE)
Esempio n. 48
0
    def doInBackground(self):
        #print "\n- Checking for the latest version..."
        try:
            url = URL(self.app.scriptVersionUrl)
            uc = url.openConnection()
            ins = uc.getInputStream()
            p = Properties()
            p.load(ins)
            latestScriptVersion = p.getProperty("script")
            self.app.latestToolsVersion = p.getProperty("tools")
        except (UnknownHostException, SocketException):
            print "I can't connect to:\n%s" % url
            ins.close()
            return

        if latestScriptVersion == self.app.SCRIPTVERSION:
            #using latest script
            print "  already using the latest script version:", self.app.SCRIPTVERSION
            if self.app.latestToolsVersion == self.app.TOOLSVERSION:
                #using latest tools
                print "  already using the latest tools version:", self.app.TOOLSVERSION
                if self.mode != "auto":
                    JOptionPane.showMessageDialog(
                        self.app.preferencesFrame,
                        self.app.strings.getString("using_latest"))
                    return
            else:
                #not using latest tools
                print "  tools can be updated: %s -> %s" % (
                    self.app.TOOLSVERSION, self.app.latestToolsVersion)
                if self.app.mode == "stable":
                    infoString = self.app.strings.getString(
                        "update_tools_question")
                else:
                    infoString = self.app.strings.getString(
                        "dev_update_tools_question")
                answer = JOptionPane.showConfirmDialog(
                    Main.parent, infoString,
                    self.app.strings.getString("updates_available"),
                    JOptionPane.YES_NO_OPTION)
                if answer == 0:
                    #Download the updated tools data
                    print "\n- Update tools data"
                    try:
                        self.app.toolsProgressDialog
                    except AttributeError:
                        from java.awt import Dialog
                        self.app.toolsProgressDialog = ToolsProgressDialog(
                            Main.parent,
                            self.app.strings.getString(
                                "download_tools_updates"),
                            Dialog.ModalityType.APPLICATION_MODAL, self.app)
                    self.app.toolsProgressDialog.show()
        else:
            #not using latest script
            print "a new script version is available:\n%s -> %s" % (
                self.app.SCRIPTVERSION, latestScriptVersion)
            messageArguments = array(
                [self.app.SCRIPTVERSION, latestScriptVersion], String)
            formatter = MessageFormat("")
            if self.app.mode == "stable":
                formatter.applyPattern(
                    self.app.strings.getString("updates_warning"))
                infoBtnString = self.app.strings.getString("Visit_Wiki")
            else:
                formatter.applyPattern(
                    self.app.strings.getString("dev_updates_warning"))
                infoBtnString = self.app.strings.getString("Visit_git")
            msg = formatter.format(messageArguments)
            options = [
                self.app.strings.getString("Do_not_check_for_updates"),
                infoBtnString,
                self.app.strings.getString("cancel")
            ]
            answer = JOptionPane.showOptionDialog(
                Main.parent, msg,
                self.app.strings.getString("updates_available"),
                JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
                None, options, options[1])
            if answer == 0:
                self.app.properties.setProperty("check_for_update", "off")
                self.app.save_config(self)
            elif answer == 1:
                if self.app.mode == "stable":
                    url = self.app.SCRIPTWEBSITE
                else:
                    url = self.app.GITWEBSITE
                OpenBrowser.displayUrl(url)
Esempio n. 49
0
    def yaraScan(self):
        # If stdout has not yet been initialized, punt.
        if stdout is None:
            return

        # If the location of the yara executable and rules files are NULL, punt.
        if yara_rules is None or yara_path is None or yara_rules.size() == 0 or yara_rules.contains("< None >") or len(yara_path) == 0:
            JOptionPane.showMessageDialog(None, "Error: Please specify the path to the yara executable and rules file in "
                                                "the options tab.")
            return

        # If iRequestResponses is None, punt.
        if self.requestResponses is None:
            JOptionPane.showMessageDialog(None, "Error: No Request/Responses were selected.")
            return
        else:
            stdout.println("Processing %d item(s)." % len(self.requestResponses))

        # Get the OS temp folder
        os_name = System.getProperty("os.name").lower()

        temp_folder = None
        if "linux" in os_name:
            temp_folder = "/tmp"
        elif "windows" in os_name:
            temp_folder = os.environ.get("TEMP")
            if temp_folder is None:
                temp_folder = os.environ.get("TMP")

        if temp_folder is None:
            stdout.println("Error: Could not determine TEMP folder location.")
            return

        # Keep track of the number of matches.
        matchCount = 0

        # Process the site map selected messages
        for idx, iRequestResponse in enumerate(self.requestResponses):
            # Process the request
            request = iRequestResponse.getRequest()
            if request is not None:
                if len(request) > 0:
                    try:
                        # Yara does not support scanning from stdin so we will need to create a temp file and scan it
                        req_filename = os.path.join(temp_folder, "req_" + str(idx) + ".tmp")
                        req_file = open(req_filename, "wb")
                        req_file.write(request)
                        req_file.close()
                        for rules in yara_rules:
                            yara_req_output = subprocess.check_output([yara_path, rules, req_filename])
                            if yara_req_output is not None and len(yara_req_output) > 0:
                                ruleName = (yara_req_output.split())[0]
                                self._lock.acquire()
                                row = self._log.size()
                                # TODO: Don't add duplicate items to the table
                                self._log.add(LogEntry(ruleName, iRequestResponse, self._helpers.analyzeRequest(iRequestResponse).getUrl()))
                                self.fireTableRowsInserted(row, row)
                                self._lock.release()
                                matchCount += 1
                    except Exception as e:
                        JOptionPane.showMessageDialog(None, "Error running Yara. Please check your configuration and rules.")
                        return
                    finally:
                        # Remove the temp file
                        if req_file is not None:
                            req_file.close()
                        os.remove(req_filename)

            # Process the response
            response = iRequestResponse.getResponse()
            if response is not None:
                if len(response) > 0:
                    try:
                        # Yara does not support scanning from stdin so we will need to create a temp file and scan it
                        resp_filename = os.path.join(temp_folder, "resp_" + str(idx) + ".tmp")
                        resp_file = open(resp_filename, "wb")
                        resp_file.write(response)
                        resp_file.close()
                        for rules in yara_rules:
                            yara_resp_output = subprocess.check_output([yara_path, rules, resp_filename])
                            if yara_resp_output is not None and len(yara_resp_output) > 0:
                                ruleName = (yara_resp_output.split())[0]
                                self._lock.acquire()
                                row = self._log.size()
                                # TODO: Don't add duplicate items to the table
                                self._log.add(LogEntry(ruleName, iRequestResponse, self._helpers.analyzeRequest(iRequestResponse).getUrl()))
                                self.fireTableRowsInserted(row, row)
                                self._lock.release()
                                matchCount += 1
                    except Exception as e:
                        JOptionPane.showMessageDialog(None, "Error running Yara. Please check your configuration and rules.")
                        return
                    finally:
                        # Remove the temp file
                        if resp_file is not None:
                            resp_file.close()
                        os.remove(resp_filename)

        # Print a completion notification
        JOptionPane.showMessageDialog(None, "Yara scanning complete. %d rule(s) matched." % matchCount)
Esempio n. 50
0
from javax.swing import JOptionPane
from hec.heclib.dss import HecDss
from hec.script import Plot
import java

try : 
  try :
    myDss = HecDss.open("C:/temp/sample.dss")
    flow = myDss.get("/RUSSIAN/NR UKIAH/FLOW/01MAR2006/1HOUR//")
    plot = Plot.newPlot("Russian River at Ukiah")
    plot.addData(flow)
    plot.showPlot()
  except Exception, e :
    JOptionPane.showMessageDialog(None, ' '.join(e.args), "Python Error", JOptionPane.ERROR_MESSAGE)
  except java.lang.Exception, e :
    MessageBox.showError(e.getMessage(), "Java Error")
finally :
  myDss.done()
Esempio n. 51
0
    def on_downloadBtn_clicked(self, event=None):
        """On download button clicked download the errors in current or
           favourite area
        """
        #Get bbox from JOSM mapview
        self.mv = self.get_mapview()
        if self.mv is None:
            self.create_new_dataset_if_empty()
            Main.map.addToggleDialog(self.dlg)
            if self.favouriteZoneStatus:
                self.zoneBbox = self.favZone.bbox
            else:
                tmpbbox = [
                    float(x)
                    for x in Main.pref.get("osm-download.bounds").split(";")
                ]
                self.zoneBbox = [
                    tmpbbox[1], tmpbbox[0], tmpbbox[3], tmpbbox[2]
                ]
        else:
            if self.favouriteZoneStatus:
                self.zoneBbox = self.favZone.bbox
            else:
                self.zoneBbox = self.get_frame_bounds()

        #Warn the user when using a polygon or boundaries as favoutire area
        #for the first time, and a tool with a limited number of errors
        #that can be downloaded (KeepRight, Osmose) it could happen that
        # not all the errors are shown
        if self.favouriteZoneStatus and self.favZone.zType in ("polygon", "boundary")\
            and self.favAreaErrorsWarning and self.selectedTool.name in ("osmose", "keepright"):
            msg = self.strings.getString("favourite_area_errors_warning")
            JOptionPane.showMessageDialog(
                Main.parent,
                "<html><body><p style='width: 400px;'>%s</body></html>" % msg)
            self.properties.setProperty("favourite_area.errors_warning", "off")
            self.save_config(self)

        #Ask confirmation before errors downloading
        #msg = "Do you really want to downalod error data now?"
        #answer = JOptionPane.showConfirmDialog(Main.parent, msg)
        #if answer != 0:
        #    return

        #Show dialog with downloading and parsing progressbar
        self.downloadAndReadDlg.visible = True
        self.downloadAndReadDlg.progressBar.setIndeterminate(True)

        #Create download queue
        self.queue = []
        downloadsDict = {}
        for check in self.selectedChecks:
            tool = check.tool
            if tool not in downloadsDict:
                downloadsDict[tool] = []
            downloadsDict[tool].append(check)
        self.queue = []
        for tool, checksList in downloadsDict.iteritems():
            if tool.isLocal and tool.name != "favourites":
                self.queue = [{"checks": checksList, "url": ""}]
            else:
                self.queue.extend(
                    tool.download_urls((self.zoneBbox, checksList)))

        #self.print_queue()

        #Download and parse errors
        self.checksListIdx = 0
        self.execute_download()
Esempio n. 52
0
    #Check if qat_script directory is in Scripting Plugin directory
    SCRIPTDIR = check_if_script_in_default_directory()

if SCRIPTDIR is None:
    #Pop up a message telling the user to move the script
    #to a default dir
    move_script_warning()
else:
    #Procede with local import
    #print "- qat_script directory:", SCRIPTDIR
    sys.path.append(SCRIPTDIR)

    #Check that jts plugin is present (needed for favourite zone feature)
    if PluginHandler.getPlugin("jts") is None:
        JOptionPane.showMessageDialog(
            Main.parent, "Please, install 'jts' plugin from JOSM Preferences.",
            "Missing plugin: jts", JOptionPane.WARNING_MESSAGE)
    else:
        from config_reader import ConfigLoader, load_zones
        import update_checker
        from tools.allTools import AllTools
        from download_and_parse import DownloadTask, ParseTask
        from gui.QatMenu import QatMenu
        from gui.QatDialog import QatDialog
        from gui.OtherDialogs import DownloadAndReadDialog,\
                                     FalsePositiveDialog
        from gui.ErrorInfoDialog import ErrorInfoDialog
        from gui.PreferencesFrame import PreferencesFrame
        from error_layer import ErrorLayer
        app = App()
Esempio n. 53
0
 def _showErrorDialog(self, title, text):
     JOptionPane.showMessageDialog(self.parentWindow, text, title,
                                   JOptionPane.ERROR_MESSAGE)
            self.tagsToSet['isced:level'] = '2;3;4'
            self.level = 'secondary '
        self.tagsToSet['name'] = name.replace('  ',' ')
        #self.extraWDStatements.append(schoolStatement)
        #self.tagsToSet['isced:level'] = ''; level = ''

        return self.tagsToSet, self.extraWDStatements, self.level
							
districtIds={}
mv = getMapView()

if mv and mv.editLayer and mv.editLayer.data:
    selectedElements = mv.editLayer.data.getSelected()
    
    if not(selectedElements):
        JOptionPane.showMessageDialog(Main.parent, "Please select an element")
    else:
        WebResourceFetcherImpl.setUserAgent("Polyglot's JOSM Bot based on WDTK")
        connection = ApiConnection.getWikidataApiConnection()
        wbde = WikibaseDataEditor(connection, siteIri)
        if (BotSettings.USERNAME != None):
            connection.login(BotSettings.USERNAME, BotSettings.PASSWORD)
        print "###################################################################3"
        print 'logged in: '+str(connection.loggedIn) + ' as '+connection.getCurrentUser()
        wbsea = WbSearchEntitiesAction(connection, siteIri)
        noNewSchools = True
        coordStatements = {}  
        for element in selectedElements:    
            if element.getType()==dummyNode.getType(): type='node'
            if element.getType()==dummyWay.getType(): type='way'
            if element.getType()==dummyRelation.getType(): type='relation'
Esempio n. 55
0
 def showErrorMessage(self, exc):
     traceback.print_exc()
     excMessage = getattr(exc, 'strerror', str(exc))
     JOptionPane.showMessageDialog(self.parentWindow, excMessage, TITLE,
                                   JOptionPane.ERROR_MESSAGE)
Esempio n. 56
0
 def notifyDone(self, message):
     message = message + "\n" + RESTART_MESSAGE
     JOptionPane.showMessageDialog(self.parentWindow, message, TITLE,
                                   JOptionPane.INFORMATION_MESSAGE)
Esempio n. 57
0
 def notice(self, event):
     JOptionPane.showMessageDialog(
         self.frame,
         Disclaimer,
         'Notice',  # Previously "Disclaimer"
         JOptionPane.WARNING_MESSAGE)
Esempio n. 58
0
#
# HelloWorld.py  - displays the number of actually open layers
#
from javax.swing import JOptionPane
from org.openstreetmap.josm import Main


def getMapView():
    if Main.main == None:
        return None
    if Main.main.map == None:
        return None
    return Main.main.map.mapView


numlayers = 0
mv = getMapView()
if mv != None:
    numlayers = mv.getNumLayers()

JOptionPane.showMessageDialog(
    Main.parent, "[Python] Hello World! You have %s layer(s)." % numlayers)
Esempio n. 59
0
import javax.swing.ImageIcon as ImageIcon
import javax.swing.SwingUtilities as SwingUtilities
import thread
import jmri.jmrit.throttle.AddressListener as AddressListener
import jmri.jmrit.jython.Jynstrument as Jynstrument
import javax.swing.JOptionPane as JOptionPane
import javax.swing.JTextArea as JTextArea
import javax.swing.JFrame as JFrame
try:
    import wiiremotej.event.WiiRemoteListener as WiiRemoteListener
    import wiiremotej.event.WiiDeviceDiscoveryListener as WiiDeviceDiscoveryListener
    import wiiremotej.WiiRemoteJ as WiiRemoteJ
    import wiiremotej.event.WRButtonEvent as WRButtonEvent
except:
    JOptionPane.showMessageDialog(JFrame(), JTextArea(depErr),
                                  "Missing dependency",
                                  JOptionPane.ERROR_MESSAGE)


class WiimoteThrottle2(Jynstrument, PropertyChangeListener, AddressListener,
                       WiiDeviceDiscoveryListener, WiiRemoteListener,
                       Runnable):
    #Jynstrument main and mandatory methods
    def getExpectedContextClassName(self):
        return "jmri.jmrit.throttle.ThrottleWindow"

    def init(self):
        self.getContext().addPropertyChangeListener(
            self)  #ThrottleFrame change
        self.addressPanel = self.getContext().getCurrentThrottleFrame(
        ).getAddressPanel()
    else:
        return None


latlonRE = re.compile(
    r'LatLon\[lat=(?P<lat>-*\d+(\.\d\d\d\d\d\d)?)\d*,lon=(?P<lon>-*\d+(\.\d\d\d\d\d\d)?)\d*\]'
)
QinJSONRE = re.compile(r'"title":"(?P<qid>Q\d+)"')
mv = getMapView()
baseurl = 'https://www.wikidata.org/w/'

if mv and mv.editLayer and mv.editLayer.data:
    selectedElements = mv.editLayer.data.getSelected()

    if not (selectedElements):
        JOptionPane.showMessageDialog(Main.parent, "Please select an element")
    else:
        for element in selectedElements:
            housenumber = str(element.get('addr:housenumber'))
            street = str(element.get('addr:street'))
            district = str(element.get('addr:district'))
            county = str(element.get('addr:county'))
            subcounty = str(element.get('addr:subcounty'))
            city = str(element.get('addr:city'))
            parish = str(element.get('addr:parish'))
            amenity = str(element.get('amenity'))
            isced_level = str(element.get('isced:level'))
            operator_type = str(element.get('operator:type'))
            name = str(element.get('name'))
            wikidata = str(element.get('wikidata'))
            print name