private void writeSmearInfo(string text) { DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream(text)); dataOutputStream.writeInt(-1060454374); [email protected](new StringBuilder().append("writing ").append(this.unigrams.Length).toString()); dataOutputStream.writeInt(this.unigrams.Length); for (int i = 0; i < this.unigrams.Length; i++) { dataOutputStream.writeFloat(this.unigramSmearTerm[i]); } for (int i = 0; i < this.unigrams.Length; i++) { [email protected](new StringBuilder().append("Writing ").append(i).append(" of ").append(this.unigrams.Length).toString()); NGramBuffer bigramBuffer = this.getBigramBuffer(i); if (bigramBuffer == null) { dataOutputStream.writeInt(0); } else { dataOutputStream.writeInt(bigramBuffer.getNumberNGrams()); for (int j = 0; j < bigramBuffer.getNumberNGrams(); j++) { int wordID = bigramBuffer.getWordID(j); Float smearTerm = this.getSmearTerm(i, wordID); dataOutputStream.writeInt(wordID); dataOutputStream.writeFloat(smearTerm.floatValue()); } } } dataOutputStream.close(); }
public static bool DeleteAllDuplicateStructures(string filename, out int totalreccnt, out int dupreccnt) { bool blStatus = false; int intDupRecCnt = 0; int intTotalRecCnt = 0; try { MolInputStream molInStream = new MolInputStream(new FileInputStream(filename)); MolImporter molImp = new MolImporter(molInStream); Molecule objMol = new Molecule(); DataOutputStream dOutStream = new DataOutputStream(new FileOutputStream(filename)); MolExporter molExpt = new MolExporter(dOutStream, "sdf"); bool blIsChiral = false; string strInchiKey = ""; ArrayList molInchiList = new ArrayList(); while (molImp.read(objMol)) { objMol = StandardizeMolecule(objMol, out blIsChiral); strInchiKey = objMol.toFormat("inchi:key"); strInchiKey = GetInchiKeyFromInchiString(strInchiKey); if (!molInchiList.Contains(strInchiKey)) { molInchiList.Add(strInchiKey); molExpt.write(objMol); } else { intDupRecCnt++; } intTotalRecCnt++; } //Close all the import & export objects molImp.close(); molInStream.close(); dOutStream.close(); molExpt.close(); blStatus = true; } catch (Exception ex) { ErrorHandling.WriteErrorLog(ex.ToString()); } totalreccnt = intTotalRecCnt; dupreccnt = intDupRecCnt; return(blStatus); }
private void writeCurrentHouseToFile() { JSystem.println("Saving house " + this.m_currentHouse.getName() + ".xml"); StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(this.m_currentHouse.getName()).append(".xml"); DataOutputStream @out = new DataOutputStream(OutputStream.getResourceAsStream(stringBuffer.toString())); this.m_currentHouse.writexml(@out); @out.close(); }
private void saveMixtureWeightsBinary(GaussianWeights gaussianWeights, string text, bool append) { this.logger.info("Saving mixture weights to: "); this.logger.info(text); Properties properties = new Properties(); properties.setProperty("version", "1.0"); if (this.doCheckSum) { properties.setProperty("chksum0", this.checksum); } DataOutputStream dataOutputStream = this.writeS3BinaryHeader(this.location, text, properties, append); int statesNum = gaussianWeights.getStatesNum(); int streamsNum = gaussianWeights.getStreamsNum(); int gauPerState = gaussianWeights.getGauPerState(); this.writeInt(dataOutputStream, statesNum); this.writeInt(dataOutputStream, streamsNum); this.writeInt(dataOutputStream, gauPerState); if (!Sphinx3Saver.assertionsDisabled && streamsNum != 1) { throw new AssertionError(); } int val = gauPerState * statesNum * streamsNum; this.writeInt(dataOutputStream, val); for (int i = 0; i < statesNum; i++) { for (int j = 0; j < streamsNum; j++) { float[] array = new float[gauPerState]; float[] array2 = new float[gauPerState]; for (int k = 0; k < gauPerState; k++) { array2[k] = gaussianWeights.get(i, j, k); } this.logMath.logToLinear(array2, array); this.writeFloatArray(dataOutputStream, array); } } if (this.doCheckSum && !Sphinx3Saver.assertionsDisabled) { int num = 0; bool flag = num != 0; this.doCheckSum = (num != 0); if (!flag) { object obj = "Checksum not supported"; throw new AssertionError(obj); } } dataOutputStream.close(); }
/// <summary> /// Encodes this <seealso cref="ChecksumTable" /> and encrypts the final whirlpool hash. /// </summary> /// <param name="whirlpool"> If whirlpool digests should be encoded. </param> /// <param name="modulus"> The modulus. </param> /// <param name="privateKey"> The private key. </param> /// <returns> The encoded <seealso cref="ByteBuffer" />. </returns> /// <exception cref="IOException"> if an I/O error occurs. </exception> public virtual ByteBuffer Encode(bool whirlpool, BigInteger modulus, BigInteger privateKey) { var bout = new ByteArrayOutputStream(); var os = new DataOutputStream(bout); try { /* as the new whirlpool format is more complicated we must write the number of entries */ if (whirlpool) { os.write(entries.Length); } /* encode the individual entries */ for (var i = 0; i < entries.Length; i++) { var entry = entries[i]; os.writeInt(entry.GetCrc()); os.writeInt(entry.GetVersion()); if (whirlpool) { os.write(entry.GetWhirlpool()); } } /* compute (and encrypt) the digest of the whole table */ byte[] bytes; if (whirlpool) { bytes = bout.toByteArray(); var temp = ByteBuffer.allocate(66); temp.put(0); temp.put(Whirlpool.Crypt(bytes, 5, bytes.Length - 5)); temp.put(0); temp.flip(); if (modulus != null && privateKey != null) { temp = Rsa.Crypt(temp, modulus, privateKey); } bytes = new byte[temp.limit()]; temp.get(bytes); os.write(bytes); } bytes = bout.toByteArray(); return(ByteBuffer.wrap(bytes)); } finally { os.close(); } }
/// <summary> /// Might be used for debugging <seealso cref="ProcessDiagramRetrievalTest.testGetProcessDiagram()"/>. /// </summary> //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @SuppressWarnings("unused") private static void writeToFile(java.io.InputStream is, java.io.File file) throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: private static void writeToFile(Stream @is, File file) { DataOutputStream @out = new DataOutputStream(new BufferedOutputStream(new FileStream(file, FileMode.Create, FileAccess.Write))); int c; while ((c = @is.Read()) != -1) { @out.writeByte(c); } @is.Close(); @out.close(); }
public static void writeGzippedCompoundToOutputStream(NBTTagCompound nbttagcompound, OutputStream outputstream) { var dataoutputstream = new DataOutputStream(new GZIPOutputStream(outputstream)); try { func_771_a(nbttagcompound, dataoutputstream); } finally { dataoutputstream.close(); } }
/// <summary> /// Encodes this <seealso cref="Archive" /> into a <seealso cref="ByteBuffer" />. /// <p /> /// Please note that this is a fairly simple implementation that does not /// attempt to use more than one chunk. /// </summary> /// <returns> An encoded <seealso cref="ByteBuffer" />. </returns> /// <exception cref="IOException"> if an I/O error occurs. </exception> public virtual ByteBuffer Encode() // TODO: an implementation that can use more than one chunk { var bout = new ByteArrayOutputStream(); var os = new DataOutputStream(bout); try { /* add the data for each entry */ for (var id = 0; id < entries.Length; id++) { /* copy to temp buffer */ var temp = new byte[entries[id].limit()]; entries[id].position(0); try { entries[id].get(temp); } finally { entries[id].position(0); } /* copy to output stream */ os.write(temp); } /* write the chunk lengths */ var prev = 0; for (var id = 0; id < entries.Length; id++) { /* * since each file is stored in the only chunk, just write the * delta-encoded file size */ var chunkSize = entries[id].limit(); os.writeInt(chunkSize - prev); prev = chunkSize; } /* we only used one chunk due to a limitation of the implementation */ bout.write(1); /* wrap the bytes from the stream in a buffer */ var bytes = bout.toByteArray(); return(ByteBuffer.wrap(bytes)); } finally { os.close(); } }
public static bool DeleteRecordFromSDFile(string _infilename, int _recindex) { bool blStatus = false; try { int intRecIndex = 0; MolInputStream molInStream = new MolInputStream(new FileInputStream(_infilename)); MolImporter molImp = new MolImporter(molInStream); string strInputFilePath = System.IO.Path.GetDirectoryName(_infilename); string strExecPath = Application.StartupPath; string strFileName = System.IO.Path.GetFileName(_infilename); string strOutFile = strExecPath + "\\" + strFileName; DataOutputStream dOutStream = new DataOutputStream(new FileOutputStream(strOutFile)); MolExporter mExpt = new MolExporter(dOutStream, "sdf"); Molecule objMol = new Molecule(); while (molImp.read(objMol)) { intRecIndex++; if (intRecIndex != _recindex) { mExpt.write(objMol); } } molImp.close(); molInStream.close(); mExpt.close(); dOutStream.close(); System.IO.File.Copy(strOutFile, _infilename, true); System.IO.File.Delete(strOutFile); blStatus = true; } catch (Exception ex) { ErrorHandling_NTS.WriteErrorLog(ex.ToString()); } return(blStatus); }
// Token: 0x06000088 RID: 136 RVA: 0x000088C8 File Offset: 0x00006AC8 public static void saveRMSString(string filename, string data) { DataOutputStream dataOutputStream = new DataOutputStream(); try { dataOutputStream.writeUTF(data); Rms.saveRMS(filename, dataOutputStream.toByteArray()); dataOutputStream.close(); } catch (Exception ex) { Cout.println(ex.StackTrace); } }
// Token: 0x060006E4 RID: 1764 RVA: 0x0005C498 File Offset: 0x0005A698 public static void saveRMS() { DataOutputStream dataOutputStream = new DataOutputStream(); try { dataOutputStream.writeShort((short)ImageSource.vSource.size()); for (int i = 0; i < ImageSource.vSource.size(); i++) { dataOutputStream.writeUTF(((ImageSource)ImageSource.vSource.elementAt(i)).id); dataOutputStream.writeByte(((ImageSource)ImageSource.vSource.elementAt(i)).version); } Rms.saveRMS("ImageSource", dataOutputStream.toByteArray()); dataOutputStream.close(); } catch (Exception ex) { ex.StackTrace.ToString(); } }
public virtual void dumpBinary(string outputFile) { DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream(outputFile)); dataOutputStream.writeInt(this.getNumberDataPoints()); Iterator iterator = this.allFeatures.iterator(); while (iterator.hasNext()) { float[] array = (float[])iterator.next(); float[] array2 = array; int num = array2.Length; for (int i = 0; i < num; i++) { float num2 = array2[i]; dataOutputStream.writeFloat(num2); } } dataOutputStream.close(); }
private void func_22098_f() { try { var file = new File(field_22099_b, "session.lock"); var dataoutputstream = new DataOutputStream(new FileOutputStream(file)); try { dataoutputstream.writeLong(field_22100_d); } finally { dataoutputstream.close(); } } catch (IOException ioexception) { ioexception.printStackTrace(); throw new RuntimeException("Failed to check session lock, aborting"); } }
public void saveChunk(World world, Chunk chunk) { world.checkSessionLock(); try { DataOutputStream dataoutputstream = RegionFileCache.func_22120_d(field_22110_a, chunk.xPosition, chunk.zPosition); var nbttagcompound = new NBTTagCompound(); var nbttagcompound1 = new NBTTagCompound(); nbttagcompound.setTag("Level", nbttagcompound1); ChunkLoader.storeChunkInCompound(chunk, world, nbttagcompound1); CompressedStreamTools.func_771_a(nbttagcompound, dataoutputstream); dataoutputstream.close(); WorldInfo worldinfo = world.getWorldInfo(); worldinfo.func_22177_b(worldinfo.func_22182_g() + RegionFileCache.func_22121_b(field_22110_a, chunk.xPosition, chunk.zPosition)); } catch (Exception exception) { exception.printStackTrace(); } }
private void func_22107_a(File file, ArrayList arraylist, int i, int j, IProgressUpdate iprogressupdate) { Collections.sort(arraylist); var abyte0 = new byte[4096]; int i1; for (Iterator iterator = arraylist.iterator(); iterator.hasNext(); iprogressupdate.setLoadingProgress(i1)) { var filematcher = (FileMatcher)iterator.next(); int k = filematcher.func_22205_b(); int l = filematcher.func_22204_c(); RegionFile regionfile = RegionFileCache.func_22123_a(file, k, l); if (!regionfile.isChunkSaved(k & 0x1f, l & 0x1f)) { try { var datainputstream = new DataInputStream(new GZIPInputStream(new FileInputStream(filematcher.func_22207_a()))); DataOutputStream dataoutputstream = regionfile.getChunkDataOutputStream(k & 0x1f, l & 0x1f); for (int j1 = 0; (j1 = datainputstream.read(abyte0)) != -1;) { dataoutputstream.write(abyte0, 0, j1); } dataoutputstream.close(); datainputstream.close(); } catch (IOException ioexception) { ioexception.printStackTrace(); } } i++; i1 = (int)Math.round((100D * i) / j); } RegionFileCache.func_22122_a(); }
private void saveDLCData() { if (this.m_bakedDLC) { return; } StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(this.m_rootFolder); stringBuffer.append(DLCManager.pathSeparatorChar); stringBuffer.append(DLCManager.DLCDATA_FILENAME); FileOutputStream fileOutputStream = new FileOutputStream(stringBuffer.toString()); fileOutputStream.clear(); DataOutputStream dataOutputStream = new DataOutputStream((OutputStream)fileOutputStream); dataOutputStream.writeInt(this.m_packCount); for (int index = 0; index < this.m_packCount; ++index) { dataOutputStream.writeInt(this.m_packSellIds[index]); } dataOutputStream.close(); }
public void networkShutdown(string s, object[] aobj) { if (!m_isRunning) { return; } isTerminating = true; terminationReason = s; field_20176_t = aobj; (new NetworkMasterThread(this)).start(); m_isRunning = false; try { socketInputStream.close(); socketInputStream = null; } catch (Throwable) { } try { socketOutputStream.close(); socketOutputStream = null; } catch (Throwable) { } try { networkSocket.close(); networkSocket = null; } catch (Throwable) { } }
private void Form1_Load(object sender, EventArgs e) { byte[] buffer = new byte[1024]; Socket s = new Socket("localhost", 42069); int successRead = s.Receive(buffer); var reader = new BinaryReader(buffer); DataOutputStream dout = new DataOutputStream(s.getOutputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = "", str2 = ""; while (!str.equals("stop")) { str = br.readLine(); dout.writeUTF(str); dout.flush(); str2 = din.readUTF(); System.out.println("Server says: " + str2); } dout.close(); s.close(); }
// Token: 0x06000890 RID: 2192 RVA: 0x0007D118 File Offset: 0x0007B318 public static void saveIP() { DataOutputStream dataOutputStream = new DataOutputStream(); try { dataOutputStream.writeByte(mResources.language); dataOutputStream.writeByte((sbyte)ServerListScreen.nameServer.Length); for (int i = 0; i < ServerListScreen.nameServer.Length; i++) { dataOutputStream.writeUTF(ServerListScreen.nameServer[i]); dataOutputStream.writeUTF(ServerListScreen.address[i]); dataOutputStream.writeShort(ServerListScreen.port[i]); dataOutputStream.writeByte(ServerListScreen.language[i]); } dataOutputStream.writeByte(ServerListScreen.serverPriority); Rms.saveRMS("NRlink2", dataOutputStream.toByteArray()); dataOutputStream.close(); SplashScr.loadIP(); } catch (Exception) { } }
public File Save() { // Creates worlds directory File worldDir = new File("worlds"); if (!DirExists(worldDir)) { worldDir.mkdir(); } // Get level directory string levelName = _level.Name; File levelDir = new File(worldDir, levelName); if (DirExists(levelDir)) { int dirPostFix = 0; do { dirPostFix++; levelDir = new File(worldDir, levelName + dirPostFix); } while (DirExists(levelDir)); } // Create directories levelDir.mkdir(); File regionDir = new File(levelDir, "region"); regionDir.mkdir(); // Write session.lock File sessionLockFile = new File(levelDir, "session.lock"); DataOutputStream dos = new DataOutputStream(new FileOutputStream(sessionLockFile)); try { dos.writeLong(CurrentTimeMillis()); } finally { dos.close(); } // Write level.dat File levelFile = new File(levelDir, "level.dat"); FileOutputStream fos = new FileOutputStream(levelFile); NBTOutputStream nbtOut = new NBTOutputStream(fos, true); try { nbtOut.writeTag(_level.Tag); } finally { nbtOut.close(); } // Calculate height maps foreach (Region region in _regions.Values) { region.CalculateHeightMap(); } // Set sky light AddSkyLight(); // Spread sky light for (int i = DefaultSkyLight; i > 1; i--) { SpreadSkyLight((byte)i); } // Iterate regions for (int index = 0; index <= _regions.Count - 1; index++) { Point point = _regions.Keys.ToList()[index]; Region region = _regions.Values.ToList()[index]; // Save region File regionFile = new File(regionDir, "r." + point.X + "." + point.Y + ".mca"); region.WriteToFile(regionFile); } return(levelDir); }
private void saveDensityFileBinary(Pool pool, string text, bool append) { Properties properties = new Properties(); int val = 0; this.logger.info("Saving density file to: "); this.logger.info(text); properties.setProperty("version", "1.0"); properties.setProperty("chksum0", this.checksum); DataOutputStream dataOutputStream = this.writeS3BinaryHeader(this.location, text, properties, append); int feature = pool.getFeature(Pool.Feature.__NUM_SENONES, -1); int feature2 = pool.getFeature(Pool.Feature.__NUM_STREAMS, -1); int feature3 = pool.getFeature(Pool.Feature.__NUM_GAUSSIANS_PER_STATE, -1); this.writeInt(dataOutputStream, feature); this.writeInt(dataOutputStream, feature2); this.writeInt(dataOutputStream, feature3); int num = 0; int[] array = new int[feature2]; for (int i = 0; i < feature2; i++) { array[i] = this.vectorLength; this.writeInt(dataOutputStream, array[i]); num += feature3 * feature * array[i]; } if (!Sphinx3Saver.assertionsDisabled && feature2 != 1) { throw new AssertionError(); } if (!Sphinx3Saver.assertionsDisabled && num != feature3 * feature * this.vectorLength) { throw new AssertionError(); } this.writeInt(dataOutputStream, num); for (int i = 0; i < feature; i++) { for (int j = 0; j < feature2; j++) { for (int k = 0; k < feature3; k++) { int id = i * feature2 * feature3 + j * feature3 + k; float[] data = (float[])pool.get(id); this.writeFloatArray(dataOutputStream, data); } } } if (this.doCheckSum && !Sphinx3Saver.assertionsDisabled) { int num2 = 0; bool flag = num2 != 0; this.doCheckSum = (num2 != 0); if (!flag) { object obj = "Checksum not supported"; throw new AssertionError(obj); } } this.writeInt(dataOutputStream, val); dataOutputStream.close(); }
public string UploadString(Uri u, string method, string data) { // http://hg.openjdk.java.net/jdk7/jdk7/jdk/file/tip/src/share/classes/sun/net/www/protocol/http/HttpURLConnection.java // fails on openJDK why? Console.WriteLine("enter UploadString " + new { u, method }); var w = new StringBuilder(); HttpURLConnection xHttpURLConnection = null; try { #region NSA is that you? intercept? we can only trust pinned off device certs var trustAllCerts = new[] { new localX509TrustManager { } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(new localHostnameVerifier { }); #endregion //UploadString getOutputStream //enter checkServerTrusted //enter getAcceptedIssuers //UploadString writeBytes var url = new java.net.URL(u.ToString()); xHttpURLConnection = (HttpURLConnection)url.openConnection(); var https = xHttpURLConnection as HttpsURLConnection; if (https != null) { //Console.WriteLine(new { https }); } //conn.setHostnameVerifier(new localHostnameVerifier { }); xHttpURLConnection.setDoOutput(true); xHttpURLConnection.setDoInput(true); xHttpURLConnection.setInstanceFollowRedirects(false); //conn.setInstanceFollowRedirects(true); xHttpURLConnection.setRequestMethod(method); var xContentType = default(string); try { if (Headers != null) { foreach (string key in Headers.AllKeys) { if (key == "Content-Type") { xContentType = Headers[key]; } xHttpURLConnection.addRequestProperty(key, Headers[key]); } } } catch (Exception e) { //System.Console.WriteLine("ERROR: Failed to write headers. Exception was:" + e.Message); } if (xContentType == null) { xHttpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); xHttpURLConnection.setRequestProperty("charset", "utf-8"); } //conn.setRequestProperty("content-length", "" + data.Length); xHttpURLConnection.setRequestProperty("Content-Length", "" + data.Length); xHttpURLConnection.setUseCaches(false); //Console.WriteLine("UploadString getOutputStream"); var o = xHttpURLConnection.getOutputStream(); //Console.WriteLine("UploadString writeBytes"); // DataOutputStream wr = new DataOutputStream(o); wr.writeBytes(data); //Console.WriteLine("UploadString flush"); wr.flush(); //Console.WriteLine("UploadString close"); wr.close(); //Console.WriteLine("UploadString readLine"); //var i = new java.io.InputStreamReader(url.openStream(), "UTF-8"); var i = new java.io.InputStreamReader(xHttpURLConnection.getInputStream(), "UTF-8"); var reader = new java.io.BufferedReader(i); // can't we just read to the end? var line = reader.readLine(); while (line != null) { w.AppendLine(line); line = reader.readLine(); } reader.close(); } catch (Exception err) { // 500 ? // = java.net.ProtocolException: Invalid HTTP method: // oops Console.WriteLine("UploadString " + new { err }); } //Console.WriteLine("exit UploadString " + new { conn }); if (xHttpURLConnection != null) { xHttpURLConnection.disconnect(); } return(w.ToString()); }
protected internal virtual void saveTransitionMatricesBinary(Pool pool, string path, bool append) { this.logger.info("Saving transition matrices to: "); this.logger.info(path); Properties properties = new Properties(); properties.setProperty("version", "1.0"); if (this.doCheckSum) { properties.setProperty("chksum0", this.checksum); } DataOutputStream dataOutputStream = this.writeS3BinaryHeader(this.location, path, properties, append); int num = pool.size(); if (!Sphinx3Saver.assertionsDisabled && num <= 0) { throw new AssertionError(); } this.writeInt(dataOutputStream, num); float[][] array = (float[][])pool.get(0); int num2 = array[0].Length; int num3 = num2 - 1; this.writeInt(dataOutputStream, num3); this.writeInt(dataOutputStream, num2); int val = num2 * num3 * num; this.writeInt(dataOutputStream, val); for (int i = 0; i < num; i++) { array = (float[][])pool.get(i); float[] array2 = array[num2 - 1]; float[] array3 = new float[array2.Length]; for (int j = 0; j < num2; j++) { if (!Sphinx3Saver.assertionsDisabled && array3[j] != 0f) { throw new AssertionError(); } } for (int j = 0; j < num3; j++) { array2 = array[j]; array3 = new float[array2.Length]; this.logMath.logToLinear(array2, array3); this.writeFloatArray(dataOutputStream, array3); } } if (this.doCheckSum && !Sphinx3Saver.assertionsDisabled) { int num4 = 0; bool flag = num4 != 0; this.doCheckSum = (num4 != 0); if (!flag) { object obj = "Checksum not supported"; throw new AssertionError(obj); } } dataOutputStream.close(); }
public override void close() { output.flush(); output.close(); }
/// <summary> /// Encodes this <seealso cref="ReferenceTable" /> into a <seealso cref="ByteBuffer" />. /// </summary> /// <returns> The <seealso cref="ByteBuffer" />. </returns> /// <exception cref="IOException"> if an I/O error occurs. </exception> public virtual ByteBuffer Encode() { /* * we can't (easily) predict the size ahead of time, so we write to a * stream and then to the buffer */ var bout = new ByteArrayOutputStream(); var os = new DataOutputStream(bout); try { /* write the header */ os.write(format); if (format >= 6) { os.writeInt(version); } os.write(flags); /* calculate and write the number of non-null entries */ os.writeShort(entries.Count); /* write the ids */ var last = 0; for (var id = 0; id < Capacity(); id++) { if (entries.ContainsKey(id)) { var delta = id - last; os.writeShort(delta); last = id; } } /* write the identifiers if required */ if ((flags & FLAG_IDENTIFIERS) != 0) { foreach (var entry in entries.Values) { os.writeInt(entry.identifier); } } /* write the CRC checksums */ foreach (var entry in entries.Values) { os.writeInt(entry.crc); } /* write the whirlpool digests if required */ if ((flags & FLAG_WHIRLPOOL) != 0) { foreach (var entry in entries.Values) { os.write(entry.whirlpool); } } /* write the versions */ foreach (var entry in entries.Values) { os.writeInt(entry.version); } /* calculate and write the number of non-null child entries */ foreach (var entry in entries.Values) { os.writeShort(entry.entries.Count); } /* write the child ids */ foreach (var entry in entries.Values) { last = 0; for (var id = 0; id < entry.Capacity(); id++) { if (entry.entries.ContainsKey(id)) { var delta = id - last; os.writeShort(delta); last = id; } } } /* write the child identifiers if required */ if ((flags & FLAG_IDENTIFIERS) != 0) { foreach (var entry in entries.Values) { foreach (var child in entry.entries.Values) { os.writeInt(child.identifier); } } } /* convert the stream to a byte array and then wrap a buffer */ var bytes = bout.toByteArray(); return(ByteBuffer.wrap(bytes)); } finally { os.close(); } }
public string UploadString(Uri u, string method, string data) { var w = new StringBuilder(); HttpURLConnection conn = null; try { var url = new java.net.URL(u.ToString()); conn = (HttpURLConnection)url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setInstanceFollowRedirects(false); conn.setRequestMethod(method); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("charset", "utf-8"); conn.setRequestProperty("content-length", "" + data.Length); conn.setUseCaches(false); try { if (Headers != null) { foreach (string key in Headers.AllKeys) { conn.addRequestProperty(key, Headers[key]); } } } catch (Exception e) { //System.Console.WriteLine("ERROR: Failed to write headers. Exception was:" + e.Message); } DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(data); wr.flush(); wr.close(); //var i = new java.io.InputStreamReader(url.openStream(), "UTF-8"); var i = new java.io.InputStreamReader(conn.getInputStream(), "UTF-8"); var reader = new java.io.BufferedReader(i); // can't we just read to the end? var line = reader.readLine(); while (line != null) { w.AppendLine(line); line = reader.readLine(); } reader.close(); } catch { // oops } if (conn != null) { conn.disconnect(); } return(w.ToString()); }
public static bool UpdateRecordInSdFile(string filename, int recindex, string molstring, string pagenum, string pagelabel, string examplenum, string iupacname, string enname) { bool blStatus = false; try { int intRecIndex = 0; MolInputStream molInStream = new MolInputStream(new FileInputStream(filename)); MolImporter molImp = new MolImporter(molInStream); string strInputFilePath = System.IO.Path.GetDirectoryName(filename); string strExecPath = Application.StartupPath; string strFileName = System.IO.Path.GetFileName(filename); string strOutFile = strExecPath + "\\" + strFileName; DataOutputStream dOutStream = new DataOutputStream(new FileOutputStream(strOutFile)); MolExporter mExpt = new MolExporter(dOutStream, "sdf"); Molecule objMolecule = new Molecule(); try { while (molImp.read(objMolecule)) { intRecIndex++; if (intRecIndex == recindex) { MolHandler molHandler = new MolHandler(molstring); Molecule molObj = molHandler.getMolecule(); objMolecule = molObj; objMolecule.setProperty("Page Number", pagenum); objMolecule.setProperty("Page Label", pagelabel); objMolecule.setProperty("Example Number", examplenum); objMolecule.setProperty("IUPAC Name", iupacname); objMolecule.setProperty("en name", enname); blStatus = true; } mExpt.write(objMolecule); } molImp.close(); molInStream.close(); mExpt.close(); dOutStream.close(); System.IO.File.Copy(strOutFile, filename, true); System.IO.File.Delete(strOutFile); } catch (Exception ex) { ErrorHandling_NTS.WriteErrorLog(ex.ToString()); } finally { molImp.close(); molInStream.close(); mExpt.close(); dOutStream.close(); } } catch (Exception ex) { ErrorHandling_NTS.WriteErrorLog(ex.ToString()); } return(blStatus); }
/// <summary> /// Encodes this <seealso cref="Sprite" /> into a <seealso cref="ByteBuffer" />. /// <p /> /// Please note that this is a fairly simple implementation which only /// supports vertical encoding. It does not attempt to use the offsets /// to save space. /// </summary> /// <returns> The buffer. </returns> /// <exception cref="IOException"> if an I/O exception occurs. </exception> public ByteBuffer Encode() { var bout = new ByteArrayOutputStream(); var os = new DataOutputStream(bout); try { /* set up some variables */ IList <int?> palette = new List <int?>(); palette.Add(0); // transparent colour /* write the sprites */ foreach (var image in frames) { /* check if we can encode this */ if (image.getWidth() != width || image.getHeight() != height) { throw new IOException("All frames must be the same size."); } /* loop through all the pixels constructing a palette */ var flags = FLAG_VERTICAL; // TODO: do we need to support horizontal encoding? for (var x = 0; x < width; x++) { for (var y = 0; y < height; y++) { /* grab the colour of this pixel */ var argb = image.getRGB(x, y); var alpha = (argb >> 24) & 0xFF; var rgb = argb & 0xFFFFFF; if (rgb == 0) { rgb = 1; } /* we need an alpha channel to encode this image */ if (alpha != 0 && alpha != 255) { flags |= FLAG_ALPHA; } /* add the colour to the palette if it isn't already in the palette */ if (!palette.Contains(rgb)) { if (palette.Count >= 256) { throw new IOException("Too many colours in this sprite!"); } palette.Add(rgb); } } } /* write this sprite */ os.write(flags); for (var x = 0; x < width; x++) { for (var y = 0; y < height; y++) { var argb = image.getRGB(x, y); var alpha = (argb >> 24) & 0xFF; var rgb = argb & 0xFFFFFF; if (rgb == 0) { rgb = 1; } if ((flags & FLAG_ALPHA) == 0 && alpha == 0) { os.write(0); } else { os.write(palette.IndexOf(rgb)); } } } /* write the alpha channel if this sprite has one */ if ((flags & FLAG_ALPHA) != 0) { for (var x = 0; x < width; x++) { for (var y = 0; y < height; y++) { var argb = image.getRGB(x, y); var alpha = (argb >> 24) & 0xFF; os.write(alpha); } } } } /* write the palette */ for (var i = 1; i < palette.Count; i++) { var rgb = (int)palette[i]; os.write((byte)(rgb >> 16)); os.write((byte)(rgb >> 8)); os.write((byte)rgb); } /* write the max width, height and palette size */ os.writeShort(width); os.writeShort(height); os.write(palette.Count - 1); /* write the individual offsets and dimensions */ for (var i = 0; i < frames.Length; i++) { os.writeShort(0); // offset X os.writeShort(0); // offset Y os.writeShort(width); os.writeShort(height); } /* write the number of frames */ os.writeShort(frames.Length); /* convert the stream to a byte array and then wrap a buffer */ var bytes = bout.toByteArray(); return(ByteBuffer.wrap(bytes)); } finally { os.close(); } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: public void close() throws java.io.IOException public override void Close() { Data.close(); }