예제 #1
0
	def actionPerformed(self,actionEvent):
		ws_data_analysis_controller = self.ws_lw_acquisition_controller.ws_data_analysis_controller
		linac_wizard_document = self.ws_lw_acquisition_controller.linac_wizard_document
		records_table = ws_data_analysis_controller.records_table
		index = records_table.getSelectedRow()
		#print "debug ws record for writing index=",index
		if(index < 0): return
		ws_records_table_model = ws_data_analysis_controller.ws_records_table_model
		ws_scan_and_fit_record = ws_records_table_model.ws_rec_table_element_arr[index]
		fl_name = ws_scan_and_fit_record.ws_node.getId()
		if(ws_scan_and_fit_record.ws_direction == WS_DIRECTION_HOR): fl_name += "_hor.dat" 
		if(ws_scan_and_fit_record.ws_direction == WS_DIRECTION_VER): fl_name += "_ver.dat"
		fl_name = fl_name.replace(":","_")
		#print "debug file=",fl_name
		x_arr = []
		y_arr = []
		y_fit_arr = []
		x_min = ws_scan_and_fit_record.X_MIN.getValue()
		x_max = ws_scan_and_fit_record.X_MAX.getValue()
		x_center = ws_scan_and_fit_record.X_CENTER.getValue()
		for ind in range(ws_scan_and_fit_record.gd_wf.getNumbOfPoints()):
			x = ws_scan_and_fit_record.gd_wf.getX(ind)
			y = ws_scan_and_fit_record.gd_wf.getY(ind)
			if(x >= x_min and x <= x_max):
				x_arr.append(x-x_center)
				y_arr.append(y)
				y_fit = ws_scan_and_fit_record.gd_fit_wf.getValueY(x)
				y_fit_arr.append(y_fit)
		#----normalization
		if(len(x_arr) > 1):
			x_step = (x_arr[len(x_arr)-1] - x_arr[0])/(len(x_arr)-1)
			sum_val = 0.
			for ind in range(len(x_arr)):
				sum_val += math.fabs(y_arr[ind])*x_step
			if(sum_val > 0.):
				for ind in range(len(x_arr)):
					y_arr[ind] /= sum_val
					y_fit_arr[ind] /= sum_val
		#----dump into the ASCII file---------------------
		fl_out_path = constants_lib.const_path_dict["LINAC_WIZARD_FILES_DIR_PATH"]
		fl_name = fl_out_path+"/"+fl_name
		fl_out = File(fl_name)
		fc = JFileChooser(fl_name)
		fc.setDialogTitle("Write WS/LW data into the ASCII file ...")
		fc.setApproveButtonText("Write")
		fl_filter = FileNameExtensionFilter("WS/LW Data",["dat",])
		fc.setFileFilter(fl_filter)
		fc.setSelectedFile(fl_out)
		returnVal = fc.showOpenDialog(linac_wizard_document.linac_wizard_window.frame)
		if(returnVal == JFileChooser.APPROVE_OPTION):
			fl_out = fc.getSelectedFile()
			fl_path = fl_out.getPath()
			if(fl_path.rfind(".dat") != (len(fl_path) - 4)):
				fl_path = open(fl_out.getPath()+".dat")
			fl_out = open(fl_path,"w")
			fl_out. write(" ind   x[mm]  y[mm]  y_fit[mm] \n")
			for ind in range(len(x_arr)):
				s = " %2d   %12.5g   %12.5g   %12.5g "%(ind,x_arr[ind],y_arr[ind],y_fit_arr[ind])
				fl_out. write(s + "\n")
			fl_out.close()
예제 #2
0
 def test_with_two_characters(self):
     #test with just two letters so A and B are copied to a
     #special dir that is deleted after the test
     base_dir = File("../../character_examples")
     test_dir = File(base_dir, "test")
     a_dir = File(base_dir, "A")
     b_dir = File(base_dir, "B")
     shutil.copytree(a_dir.getPath(), File(test_dir, "A").getPath())
     shutil.copytree(b_dir.getPath(), File(test_dir, "B").getPath())
     extracor = SimpleImageFeatureExtractor(nr_of_divisions=7,
                                            size_classification_factor=1.3)
     #Extract features
     training_examples, test_examples = extracor.extract_training_and_test_examples(
         test_dir.getPath(), 90, 10)
     #print("training examples", training_examples)
     #print("testing examples", test_examples)
     classifier = CharacterClassifier(training_examples,
                                      nr_of_hmms_to_try=1,
                                      fraction_of_examples_for_test=0.3,
                                      feature_extractor=extracor,
                                      train_with_examples=False)
     before = classifier.test(test_examples)
     #Test serialization
     classifier_string = classifier.to_string()
     reborn_classifier = CharacterClassifier(
         from_string_string=classifier_string)
     reborn_classifier_test_result = reborn_classifier.test(test_examples)
     if (reborn_classifier_test_result == before):
         pass
     else:
         raise "Something is wrong with the test result"
     classifier.train()
     after = classifier.test(test_examples)
     print("test_with_two_characters", "before", before, "after", after)
     shutil.rmtree(test_dir.getPath())
예제 #3
0
 def test_with_two_characters(self):
     #test with just two letters so A and B are copied to a 
     #special dir that is deleted after the test
     base_dir = File("../../character_examples")
     test_dir = File(base_dir,"test")
     a_dir = File(base_dir,"A")
     b_dir = File(base_dir,"B")
     shutil.copytree(a_dir.getPath(), File(test_dir,"A").getPath())
     shutil.copytree(b_dir.getPath(), File(test_dir,"B").getPath())
     extracor = SimpleImageFeatureExtractor(nr_of_divisions=7, 
                                            size_classification_factor=1.3)
     #Extract features
     training_examples, test_examples = extracor.extract_training_and_test_examples(test_dir.getPath(), 90, 10)
     #print("training examples", training_examples)
     #print("testing examples", test_examples)
     classifier = CharacterClassifier(training_examples, 
                                      nr_of_hmms_to_try = 1, 
                                      fraction_of_examples_for_test = 0.3,
                                      feature_extractor=extracor,
                                      train_with_examples=False)
     before = classifier.test(test_examples)
     #Test serialization
     classifier_string = classifier.to_string()
     reborn_classifier = CharacterClassifier(from_string_string=classifier_string)
     reborn_classifier_test_result = reborn_classifier.test(test_examples)
     if(reborn_classifier_test_result==before):
         pass
     else:
         raise "Something is wrong with the test result"
     classifier.train()
     after = classifier.test(test_examples)
     print("test_with_two_characters", "before", before, "after", after)
     shutil.rmtree(test_dir.getPath())
