def saveKif(cls, description): """ generated source for method saveKif """ # Save the description in a new file # Useful for debugging chains of condensations to see # which cause decreased performance filename = "ci0.kif" filenum = 0 file_ = None while file_ == None or file_.exists(): filenum += 1 filename = "ci" + filenum + ".kif" file_ = File(filename) file_ = File("games/rulesheets", filename) out = None try: out = BufferedWriter(FileWriter(file_)) for gdl in description: out.append(gdl.__str__() + "\n") except IOException as e: e.printStackTrace() finally: try: if out != None: out.close() except IOException as e: pass
def rawPython(a,b,c): """Execute the text as a new CPython process""" tmpFile = File.createTempFile("fieldRawPython", ".py", None) writer = BufferedWriter(FileWriter(tmpFile)) writer.write(b, 0, len(b)) writer.close() com = ExecuteCommand(".", ("/System/Library/Frameworks/Python.framework/Versions/Current/bin/python", tmpFile.getAbsolutePath()),1) com.waitFor(1) print com.getOutput()
def ig_dump_dot(dmuid, filename): igm = project.getIGM() uid = DMUID.parse(dmuid) module = igm.findModule(Toplevel(uid, None)) if module == None: printf('DM %s not found', dmuid) else: printf('Dumping %s...', module) dot = IG2DOT(module) dot.blacklistField("fImportedLibs") dot.blacklistField("fImportedPackages") dot.blacklistField("fZPrjID") dot.blacklistField("fSFDBID") dot.blacklistField("fLine") dot.blacklistField("fCol") dot.blacklistField("fScore") dot.blacklistField("fFailed") dot.blacklistField("fReject") dot.blacklistField("fInertial") dot.blacklistField("fDelay") out = PrintWriter(BufferedWriter(FileWriter(filename))) dot.convert(out) out.close() printf("python: wrote dot file to %s", filename)
def __init__(self, dump_path, dsl_pipe): self.dump_path = dump_path if not os.path.exists(dsl_pipe): raise Exception(""" The path to pipe for DSL reporter %s does not exists. Make sure SPADE is running and DSL reporter has been setup. For more infromation, take a look at http://code.google.com/p/data-provenance/wiki/Pipe""" ) self.pipe = BufferedWriter( OutputStreamWriter(FileOutputStream(dsl_pipe))) self.logger = logging.getLogger(self.__class__.__name__) self.user_data = self._read_json_data("me_data") self.user_newsfeed = self._read_json_data("me_newsfeed") self.friends = dict() self.created_user_nodes = set() for f in self._read_json_data("me_friends"): fuid = f['id'] try: self.friends[fuid] = self._read_json_data("%s_info" % fuid) except IOError, e: logger.info( "Skipping data for friend %s; unable to read data" % f['name']) self.friends[fuid] = f
def dm_dump_dot(dmuid, filename): dmm = project.getDUM() uid = DMUID.parse(dmuid) dm = dmm.getDM(uid) if dm == None: printf('DM %s not found', dmuid) else: printf('Dumping %s...', dm) dot = AST2DOT(dm, project.getZDB()) dot.blacklistField("fParent") # dot.blacklistField("fSource") # dot.blacklistField("fStartCol") # dot.blacklistField("fStartLine") dot.blacklistField("fEndCol") dot.blacklistField("fEndLine") dot.blacklistField("fDeclarationMap") out = PrintWriter(BufferedWriter(FileWriter(filename))) dot.convert(out) out.close() printf("python: wrote dot file to %s", filename)
def rtl_dump_svg(dmuid, filename): rtlmanager = project.getRTLM() uid = DMUID.parse(dmuid) rtlm = rtlmanager.findModule(Toplevel(uid, None)) if rtlm == None: printf('RTLM %s not found', dmuid) else: printf('Dumping %s...', rtlm) out = PrintWriter(BufferedWriter(FileWriter(filename))) gc = VGGCSVG(out) contentProvider = RTLVisualGraphContentProvider(rtlm) labelProvider = RTLVisualGraphLabelProvider(rtlm) selectionProvider = RTLVisualGraphSelectionProvider() layout = VGLayout(contentProvider, labelProvider, gc) layout.paint(selectionProvider) out.close() printf("python: wrote svg file to %s", filename)
def publish_parliament_info(config_file, parliament_cache_info): cfg = TransformerConfig(config_file) xml_parl_info = param_parl_info(cfg, parliament_cache_info.parl_info) path_to_file = os.path.join(cfg.get_temp_files_folder(),"legislature_info.xml") bwriter = BufferedWriter( OutputStreamWriter( FileOutputStream(path_to_file), "UTF8" ) ) bwriter.append(xml_parl_info) bwriter.flush() bwriter.close() wd_cfg = WebDavConfig(config_file) xml_folder = wd_cfg.get_http_server_port() + wd_cfg.get_bungeni_xml_folder() webdaver = None try: webdaver = WebDavClient( wd_cfg.get_username(), wd_cfg.get_password(), xml_folder ) #already called in language publish #webdaver.reset_remote_folder(xml_folder) up_stat = webdaver.pushFile(path_to_file) except Exception, e: print "Error while publishing parliament info", e
def publish_languages_info_xml(config_file): up_stat = None webdaver = None try : cfg = TransformerConfig(config_file) xml_lang_info = languages_info_xml(cfg) path_to_file = os.path.join( cfg.get_temp_files_folder(), "lang_info.xml" ) bwriter = BufferedWriter( OutputStreamWriter( FileOutputStream(path_to_file), "UTF8" ) ) bwriter.append(xml_lang_info) bwriter.flush() bwriter.close() wd_cfg = WebDavConfig(config_file) xml_folder = wd_cfg.get_http_server_port() + wd_cfg.get_bungeni_xml_folder() webdaver = WebDavClient( wd_cfg.get_username(), wd_cfg.get_password(), xml_folder ) webdaver.reset_remote_folder( xml_folder ) up_stat = webdaver.pushFile(path_to_file) except Exception,e: print "Error while getting languages info", e
def run(): print base = raw_input('Base file, eg. config/templates/wl_as_template.properties? ') env = raw_input('Environment, eg. local? ') print new_cfg = 'config/' + env + '/new_config.properties' input = BufferedReader(FileReader(base)) output = BufferedWriter(FileWriter(new_cfg)) output.write('base=' + base + '\n\n') line = input.readLine() while line is not None: if re.match('.*\?', line): output.write(line) output.newLine() line = input.readLine() input.close() output.close() log.info('new configuration file written to: ' + new_cfg)
def save(self,event=None): if self.fileChooser.showSaveDialog(self)==JFileChooser.APPROVE_OPTION: f=self.fileChooser.getSelectedFile() writer=BufferedWriter(FileWriter(f)) data,title=self.extract_data() title=[t.replace(',',' ') for t in title] writer.write(','.join(title)+'\n') for row in data: writer.write(','.join(row)+'\n') writer.close()
def http_post(self, json_string, url): '''Return java.lang.String JSON Input: java.lang.String JSON, java.lang.String URL ''' start_timer = System.currentTimeMillis() try: # Get a connection and set the request properties url = URL(url) urlconnect = url.openConnection() urlconnect.setDoOutput(True) urlconnect.setRequestMethod("POST") urlconnect.setRequestProperty("Content-Type", "application/json; UTF-8") urlconnect.setRequestProperty("Accept", "application/json") # Write to the body bw = BufferedWriter( OutputStreamWriter( urlconnect.getOutputStream() ) ) bw.write(json_string) bw.flush() bw.close() # Read the result from the POST br = BufferedReader( InputStreamReader( urlconnect.getInputStream(), "UTF-8" ) ) s = br.readLine() br.close() except MalformedURLException() as ex: cumulus_logger.error(str(ex)) MessageBox.showError(str(ex), "Exception") raise Exception(ex) except IOException as ex: cumulus_logger.error(str(ex)) MessageBox.showError(str(ex), "Exception") raise Exception(ex) end_timer = System.currentTimeMillis() cumulus_logger.debug( "HTTP GET (milliseconds): {}".format( (end_timer - start_timer) ) ) return s
def rawPython(a, b, c): """Execute the text as a new CPython process""" tmpFile = File.createTempFile("fieldRawPython", ".py", None) writer = BufferedWriter(FileWriter(tmpFile)) writer.write(b, 0, len(b)) writer.close() com = ExecuteCommand(".", ( "/System/Library/Frameworks/Python.framework/Versions/Current/bin/python", tmpFile.getAbsolutePath()), 1) com.waitFor(1) print com.getOutput()
def exportChangeHistory(): jfc = JFileChooser() todo = jfc.showSaveDialog(GraphModifier.self.buttonPanel) if todo == JFileChooser.APPROVE_OPTION: file = jfc.getSelectedFile() filePath = file.getAbsolutePath() # write to the file try: bw = BufferedWriter(FileWriter(filePath)) for i in changeHistory: bw.write("#" + i[0] + "\n") bw.write(i[1]) bw.close() JOptionPane.showMessageDialog(GraphModifier.self.buttonPanel, "File: " + filePath + " saved!") except Exception: JOptionPane.showMwssageDialog(GraphModifier.self.buttonPanel, "Failed to save file:" + filePath) GraphModifier.self.bottomPanel.setVisible(false)
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()
from java.io import BufferedReader as BR from java.io import FileReader as FR from java.io import BufferedWriter as BW from java.io import FileWriter as FW from java.io import File as F file_r = F("file3.txt") file_w = F("file4.txt") br = BR(FR(file_r)) bw = BW(FW(file_w)) while True: line = br.readLine() if line != None: bw.write(line + "\n") else: break br.close() bw.close()
domainPassword=configProperties.getProperty('wls.admin.password') rootDir=configProperties.getProperty('wls.server.' + str(server) + '.root.dir') securityDir = File(domainPath + File.separator + domainName + File.separator + 'servers' + File.separator + str(serverName) + File.separator + 'security') if not securityDir.exists() and rootDir is None: log.info('Creating directory ' + str(securityDir)) securityDir.mkdirs() bootFile = File(securityDir.getAbsolutePath() + File.separator + 'boot.properties') # TODO: Use flag no.managed.server.boot.properties=true/false instead of checking domain called osb_domain (H@CK) if not bootFile.exists() and rootDir is None and not domainName == 'osb_domain': log.info('Creating boot.properties for server [' + str(serverName) + '].') bootFile.createNewFile() fileWriter = FileWriter(bootFile) bufWriter = BufferedWriter(fileWriter) bufWriter.write('username='******'password='******'Ignoring boot.properties creation for [' + str(serverName) + '].') #======================================================================================= # Configure additional managed server properties #======================================================================================= __configureAdditionalManagedServerProperties(serverName, enableHostnameVerification) __configureCoherenceManagedServerProperties(serverName,coherenceUnicastAddress,wlsVersion) servergroups=configProperties.getProperty('wls.server.'+str(server)+'.servergroups') if servergroups is not None: servergroupslist=servergroups.split(',')
conn = url.openConnection() in_st_url = BR(ISR(conn.getInputStream())) with open("Temp_2.py", "w") as f: while True: try: f.write(in_st_url.readLine() + "\n") except: break builder = pb(["python", "Temp_2.py"]) builder.directory(F("C:\\Users\\Sony\\Desktop\\jython-prac-prog\\network")) process = builder.start() p_i = BR(ISR(process.getInputStream())) p_o = BW(OSR(process.getOutputStream())) with open("input.txt", "r") as f: global li li = f.readlines() for k in li: p_o.write(k) p_o.flush() p_o.close() s = S(p_i) while s.hasNextLine(): print(s.nextLine())
#======================================================================================= # Write the domain #======================================================================================= try: log.info('Writing domain') writeDomain(str(domainPath) + '/' + str(domainName)) securityDir = File(domainPath + File.separator + domainName + File.separator + 'servers' + File.separator + str(adminServerName) + File.separator + 'security') if not securityDir.exists(): securityDir.mkdirs() bootFile = File(securityDir.getAbsolutePath() + File.separator + 'boot.properties') bootFile.createNewFile() fileWriter = FileWriter(bootFile) bufWriter = BufferedWriter(fileWriter) bufWriter.write('username='******'password='******'Unable to write domain [' + str(domainPath) + '/' + str(domainName) + '] : ' + str(error) #======================================================================================= # Close the domain template. #======================================================================================= closeTemplate() #============================================================================== # __addTemplate
def exportGDFFile(): defaultNodeProperties = ["name","x","y","visible","color","fixed","style","width","height","label","labelVisible","image"] defaultEdgeProperties = ["node1","node2","visible","color","weight","width","directed","label","labelVisible"] nodeHeader = "nodedef>" edgeHeader = "edgedef>" # create the node header line for i in defaultNodeProperties: nodeHeader = nodeHeader + i + "," # get the nodes other properties for i in nodeProperties.keys(): if nodeProperties[i] == type("string"): nodeHeader = nodeHeader + i + " VARCHAR(100)," elif nodeProperties[i] == type(1): nodeHeader = nodeHeader + i + " INT," elif nodeProperties[i] == type(1.5): nodeHeader = nodeHeader + i + " FLOAT," nodeHeader = nodeHeader[0:-1] # create the edge header line for i in defaultEdgeProperties: edgeHeader = edgeHeader + i + "," # get the other edge properties for i in edgeProperties.keys(): if not i == "node1" and not i == "node2": if edgeProperties[i] == type("string"): edgeHeader = edgeHeader + i + " VARCHAR(100)," elif edgeProperties[i] == type(1): edgeHeader = edgeHeader + i + " INT," elif edgeProperties[i] == type(1.5): edgeHeader = edgeHeader + i + " FLOAT," edgeHeader = edgeHeader[0:-1] jfc = JFileChooser() todo = jfc.showSaveDialog(GraphModifier.self.buttonPanel) if todo == JFileChooser.APPROVE_OPTION: file = jfc.getSelectedFile() filePath = file.getAbsolutePath() # write to the file try: bw = BufferedWriter(FileWriter(filePath)) bw.write(nodeHeader + "\n") nodeStuff = defaultNodeProperties + nodeProperties.keys() # write the node stuff into the file for i in g.nodes: nodeString = "" for j in nodeStuff: nodeString = nodeString + str(eval("i." + str(j))) + "," nodeString = nodeString[0:-1] nodeString = nodeString + "\n" bw.write(nodeString) # write the edge stuff into the file # filter out edge porperty keys filteredKeys = [] for i in edgeProperties.keys(): if not i == "node1" and not i == "node2": filteredKeys.append(i) edgeStuff = defaultEdgeProperties + filteredKeys bw.write(edgeHeader + "\n") for i in g.edges: edgeString = "" for j in edgeStuff: # get node name if j == "node1" or j == "node2": edgeString = edgeString + str(eval("i." + str(j) + ".name")) + "," else: edgeString = edgeString + str(eval("i." + str(j))) + "," edgeString = edgeString[0:-1] edgeString = edgeString + "\n" bw.write(edgeString) bw.close() JOptionPane.showMessageDialog(GraphModifier.self.buttonPanel, "GDF created sucessfully") except Exception: JOptionPane.showMessageDialog(GraphModifier.self.buttonPanel, "Error in exporting GDF") GraphModifier.self.bottomPanel.setVisible(false)