예제 #4
0
def join(path, *args):
    """Join two or more pathname components, inserting os.sep as needed"""
    f = File(path)
    for a in args:
	g = File(a)
	if g.isAbsolute() or len(f.getPath()) == 0:
	    f = g
	else:
	    f = File(f, a)
    return f.getPath()
예제 #5
0
def join(path, *args):
    """Join two or more pathname components, inserting os.sep as needed"""
    path = _tostr(path, "join")
    f = File(path)
    for a in args:
        a = _tostr(a, "join")
        g = File(a)
        if g.isAbsolute() or len(f.getPath()) == 0:
            f = g
        else:
            if a == "":
                a = os.sep
            f = File(f, a)
    return asPyString(f.getPath())
예제 #6
0
 def join(path, *args):
   if sys.platform.startswith('java'):
     from java.io import File
     f = File(path)
     for a in args:
       g = File(a)
       if g.isAbsolute() or len(f.getPath()) == 0:
         f = g
       else:
         f = File(f, a)
     return f.getPath()
   else:
     import os
     return os.path.join(path, *args)
예제 #7
0
def join(path, *args):
    """Join two or more pathname components, inserting os.sep as needed"""
    path = _tostr(path, "join")
    f = File(path)
    for a in args:
        a = _tostr(a, "join")
        g = File(a)
        if g.isAbsolute() or len(f.getPath()) == 0:
            f = g
        else:
            if a == "":
                a = os.sep
            f = File(f, a)
    return asPyString(f.getPath())
    def extract_opss_wallet(self):
        """
        Extract the and unzip the OPSS wallet, if present, and return the path to the wallet directory.
        :return: the path to the extracted wallet, or None if no wallet was found
        :raises: BundleAwareException of the appropriate type: if an error occurs
        """
        _method_name = 'extract_opss_wallet'
        self.__logger.entering(class_name=self.__class_name,
                               method_name=_method_name)

        wallet_path = None
        for archive_file in self.__archive_files[::-1]:
            atp_wallet_zipentry = archive_file.getOPSSWallet()
            if atp_wallet_zipentry:
                wallet_dir = File(self.__domain_home, 'opsswallet')
                wallet_dir.mkdirs()
                wallet_path = wallet_dir.getPath()
                FileUtils.extractZipFileContent(archive_file,
                                                atp_wallet_zipentry,
                                                wallet_path)
                break

        self.__logger.exiting(class_name=self.__class_name,
                              method_name=_method_name,
                              result=wallet_path)
        return wallet_path
예제 #9
0
    def extract_obj(self, file_path, res, offset):
        try:
            f = File(file_path)

            # check same name file.
            counter = 0
            while True:

                # The same file name is not exists.
                if not f.exists():
                    break

                # Count up the file name.
                counter += 1
                stem = u"".join(file_path.split(u".")[:-1])
                ex = file_path.split(u".")[-1]

                _file_path = u"{}({}).{}".format(stem, counter, ex)
                f = File(_file_path)

            fos = FileOutputStream(f)

            fos.write(res[offset:])
            self._stdout.printf("save as \"%s\".\n\n", f.getPath())

            fos.close()

        except Exception as e:
            self._stderr.println("[!] In extract_obj.")
            self._stderr.println(e)
예제 #10
0
    def writeResponseToStatusResponseCache(self, jobId, jobStatus):
        curationStatusRespones = File(FascinatorHome.getPath() +
                                      "/curation-status-responses")
        if curationStatusRespones.exists():
            FileUtils.forceMkdir(curationStatusRespones)

        FileUtils.writeStringToFile(
            File(curationStatusRespones.getPath() +
                 "/" + Integer(jobId).toString() + ".json"),
            jobStatus.toString(True))
예제 #11
0
    def _update_server(self, name, dictionary, config_location):
        _method_name = '_update_server'

        # these imports are local, since they are only present in JRF environments.
        # this method is only called after that check has been made.
        from oracle.core.ojdl.weblogic.ODLConfiguration import CONFIG_DIR
        from oracle.core.ojdl.weblogic.ODLConfiguration import CONFIG_FILE
        from oracle.core.ojdl.logging.config import LoggingConfigurationDocument

        config_dir = File(self.model_context.get_domain_home(), CONFIG_DIR)
        server_dir = File(config_dir, name)
        config_file = File(server_dir, CONFIG_FILE)

        try:
            FileUtils.validateWritableFile(config_file.getPath())
            document = LoggingConfigurationDocument(FileInputStream(config_file))

            # configure AddJvmNumber
            add_jvm_number = dictionary_utils.get_element(dictionary, _ADD_JVM_NUMBER)
            if add_jvm_number is not None:
                document.setAddJvmNumber(alias_utils.convert_boolean(add_jvm_number))

            # configure HandlerDefaults
            handler_defaults = dictionary_utils.get_dictionary_element(dictionary, _HANDLER_DEFAULTS)
            if handler_defaults is not None:
                for key in handler_defaults:
                    value = handler_defaults[key]
                    document.setHandlerDefault(key, _get_property_text(value))

            # configure Handlers
            # do these before loggers, in case new handlers are assigned to loggers
            existing_handler_names = document.getHandlerNames()
            handlers = dictionary_utils.get_dictionary_element(dictionary, _HANDLER)
            if handlers is not None:
                for handler_name in handlers:
                    handler = handlers[handler_name]
                    self._configure_handler(handler_name, handler, document, existing_handler_names, config_location)

            # configure Loggers
            existing_logger_names = document.getLoggerNames()
            loggers = dictionary_utils.get_dictionary_element(dictionary, _LOGGER)
            if loggers is not None:
                for logger_name in loggers:
                    logger = loggers[logger_name]
                    self._configure_logger(logger_name, logger, document, existing_logger_names, config_location)

            document.writeDocument(FileOutputStream(config_file))

        except (ParserConfigurationException, SAXException, IOException, IllegalArgumentException), ex:
            self.logger.severe('WLSDPLY-19707', name, ex.getLocalizedMessage(),
                               class_name=self.__class_name, method_name=_method_name)
예제 #12
0
 def saveSprite(self, spritefileName, spriteName, bitmap):
 
     # Create a subdirectory of the SpriteViewer directory for the current
     # set of sprites.
     subDir = File(Environment.DIRECTORY_DOWNLOADS, "SpriteViewer")
     
     outputFile = Files.createExternalFile(subDir.getPath(),
         spritefileName, spriteName, "", ".png")
     
     stream = BufferedOutputStream(FileOutputStream(outputFile))
     bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream)
     stream.flush()
     
     Toast.makeText(self, "Saved " + outputFile.getPath(), Toast.LENGTH_LONG).show()
	def actionPerformed(self,actionEvent):
		self.scl_long_tuneup_controller.getMessageTextField().setText("")	
		rightNow = Calendar.getInstance()
		date_format = SimpleDateFormat("MM.dd.yyyy")
		time_str = date_format.format(rightNow.getTime())				
		fc = JFileChooser(constants_lib.const_path_dict["XAL_XML_ACC_FILES_DIRS_PATH"])
		fc.setDialogTitle("Save SCL data into the SCL_new.xdxf file")
		fc.setApproveButtonText("Save")
		fl_filter = FileNameExtensionFilter("SCL Acc File",["xdxf",])
		fc.setFileFilter(fl_filter)
		fc.setSelectedFile(File("SCL_"+time_str+".xdxf"))		
		returnVal = fc.showOpenDialog(self.scl_long_tuneup_controller.linac_wizard_document.linac_wizard_window.frame)
		if(returnVal == JFileChooser.APPROVE_OPTION):
			fl_out = fc.getSelectedFile()
			fl_path = fl_out.getPath()
			if(fl_path.rfind(".xdxf") != (len(fl_path) - 5)):
				fl_out = File(fl_out.getPath()+".xdxf")	
			#---------prepare the XmlDataAdaptor 
			root_DA = XmlDataAdaptor.newEmptyDocumentAdaptor()
			scl_DA = root_DA.createChild("xdxf")	
			scl_DA.setValue("date",time_str)
			scl_DA.setValue("system","sns")
			scl_DA.setValue("version","2.0")
			#---- SCLMed	
			seq_name_arr = ["SCLMed","SCLHigh","HEBT1"]
			for seq_name in seq_name_arr:
				accl = self.scl_long_tuneup_controller.linac_wizard_document.accl
				seq = accl.findSequence(seq_name)
				cavs = seq.getAllNodesWithQualifier(AndTypeQualifier().and((OrTypeQualifier()).or(SCLCavity.s_strType)))
				quads = seq.getAllNodesWithQualifier(AndTypeQualifier().and((OrTypeQualifier()).or(Quadrupole.s_strType)))
				scl_seq_DA = scl_DA.createChild("sequence")
				scl_seq_DA.setValue("id",seq.getId())
				for quad in quads:
					node_DA = scl_seq_DA.createChild("node")
					node_DA.setValue("id",quad.getId())
					attr_DA = node_DA.createChild("attributes")
					field_DA = attr_DA.createChild("magnet")
					scl_quad_fields_dict_holder = self.scl_long_tuneup_controller.scl_long_tuneup_init_controller.scl_quad_fields_dict_holder
					field_DA.setValue("dfltMagFld",str(scl_quad_fields_dict_holder.quad_field_dict[quad]))
				for cav in cavs:
					node_DA = scl_seq_DA.createChild("sequence")
					node_DA.setValue("id",cav.getId())
					attr_DA = node_DA.createChild("attributes")
					rf_cav_DA = attr_DA.createChild("rfcavity")
					cav_wrappper = self.scl_long_tuneup_controller.getCav_WrapperForCavId(cav.getId())
					(amp,phase) =  (cav_wrappper.designAmp,cav_wrappper.designPhase)
					rf_cav_DA.setValue("amp",float("%8.5f"%amp))
					rf_cav_DA.setValue("phase",float("%8.3f"%phase))
			root_DA.writeTo(fl_out)		
예제 #14
0
	def actionPerformed(self,actionEvent):
		fc = JFileChooser(constants_lib.const_path_dict["LINAC_WIZARD_FILES_DIR_PATH"])
		fc.setDialogTitle("Save data into the file ...")
		fc.setApproveButtonText("Save")
		fl_filter = FileNameExtensionFilter("SCL Wizard",["sclw",])
		fc.setFileFilter(fl_filter)
		returnVal = fc.showOpenDialog(self.linac_wizard_document.linac_wizard_window.frame)
		if(returnVal == JFileChooser.APPROVE_OPTION):
			fl_out = fc.getSelectedFile()
			fl_path = fl_out.getPath()
			if(fl_path.rfind(".sclw") != (len(fl_path) - 5)):
				fl_out = File(fl_out.getPath()+".sclw")
			io_controller = self.linac_wizard_document.getIO_Controller()
			io_controller.writeData(fl_out.toURI().toURL())
			io_controller.old_fl_out_name = fl_out.getName()
			self.linac_wizard_document.linac_wizard_window.setTitle(io_controller.old_fl_out_name)
	def actionPerformed(self,actionEvent):
		fc = JFileChooser(constants_lib.const_path_dict["LINAC_WIZARD_FILES_DIR_PATH"])
		fc.setDialogTitle("Save data into the file ...")
		fc.setApproveButtonText("Save")
		fl_filter = FileNameExtensionFilter("SCL Wizard",["sclw",])
		fc.setFileFilter(fl_filter)
		returnVal = fc.showOpenDialog(self.linac_wizard_document.linac_wizard_window.frame)
		if(returnVal == JFileChooser.APPROVE_OPTION):
			fl_out = fc.getSelectedFile()
			fl_path = fl_out.getPath()
			if(fl_path.rfind(".sclw") != (len(fl_path) - 5)):
				fl_out = File(fl_out.getPath()+".sclw")
			io_controller = self.linac_wizard_document.getIO_Controller()
			io_controller.writeData(fl_out.toURI().toURL())
			io_controller.old_fl_out_name = fl_out.getName()
			self.linac_wizard_document.linac_wizard_window.setTitle(io_controller.old_fl_out_name)
	def actionPerformed(self,actionEvent):
		self.scl_long_tuneup_controller.getMessageTextField().setText("")		
		fc = JFileChooser(constants_lib.const_path_dict["LINAC_WIZARD_FILES_DIR_PATH"])
		fc.setDialogTitle("Save SCL Table data into ASCII file")
		fc.setApproveButtonText("Save")
		fl_filter = FileNameExtensionFilter("ASCII *.dat File",["dat",])
		fc.setFileFilter(fl_filter)
		returnVal = fc.showOpenDialog(self.scl_long_tuneup_controller.linac_wizard_document.linac_wizard_window.frame)
		if(returnVal == JFileChooser.APPROVE_OPTION):
			fl_out = fc.getSelectedFile()
			fl_path = fl_out.getPath()
			if(fl_path.rfind(".dat") != (len(fl_path) - 4)):
				fl_out = File(fl_out.getPath()+".dat")			
			buffer_out = BufferedWriter(FileWriter(fl_out))
			txt = "# cav  pos  cav_amp_epics  cav_amp_model  cav_phase rf_gap_avg_phase"
			txt += " phase_offset real_offset eKin_in  eKin_out "
			txt += " delta_eKin_in_out_keV bpm_eKin_out model_eKin_out delta_eKin_fit_keV  E0TL_MeV"
			buffer_out.write(txt)
			buffer_out.newLine()
			buffer_out.flush()
			cav_wrappers = self.scl_long_tuneup_controller.cav_wrappers
			for cav_ind in range(len(cav_wrappers)):
				cav_wrapper = cav_wrappers[cav_ind]
				txt = str(cav_ind+1)+" "
				txt += cav_wrapper.cav.getId()+" %8.3f "%cav_wrapper.pos+" %12.5g "%cav_wrapper.initLiveAmp
				txt += " %12.5g "%cav_wrapper.designAmp + " %8.3f "%cav_wrapper.designPhase 
				txt += " %8.3f "%cav_wrapper.avg_gap_phase + " %8.3f "%cav_wrapper.scanPhaseShift
				txt += " %8.3f "%cav_wrapper.real_scanPhaseShift
				txt += " %12.5g "%cav_wrapper.eKin_in + " %12.5g "%cav_wrapper.eKin_out
				dE = 0.
				if(cav_ind != 0):
					dE = (cav_wrapper.eKin_in - cav_wrappers[cav_ind-1].eKin_out)*1000.
				txt += " %12.5g "%dE + " %12.5g "%cav_wrapper.bpm_eKin_out+ " %12.5g "%cav_wrapper.model_eKin_out
				txt += "% 6.1f"%(1000.*cav_wrapper.eKin_err)
				E0TL = 0.
				if(len(cav_wrapper.energy_guess_harm_funcion.getParamArr()) > 1):
					E0TL = cav_wrapper.energy_guess_harm_funcion.getParamArr()[1]
				txt += " %12.5g "%E0TL
				buffer_out.write(txt)
				buffer_out.newLine()
			#---- end of writing
			buffer_out.flush()
			buffer_out.close()
예제 #17
0
    def _upload_file_node(self, context, node, destination, filename,
            abs_path=False):
        ssh = context.getUtils().sshForNode().apply(node)
        path = filename if abs_path else self.__scriptdir + "/" + filename
        tmpfile = os.path.exists(path + ".tmp")
        file = File(path + ".tmp" if tmpfile else path)

        if abs_path:
            filename = os.path.basename(path)

        try:
            ssh.connect()
            log.info("Uploading file %s..." % filename)
            ssh.put(destination + "/" + filename,
                    Payloads.newFilePayload(file))
        finally:
            if ssh:
                ssh.disconnect()
            if tmpfile:
                os.remove(file.getPath())
예제 #18
0
    def writeResponseToStatusResponseCache(self, jobId, jobStatus):
        curationStatusRespones = File(FascinatorHome.getPath()+ "/curation-status-responses")
        if curationStatusRespones.exists():
            FileUtils.forceMkdir(curationStatusRespones)

        FileUtils.writeStringToFile(File(curationStatusRespones.getPath()+ "/" + Integer(jobId).toString() + ".json"), jobStatus.toString(True))
예제 #19
0
def makePDF(geometry=None,
            bounds=None,
            background=None,
            scale=1,
            filename=None,
            is3d=0):
    """
	makePDF exports PLines to a PDF file.

	Every parameter is actually optional. 
	X{geometry} specifies a list of PLines to draw, if it's
	missing, then everything on the canvas gets exported (you can set .notForExport on a line to
	make sure it doesn't get exported). 

	X{bounds} specifies a Rect or a PLine that encloses all of the geometry 
	that gets drawn. It becomes the "paper size" of the PDF that's exported. If it's ommitted then the 
	bounds of the geometry that's going to get exported is used instead. One trick is to make a PLine 
	with a rect, then pass that PLine into here as the parameter bounds.

	X{background} is an optional background color. 

	X{filename} is an optional filename (a temp file is used if this is omitted)

	X{scale} increases the "dpi" of the canvas, making the paper and the drawing bigger (while keeping the line thickness the same).
	
	"""

    if (not geometry):
        geometry = sum([
            x.lines for x in getSelf().all if hasattr(x, "lines") and x.lines
        ], [])
    else:
        try:
            geometry = sum(geometry, [])
        except:
            pass

    something = geometry

    pdfContext = BasePDFGraphicsContext()

    if (not is3d):
        ld = SimplePDFLineDrawing()
        ld.installInto(pdfContext)
        SimplePDFImageDrawing().installInto(pdfContext, ld)
        ctx = SimplePDFLineDrawing
    else:
        ld = SimplePDFLineDrawing_3d()
        ld.installInto(pdfContext)
        #SimplePDFImageDrawing().installInto(pdfContext, ld)
        ctx = SimplePDFLineDrawing_3d

    if (bounds == None):
        for n in something:
            b = LineUtils().fastBounds(n)
            if (b):
                b = Rect(b[0].x, b[0].y, b[1].x - b[0].x, b[1].y - b[0].y)
                if (b.w > 0 or b.h > 0):
                    print b
                    bounds = Rect.union(b, bounds)
        if (not bounds):
            print "makePDF error: no bounds specified"
            return None

        bounds.x -= 2
        bounds.y -= 2
        bounds.w += 4
        bounds.h += 4

    if (isinstance(bounds, PLine)):
        bounds = bounds.bounds()

    if (isinstance(bounds, CachedLine)):
        bounds = bounds.bounds2()

    print bounds
    pdfContext.paperWidth = bounds.w * scale
    pdfContext.paperHeight = bounds.h * scale

    if (background):
        pdfContext.getGlobalProperties().paperColor = background

    ctx.outputTransform.z = (-bounds.x) * pdfContext.paperWidth / bounds.w
    ctx.outputTransform.w = (bounds.y +
                             bounds.h) * pdfContext.paperHeight / bounds.h
    ctx.outputTransform.x = pdfContext.paperWidth / bounds.w
    ctx.outputTransform.y = -pdfContext.paperHeight / bounds.h

    if (not filename):
        name = File.createTempFile("field", ".pdf", None)
    else:
        name = File(filename)

    pdfContext.drawTo = name

    pdfContext.windowDisplayEnter()
    for n in something:
        pdfContext.submitLine(n, n.getProperties())
    pdfContext.windowDisplayExit()

    return name.getPath()
예제 #20
0
파일: TweakTools.py 프로젝트: EQ4/Field
def makePDF(geometry = None, bounds = None, background = None, scale=1, filename=None, is3d=0):
	"""
	makePDF exports PLines to a PDF file.

	Every parameter is actually optional. 
	X{geometry} specifies a list of PLines to draw, if it's
	missing, then everything on the canvas gets exported (you can set .notForExport on a line to
	make sure it doesn't get exported). 

	X{bounds} specifies a Rect or a PLine that encloses all of the geometry 
	that gets drawn. It becomes the "paper size" of the PDF that's exported. If it's ommitted then the 
	bounds of the geometry that's going to get exported is used instead. One trick is to make a PLine 
	with a rect, then pass that PLine into here as the parameter bounds.

	X{background} is an optional background color. 

	X{filename} is an optional filename (a temp file is used if this is omitted)

	X{scale} increases the "dpi" of the canvas, making the paper and the drawing bigger (while keeping the line thickness the same).
	
	"""

	if (not geometry):
		geometry = sum([x.lines for x in getSelf().all if hasattr(x, "lines") and x.lines], [])
	else:
		try:
			geometry = sum(geometry, [])
		except:
			pass

	something = geometry

	pdfContext = BasePDFGraphicsContext()
	
	if (not is3d):
		ld = SimplePDFLineDrawing()
		ld.installInto(pdfContext)
		SimplePDFImageDrawing().installInto(pdfContext, ld)
		ctx = SimplePDFLineDrawing
	else:
		ld = SimplePDFLineDrawing_3d()
		ld.installInto(pdfContext)		
		#SimplePDFImageDrawing().installInto(pdfContext, ld)
		ctx = SimplePDFLineDrawing_3d

	if (bounds==None):
		for n in something:
			b = LineUtils().fastBounds(n)
			if (b):
				b = Rect(b[0].x,b[0].y, b[1].x-b[0].x, b[1].y-b[0].y)
				if (b.w>0 or b.h>0):
					print b
					bounds = Rect.union(b, bounds)
		if (not bounds):
			print "makePDF error: no bounds specified"
			return None

		bounds.x-=2
		bounds.y-=2
		bounds.w+=4
		bounds.h+=4

	if (isinstance(bounds, PLine)):
		bounds = bounds.bounds()

	if (isinstance(bounds, CachedLine)):
		bounds = bounds.bounds2()

	print bounds
	pdfContext.paperWidth=bounds.w*scale
	pdfContext.paperHeight=bounds.h*scale
	
	if (background):
		pdfContext.getGlobalProperties().paperColor = background

	ctx.outputTransform.z=(-bounds.x)*pdfContext.paperWidth/bounds.w
	ctx.outputTransform.w=(bounds.y+bounds.h)*pdfContext.paperHeight/bounds.h
	ctx.outputTransform.x=pdfContext.paperWidth/bounds.w
	ctx.outputTransform.y=-pdfContext.paperHeight/bounds.h

	if (not filename):
		name = File.createTempFile("field", ".pdf", None)
	else:
		name = File(filename)

	pdfContext.drawTo = name

	pdfContext.windowDisplayEnter()
	for n in something:
		pdfContext.submitLine(n, n.getProperties())
	pdfContext.windowDisplayExit()

	return name.getPath()
예제 #21
0
from java.nio.file import Paths
from java.nio.file import Path
from java.io import File

p=Paths.get("home","pi","Desktop","jython-prac-prog","stram_jython","file2.txt")

x = p.toFile()

x = File(x.getName())
print (x.isFile())

f = File("image1.png") 
print (f.getName())
print ("length",f.length())
print ("Execute",f.canExecute())
print ("read",f.canRead())
print ("write",f.canWrite())
print ("path",f.getPath())
print ("Directory",f.isDirectory())
print ("parent",f.getParent())

예제 #22
0
def generate_k8s_script(model_context, token_dictionary, model_dictionary, exception_type):
    """
    Generate a shell script for creating k8s secrets.
    :param model_context: used to determine output directory
    :param token_dictionary: contains every token
    :param model_dictionary: used to determine domain UID
    :param exception_type: type of exception to throw
    """

    # determine the domain name and UID
    topology = dictionary_utils.get_dictionary_element(model_dictionary, TOPOLOGY)
    domain_name = dictionary_utils.get_element(topology, NAME)
    if domain_name is None:
        domain_name = DEFAULT_WLS_DOMAIN_NAME

    domain_uid = k8s_helper.get_domain_uid(domain_name)
    comment = exception_helper.get_message("WLSDPLY-01665")
    script_hash = {'domainUid': domain_uid, 'topComment': comment}

    # build a map of secret names (jdbc-generic1) to keys (username, password)
    secret_map = {}
    for property_name in token_dictionary:
        halves = property_name.split(':', 1)
        value = token_dictionary[property_name]
        if len(halves) == 2:
            secret_name = halves[0]

            # admin credentials are inserted later, at the top of the list
            if secret_name == WEBLOGIC_CREDENTIALS_SECRET_NAME:
                continue

            secret_key = halves[1]
            if secret_name not in secret_map:
                secret_map[secret_name] = {}
            secret_keys = secret_map[secret_name]
            secret_keys[secret_key] = value

    # update the hash with secrets and paired secrets
    secrets = []
    paired_secrets = [_build_secret_hash(WEBLOGIC_CREDENTIALS_SECRET_NAME, USER_TAG, PASSWORD_TAG)]

    secret_names = secret_map.keys()
    secret_names.sort()
    for secret_name in secret_names:
        secret_keys = secret_map[secret_name]
        user_name = dictionary_utils.get_element(secret_keys, SECRET_USERNAME_KEY)
        if user_name is None:
            secrets.append(_build_secret_hash(secret_name, None, PASSWORD_TAG))
        else:
            paired_secrets.append(_build_secret_hash(secret_name, user_name, PASSWORD_TAG))

    script_hash['secrets'] = secrets
    script_hash['pairedSecrets'] = paired_secrets
    script_hash['longMessage'] = exception_helper.get_message('WLSDPLY-01667', '${LONG_SECRETS_COUNT}')

    long_messages = [
        {'text': exception_helper.get_message('WLSDPLY-01668')},
        {'text': exception_helper.get_message('WLSDPLY-01669')},
        {'text': exception_helper.get_message('WLSDPLY-01670')}
    ]
    script_hash['longMessageDetails'] = long_messages

    file_location = model_context.get_output_dir()
    k8s_file = File(file_location, K8S_SCRIPT_NAME)
    file_template_helper.create_file_from_resource(K8S_SCRIPT_RESOURCE_PATH, script_hash, k8s_file, exception_type)
    FileUtils.chmod(k8s_file.getPath(), 0750)
예제 #23
0
	capturer = CaptureOverlayAction()
	capturer.execute(trackmate)

#---------------
# Export results
#---------------

dir = File(settings.imageFolder + '/Tracked')
dir.mkdir()

if not batchmode:
	cap = WindowManager.getImage("TrackMate capture")
	if not WindowManager.checkForDuplicateName:
		capTitle = 'Captured_' + settings.imageFileName
		capFile = File(dir, '/' + capTitle)
		print 'Saving capture to ' + capFile.getPath()
		IJ.save(cap, capFile.getPath())
		cap.setTitle(capTitle)
	else: 
		print 'Warning: Capture not saved because there are duplicate ImagePlus names'
		loglist.append ('Warning: Capture not saved because there are duplicate ImagePlus names')
		model.getLogger().log('Warning: Capture not saved because there are duplicate ImagePlus names')

if batchmode:
	batchtracks = File(dir, 'Tracked_Batch_' + settings.imageFileName + '.xml')
	ExportTracksToXML.export(model, settings, batchtracks)
else:
	tracks = File(dir, 'Tracked_TracksOnly.xml')
	ExportTracksToXML.export(model, settings, tracks)

file = File(dir, 'Tracked_Complete.xml')
예제 #24
0
class ConfigurableConfigPanel(ConfigPanel, ActionListener, DocumentListener, ChangeListener):
    """ generated source for class ConfigurableConfigPanel """
    serialVersionUID = 1L
    associatedFile = File()
    associatedFileField = JTextField()
    params = JSONObject()
    savedParams = str()
    loadButton = JButton()
    saveAsButton = JButton()
    saveButton = JButton()
    name = JTextField()
    strategy = JComboBox()
    metagameStrategy = JComboBox()
    stateMachine = JComboBox()
    cacheStateMachine = JCheckBox()
    maxPlys = JSpinner()
    heuristicFocus = JSpinner()
    heuristicMobility = JSpinner()
    heuristicOpponentFocus = JSpinner()
    heuristicOpponentMobility = JSpinner()
    mcDecayRate = JSpinner()
    rightPanel = JPanel()

    def __init__(self):
        """ generated source for method __init__ """
        super(ConfigurableConfigPanel, self).__init__(GridBagLayout())
        leftPanel = JPanel(GridBagLayout())
        leftPanel.setBorder(TitledBorder("Major Parameters"))
        self.rightPanel = JPanel(GridBagLayout())
        self.rightPanel.setBorder(TitledBorder("Minor Parameters"))
        self.strategy = JComboBox([None]*)
        self.metagameStrategy = JComboBox([None]*)
        self.stateMachine = JComboBox([None]*)
        self.cacheStateMachine = JCheckBox()
        self.maxPlys = JSpinner(SpinnerNumberModel(1, 1, 100, 1))
        self.heuristicFocus = JSpinner(SpinnerNumberModel(1, 0, 10, 1))
        self.heuristicMobility = JSpinner(SpinnerNumberModel(1, 0, 10, 1))
        self.heuristicOpponentFocus = JSpinner(SpinnerNumberModel(1, 0, 10, 1))
        self.heuristicOpponentMobility = JSpinner(SpinnerNumberModel(1, 0, 10, 1))
        self.mcDecayRate = JSpinner(SpinnerNumberModel(0, 0, 99, 1))
        self.name = JTextField()
        self.name.setColumns(20)
        self.name.setText("Player #" + Random().nextInt(100000))
        self.loadButton = JButton(loadButtonMethod())
        self.saveButton = JButton(saveButtonMethod())
        self.saveAsButton = JButton(saveAsButtonMethod())
        self.associatedFileField = JTextField()
        self.associatedFileField.setEnabled(False)
        buttons = JPanel()
        buttons.add(self.loadButton)
        buttons.add(self.saveButton)
        buttons.add(self.saveAsButton)
        nRow = 0
        leftPanel.add(JLabel("Name"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        __nRow_0 = nRow
        nRow += 1
        leftPanel.add(self.name, GridBagConstraints(1, __nRow_0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5))
        leftPanel.add(JLabel("Gaming Strategy"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        __nRow_1 = nRow
        nRow += 1
        leftPanel.add(self.strategy, GridBagConstraints(1, __nRow_1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5))
        leftPanel.add(JLabel("Metagame Strategy"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        __nRow_2 = nRow
        nRow += 1
        leftPanel.add(self.metagameStrategy, GridBagConstraints(1, __nRow_2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5))
        leftPanel.add(JLabel("State Machine"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        __nRow_3 = nRow
        nRow += 1
        leftPanel.add(self.stateMachine, GridBagConstraints(1, __nRow_3, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5))
        __nRow_4 = nRow
        nRow += 1
        leftPanel.add(buttons, GridBagConstraints(1, __nRow_4, 2, 1, 1.0, 1.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE, Insets(5, 5, 0, 5), 0, 0))
        leftPanel.add(self.associatedFileField, GridBagConstraints(0, nRow, 2, 1, 1.0, 0.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.HORIZONTAL, Insets(0, 5, 5, 5), 0, 0))
        layoutRightPanel()
        add(leftPanel, GridBagConstraints(0, 0, 1, 1, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(5, 5, 5, 5), 5, 5))
        add(self.rightPanel, GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(5, 5, 5, 5), 5, 5))
        self.params = JSONObject()
        syncJSONtoUI()
        self.strategy.addActionListener(self)
        self.metagameStrategy.addActionListener(self)
        self.stateMachine.addActionListener(self)
        self.cacheStateMachine.addActionListener(self)
        self.maxPlys.addChangeListener(self)
        self.heuristicFocus.addChangeListener(self)
        self.heuristicMobility.addChangeListener(self)
        self.heuristicOpponentFocus.addChangeListener(self)
        self.heuristicOpponentMobility.addChangeListener(self)
        self.mcDecayRate.addChangeListener(self)
        self.name.getDocument().addDocumentListener(self)

    def layoutRightPanel(self):
        """ generated source for method layoutRightPanel """
        nRow = 0
        self.rightPanel.removeAll()
        self.rightPanel.add(JLabel("State machine cache?"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        __nRow_5 = nRow
        nRow += 1
        self.rightPanel.add(self.cacheStateMachine, GridBagConstraints(1, __nRow_5, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        if self.strategy.getSelectedItem().__str__() == "Heuristic":
        __nRow_6 = nRow
        nRow += 1
        __nRow_7 = nRow
        nRow += 1
        __nRow_8 = nRow
        nRow += 1
        __nRow_9 = nRow
        nRow += 1
        __nRow_10 = nRow
        nRow += 1
            self.rightPanel.add(JLabel("Max plys?"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(self.maxPlys, GridBagConstraints(1, __nRow_6, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(JLabel("Focus Heuristic Weight"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(self.heuristicFocus, GridBagConstraints(1, __nRow_7, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(JLabel("Mobility Heuristic Weight"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(self.heuristicMobility, GridBagConstraints(1, __nRow_8, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(JLabel("Opponent Focus Heuristic Weight"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(self.heuristicOpponentFocus, GridBagConstraints(1, __nRow_9, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(JLabel("Opponent Mobility Heuristic Weight"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(self.heuristicOpponentMobility, GridBagConstraints(1, __nRow_10, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        if self.strategy.getSelectedItem().__str__() == "Monte Carlo":
        __nRow_11 = nRow
        nRow += 1
            self.rightPanel.add(JLabel("Goal Decay Rate"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(self.mcDecayRate, GridBagConstraints(1, __nRow_11, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        __nRow_12 = nRow
        nRow += 1
        self.rightPanel.add(JLabel(), GridBagConstraints(2, __nRow_12, 1, 1, 1.0, 1.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        self.rightPanel.repaint()

    @SuppressWarnings("unchecked")
    def getParameter(self, name, defaultValue):
        """ generated source for method getParameter """
        try:
            if self.params.has(name):
                return self.params.get(name)
            else:
                return defaultValue
        except JSONException as je:
            return defaultValue

    def actionPerformed(self, arg0):
        """ generated source for method actionPerformed """
        if arg0.getSource() == self.strategy:
            self.layoutRightPanel()
        syncJSONtoUI()

    def changedUpdate(self, e):
        """ generated source for method changedUpdate """
        syncJSONtoUI()

    def insertUpdate(self, e):
        """ generated source for method insertUpdate """
        syncJSONtoUI()

    def removeUpdate(self, e):
        """ generated source for method removeUpdate """
        syncJSONtoUI()

    def stateChanged(self, arg0):
        """ generated source for method stateChanged """
        syncJSONtoUI()

    def syncJSONtoUI(self):
        """ generated source for method syncJSONtoUI """
        if settingUI:
            return
        self.params = getJSONfromUI()
        self.saveButton.setEnabled(self.savedParams == None or not self.params.__str__() == self.savedParams)

    def getJSONfromUI(self):
        """ generated source for method getJSONfromUI """
        newParams = JSONObject()
        try:
            if not self.name.getText().isEmpty():
                newParams.put("name", self.name.getText())
            newParams.put("strategy", self.strategy.getSelectedItem().__str__())
            newParams.put("metagameStrategy", self.metagameStrategy.getSelectedItem().__str__())
            newParams.put("stateMachine", self.stateMachine.getSelectedItem().__str__())
            newParams.put("cacheStateMachine", self.cacheStateMachine.isSelected())
            newParams.put("maxPlys", self.maxPlys.getModel().getValue())
            newParams.put("heuristicFocus", self.heuristicFocus.getModel().getValue())
            newParams.put("heuristicMobility", self.heuristicMobility.getModel().getValue())
            newParams.put("heuristicOpponentFocus", self.heuristicOpponentFocus.getModel().getValue())
            newParams.put("heuristicOpponentMobility", self.heuristicOpponentMobility.getModel().getValue())
            newParams.put("mcDecayRate", self.mcDecayRate.getModel().getValue())
        except JSONException as je:
            je.printStackTrace()
        return newParams

    settingUI = False

    def setUIfromJSON(self):
        """ generated source for method setUIfromJSON """
        self.settingUI = True
        try:
            if self.params.has("name"):
                self.name.setText(self.params.getString("name"))
            if self.params.has("strategy"):
                self.strategy.setSelectedItem(self.params.getString("strategy"))
            if self.params.has("metagameStrategy"):
                self.metagameStrategy.setSelectedItem(self.params.getString("metagameStrategy"))
            if self.params.has("stateMachine"):
                self.stateMachine.setSelectedItem(self.params.getString("stateMachine"))
            if self.params.has("cacheStateMachine"):
                self.cacheStateMachine.setSelected(self.params.getBoolean("cacheStateMachine"))
            if self.params.has("maxPlys"):
                self.maxPlys.getModel().setValue(self.params.getInt("maxPlys"))
            if self.params.has("heuristicFocus"):
                self.heuristicFocus.getModel().setValue(self.params.getInt("heuristicFocus"))
            if self.params.has("heuristicMobility"):
                self.heuristicMobility.getModel().setValue(self.params.getInt("heuristicMobility"))
            if self.params.has("heuristicOpponentFocus"):
                self.heuristicOpponentFocus.getModel().setValue(self.params.getInt("heuristicOpponentFocus"))
            if self.params.has("heuristicOpponentMobility"):
                self.heuristicOpponentMobility.getModel().setValue(self.params.getInt("heuristicOpponentMobility"))
            if self.params.has("mcDecayRate"):
                self.mcDecayRate.getModel().setValue(self.params.getInt("mcDecayRate"))
        except JSONException as je:
            je.printStackTrace()
        finally:
            self.settingUI = False

    def loadParamsJSON(self, fromFile):
        """ generated source for method loadParamsJSON """
        if not fromFile.exists():
            return
        self.associatedFile = fromFile
        self.associatedFileField.setText(self.associatedFile.getPath())
        self.params = JSONObject()
        try:
            try:
                while (line = br.readLine()) != None:
                    pdata.append(line)
            finally:
                br.close()
            self.params = JSONObject(pdata.__str__())
            self.savedParams = self.params.__str__()
            self.setUIfromJSON()
            self.syncJSONtoUI()
        except Exception as e:
            e.printStackTrace()

    def saveParamsJSON(self, saveAs):
        """ generated source for method saveParamsJSON """
        try:
            if saveAs or self.associatedFile == None:
                fc.setFileFilter(PlayerFilter())
                if returnVal == JFileChooser.APPROVE_OPTION and fc.getSelectedFile() != None:
                    if toFile.__name__.contains("."):
                        self.associatedFile = File(toFile.getParentFile(), toFile.__name__.substring(0, toFile.__name__.lastIndexOf(".")) + ".player")
                    else:
                        self.associatedFile = File(toFile.getParentFile(), toFile.__name__ + ".player")
                    self.associatedFileField.setText(self.associatedFile.getPath())
                else:
                    return
            bw.write(self.params.__str__())
            bw.close()
            self.savedParams = self.params.__str__()
            self.syncJSONtoUI()
        except IOException as ie:
            ie.printStackTrace()

    def saveButtonMethod(self):
        """ generated source for method saveButtonMethod """
        return AbstractAction("Save")

    def saveAsButtonMethod(self):
        """ generated source for method saveAsButtonMethod """
        return AbstractAction("Save As")

    def loadButtonMethod(self):
        """ generated source for method loadButtonMethod """
        return AbstractAction("Load")

    class PlayerFilter(FileFilter):
        """ generated source for class PlayerFilter """
        def accept(self, f):
            """ generated source for method accept """
            if f.isDirectory():
                return True
            return f.__name__.endsWith(".player")

        def getDescription(self):
            """ generated source for method getDescription """
            return "GGP Players (*.player)"
    def _update_server(self, name, dictionary, config_location):
        _method_name = '_update_server'

        # these imports are local, since they are only present in JRF environments.
        # this method is only called after that check has been made.
        from oracle.core.ojdl.weblogic.ODLConfiguration import CONFIG_DIR
        from oracle.core.ojdl.weblogic.ODLConfiguration import CONFIG_FILE
        from oracle.core.ojdl.logging.config import LoggingConfigurationDocument

        config_dir = File(self.model_context.get_domain_home(), CONFIG_DIR)
        server_dir = File(config_dir, name)
        config_file = File(server_dir, CONFIG_FILE)
        log_template_dir = config_dir.getParentFile()

        try:
            if config_file.exists():
                source_file = config_file
                FileUtils.validateWritableFile(config_file.getPath())
            else:
                # for dynamic servers, the logging config does not exist until the server is started.
                # read the from template file, verify that the server directory is present and writable.
                source_file = File(log_template_dir, LOGGING_TEMPLATE_FILE)
                FileUtils.validateExistingFile(source_file)
                if not server_dir.exists() and not server_dir.mkdirs():
                    ex = exception_helper.create_deploy_exception(
                        'WLSDPLY-19710', server_dir)
                    self.logger.throwing(ex,
                                         class_name=self.__class_name,
                                         method_name=_method_name)
                    raise ex
                FileUtils.validateWritableDirectory(server_dir.getPath())

            document = LoggingConfigurationDocument(
                FileInputStream(source_file))

            # configure AddJvmNumber
            add_jvm_number = dictionary_utils.get_element(
                dictionary, _ADD_JVM_NUMBER)
            if add_jvm_number is not None:
                document.setAddJvmNumber(
                    alias_utils.convert_boolean(add_jvm_number))

            # configure HandlerDefaults
            handler_defaults = dictionary_utils.get_dictionary_element(
                dictionary, _HANDLER_DEFAULTS)
            if handler_defaults is not None:
                for key in handler_defaults:
                    value = handler_defaults[key]
                    document.setHandlerDefault(key, _get_property_text(value))

            # configure Handlers
            # do these before loggers, in case new handlers are assigned to loggers
            existing_handler_names = document.getHandlerNames()
            handlers = dictionary_utils.get_dictionary_element(
                dictionary, _HANDLER)
            if handlers is not None:
                for handler_name in handlers:
                    handler = handlers[handler_name]
                    self._configure_handler(handler_name, handler, document,
                                            existing_handler_names,
                                            config_location)

            # configure Loggers
            existing_logger_names = document.getLoggerNames()
            loggers = dictionary_utils.get_dictionary_element(
                dictionary, _LOGGER)
            if loggers is not None:
                for logger_name in loggers:
                    logger = loggers[logger_name]
                    self._configure_logger(logger_name, logger, document,
                                           existing_logger_names,
                                           config_location)

            document.writeDocument(FileOutputStream(config_file))

        except (ParserConfigurationException, SAXException, IOException,
                IllegalArgumentException), ex:
            self.logger.severe('WLSDPLY-19707',
                               name,
                               ex.getLocalizedMessage(),
                               class_name=self.__class_name,
                               method_name=_method_name)