static void TestRaw() { using (var vorbis = new NVorbis.VorbisReader(@"..\..\..\TestFiles\2test.ogg")) using (var outFile = System.IO.File.Create(@"..\..\..\TestFiles\2test.wav")) using (var writer = new System.IO.BinaryWriter(outFile)) { writer.Write(Encoding.ASCII.GetBytes("RIFF")); writer.Write(0); writer.Write(Encoding.ASCII.GetBytes("WAVE")); writer.Write(Encoding.ASCII.GetBytes("fmt ")); writer.Write(18); writer.Write((short)1); // PCM format writer.Write((short)vorbis.Channels); writer.Write(vorbis.SampleRate); writer.Write(vorbis.SampleRate * vorbis.Channels * 2); // avg bytes per second writer.Write((short)(2 * vorbis.Channels)); // block align writer.Write((short)16); // bits per sample writer.Write((short)0); // extra size writer.Write(Encoding.ASCII.GetBytes("data")); writer.Flush(); var dataPos = outFile.Position; writer.Write(0); var buf = new float[vorbis.SampleRate / 10 * vorbis.Channels]; int count; while ((count = vorbis.ReadSamples(buf, 0, buf.Length)) > 0) { for (int i = 0; i < count; i++) { var temp = (int)(32767f * buf[i]); if (temp > 32767) { temp = 32767; } else if (temp < -32768) { temp = -32768; } writer.Write((short)temp); } } writer.Flush(); writer.Seek(4, System.IO.SeekOrigin.Begin); writer.Write((int)(outFile.Length - 8L)); writer.Seek((int)dataPos, System.IO.SeekOrigin.Begin); writer.Write((int)(outFile.Length - dataPos - 4L)); writer.Flush(); } }
readonly private HashAlgorithm ha = HashAlgorithm.Create("SHA1"); // 160bit of entropy public NamesGenerator(Guid itemid, int dataversion, byte[] salt) { ms = new System.IO.MemoryStream(); bw = new System.IO.BinaryWriter(ms); bw.Write(itemid.ToByteArray()); bw.Write(dataversion); bw.Write(salt); bw.Flush(); seedpos = ms.Position; bw.Write(seed); bw.Flush(); ms.SetLength(ms.Position); }
public static byte[] SerializeVoxelAreaData (VoxelArea v) { #if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST System.IO.MemoryStream stream = new System.IO.MemoryStream(); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream); writer.Write (v.width); writer.Write (v.depth); writer.Write (v.linkedSpans.Length); for (int i=0;i<v.linkedSpans.Length;i++) { writer.Write(v.linkedSpans[i].area); writer.Write(v.linkedSpans[i].bottom); writer.Write(v.linkedSpans[i].next); writer.Write(v.linkedSpans[i].top); } //writer.Close(); writer.Flush(); Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(); stream.Position = 0; zip.AddEntry ("data",stream); System.IO.MemoryStream stream2 = new System.IO.MemoryStream(); zip.Save(stream2); byte[] bytes = stream2.ToArray(); stream.Close(); stream2.Close(); return bytes; #else throw new System.NotImplementedException ("This method only works with !ASTAR_RECAST_CLASS_BASED_LINKED_LIST"); #endif }
public static byte[] EncryptData(byte[] publickey, byte[] data) { using (System.Security.Cryptography.Aes myAes = System.Security.Cryptography.Aes.Create()) { System.Security.Cryptography.ICryptoTransform encryptor = myAes.CreateEncryptor(myAes.Key, myAes.IV); using (System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream()) { using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write)) { System.IO.MemoryStream headerms = new System.IO.MemoryStream(); System.IO.BinaryWriter headerbw = new System.IO.BinaryWriter(headerms); using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(csEncrypt)) { System.Security.Cryptography.RSACryptoServiceProvider public_key = new System.Security.Cryptography.RSACryptoServiceProvider(1024); public_key.ImportCspBlob(publickey); byte[] encryptedkey = public_key.Encrypt(Combine(myAes.Key, myAes.IV), false); headerbw.Write(encryptedkey.Length); headerbw.Write(myAes.Key.Length); headerbw.Write(myAes.IV.Length); headerbw.Write(encryptedkey); headerbw.Flush(); bw.Write(data); } byte[] result = Combine(headerms.ToArray(), msEncrypt.ToArray()); headerbw.Close(); return(result); } } } }
private void bunifuFlatButton1_Click(object sender, EventArgs e) { if (bunifuTextbox1.text == "" || bunifuTextbox2.text == "") { System.Windows.Forms.MessageBox.Show("Bir şeyleri yanlış yapıyorsun", ""); } else { if (!bunifuTextbox3.text.Contains(".exe")) { bunifuTextbox3.text += ".exe"; } if (!bunifuTextbox2.text.Contains(".")) { bunifuTextbox2.text = "." + bunifuTextbox2.text; } System.IO.File.Copy(Environment.CurrentDirectory + "/Ran.exe", Environment.CurrentDirectory + "/" + bunifuTextbox3.text); System.IO.BinaryWriter bw = new System.IO.BinaryWriter(new System.IO.FileStream(Environment.CurrentDirectory + "/" + bunifuTextbox3.text, System.IO.FileMode.Append)); bw.Write("-STARTKEY-" + bunifuTextbox1.text + "-ENDKEY-"); bw.Write("-STARTEXTENSION-" + bunifuTextbox2.text + "-ENDEXTENSION-"); bw.Flush(); bw.Close(); } }
public static byte[] SerializeVoxelAreaData (VoxelArea v) { System.IO.MemoryStream stream = new System.IO.MemoryStream(); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream); writer.Write (v.width); writer.Write (v.depth); writer.Write (v.linkedSpans.Length); for (int i=0;i<v.linkedSpans.Length;i++) { writer.Write(v.linkedSpans[i].area); writer.Write(v.linkedSpans[i].bottom); writer.Write(v.linkedSpans[i].next); writer.Write(v.linkedSpans[i].top); } //writer.Close(); writer.Flush(); Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(); stream.Position = 0; zip.AddEntry ("data",stream); System.IO.MemoryStream stream2 = new System.IO.MemoryStream(); zip.Save(stream2); byte[] bytes = stream2.ToArray(); stream.Close(); stream2.Close(); return bytes; }
static void CreateSelfSignCertificate(CertOption option) { var fileName = option.CertFileName; var subject = option.Subject; var password = option.Password; try { var securePassword = Certificate.ConvertSecureString(password); var startDate = DateTime.Now; var endDate = startDate.AddYears(option.Years); var certData = Certificate.CreateSelfSignCertificatePfx(subject, startDate, endDate, securePassword); using (var writer = new System.IO.BinaryWriter(System.IO.File.Open(fileName, System.IO.FileMode.Create))) { writer.Write(certData); writer.Flush(); writer.Close(); } securePassword = Certificate.ConvertSecureString(password); } catch (Exception e) { Console.WriteLine(e.Message); } }
public void Complete() { if (zinfoset == false) { throw new Exception("Z information not set - can't complete stream write."); } w_tlg.Write(topvws); w_tlg.Write(botvws); w_tlg.Write(m_toptz); w_tlg.Write(m_topbz); w_tlg.Write(m_bottz); w_tlg.Write(m_botbz); FlushStream(t_topvw); FlushStream(t_botvw); w_tlg.Write(toptks); w_tlg.Write(bottks); w_tlg.Write(linked); FlushStream(t_toptk); FlushStream(t_bottk); FlushStream(t_linked); FlushStream(t_topix); FlushStream(t_botix); long nextpos = w_tlg.BaseStream.Position; w_tlg.Seek((int)Section_Tracks_pos, System.IO.SeekOrigin.Begin); w_tlg.Write(nextpos); w_tlg.Seek(0, System.IO.SeekOrigin.End); w_tlg.Flush(); w_tlg.Close(); Dispose(); }
public static void CreateHeaderFile(string filename, int capacity) { int count = HashHelpers.GetPrime(capacity); using (System.IO.Stream stream = System.IO.File.Create(filename)) { using (System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream)) { writer.Write(count); writer.Write(0); writer.Write(0); writer.Write(-1); byte[] keydata = new byte[KEY_MAXLENGTH]; for (int i = 0; i < count; i++) { writer.Write(-1); writer.Write(0); writer.Write(0); writer.Write(0); writer.Write(keydata, 0, KEY_MAXLENGTH); } writer.Flush(); } } }
public static byte[] SerializeVoxelAreaData(VoxelArea v) { #if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST System.IO.MemoryStream stream = new System.IO.MemoryStream(); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream); writer.Write (v.width); writer.Write (v.depth); writer.Write (v.linkedSpans.Length); for (int i=0;i<v.linkedSpans.Length;i++) { writer.Write(v.linkedSpans[i].area); writer.Write(v.linkedSpans[i].bottom); writer.Write(v.linkedSpans[i].next); writer.Write(v.linkedSpans[i].top); } //writer.Close(); writer.Flush(); Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(); stream.Position = 0; zip.AddEntry ("data",stream); System.IO.MemoryStream stream2 = new System.IO.MemoryStream(); zip.Save(stream2); byte[] bytes = stream2.ToArray(); stream.Close(); stream2.Close(); return bytes; #else throw new System.NotImplementedException ("This method only works with !ASTAR_RECAST_CLASS_BASED_LINKED_LIST"); #endif }
public static byte[] SerializeVoxelAreaData(VoxelArea v) { System.IO.MemoryStream stream = new System.IO.MemoryStream(); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream); writer.Write(v.width); writer.Write(v.depth); writer.Write(v.linkedSpans.Length); for (int i = 0; i < v.linkedSpans.Length; i++) { writer.Write(v.linkedSpans[i].area); writer.Write(v.linkedSpans[i].bottom); writer.Write(v.linkedSpans[i].next); writer.Write(v.linkedSpans[i].top); } //writer.Close(); writer.Flush(); Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(); stream.Position = 0; zip.AddEntry("data", stream); System.IO.MemoryStream stream2 = new System.IO.MemoryStream(); zip.Save(stream2); byte[] bytes = stream2.ToArray(); stream.Close(); stream2.Close(); return(bytes); }
public byte[] doSerialize() { if (m_assembly == null) { return(null); } m_header.msg_full_name = m_body.ToString(); System.IO.MemoryStream stream = new System.IO.MemoryStream(); stream.Position = sizeof(uint) * 2; ProtoRW rw = new ProtoRW(); //ProtoBuf.Serializer.Serialize(stream, m_header); rw.Serialize(stream, m_header); m_headerLength = (uint)(stream.Length - sizeof(uint) * 2); //ProtoBuf.Serializer.Serialize(stream, m_body); rw.Serialize(stream, m_body); System.IO.BinaryWriter binaryWriter = new System.IO.BinaryWriter(stream); stream.Position = 0; m_totalLength = (uint)stream.Length; binaryWriter.Write(m_totalLength); binaryWriter.Write(m_headerLength); binaryWriter.Flush(); return(stream.ToArray()); }
public static void Save(string directory, string file,string ext, XCImageCollection images) { System.IO.BinaryWriter bw = new System.IO.BinaryWriter(System.IO.File.Create(directory+"\\"+file+ext)); foreach(XCImage tile in images) bw.Write(tile.Bytes); bw.Flush(); bw.Close(); }
public override bool Write(System.IO.BinaryWriter bw) { base.Write(bw); bw.Write((byte)_num); bw.Flush(); return(true); }
public void SaveToFile(string fileName) { using(var writer = new System.IO.BinaryWriter(System.IO.File.OpenWrite(fileName))) { writer.Write(_header); writer.Write(_bytes); writer.Flush(); } }
public void WriteZippedResources() { using (var binWriter = new System.IO.BinaryWriter(this.fileSystem.File.OpenWrite(MyDhtmlResourceSet.ZippedResources.LocalPath))) { binWriter.Write(Properties.Resources.Pickles_BaseDhtmlFiles); binWriter.Flush(); binWriter.Close(); } }
/** セーブ。 * * a_binary : バイナリー。 * a_full_path_with_extention : フルパス。拡張子付き。 * */ public static bool Save(byte[] a_binary, string a_full_path_with_extention) { using (System.IO.BinaryWriter t_stream = new System.IO.BinaryWriter(System.IO.File.Open(a_full_path_with_extention, System.IO.FileMode.Create))){ t_stream.Write(a_binary); t_stream.Flush(); t_stream.Close(); } return(true); }
public byte[] SaveStateBinary() { var ms = new System.IO.MemoryStream(savebuff2, true); var bw = new System.IO.BinaryWriter(ms); SaveStateBinary(bw); bw.Flush(); ms.Close(); return(savebuff2); }
public byte[] ToByteArray() { var stream = new System.IO.MemoryStream(); var writer = new System.IO.BinaryWriter(stream); writer.Write(this.Length); writer.Write(this.Kind); writer.Flush(); return(stream.ToArray()); }
static void Main(string[] args) { var options = new SwitchOptions(); if (!CommandLine.ParseArguments(args, options)) return; try { if (String.IsNullOrEmpty(options.outFile)) { Console.WriteLine("You must supply an outfile."); return; } var source = new System.IO.StreamReader(options.inFile); var lexed = new LexResult(); var r = Lexer.Lex(source, lexed); if (r == 0x00) { var destination = System.IO.File.Open(options.outFile, System.IO.FileMode.Create); var writer = new System.IO.BinaryWriter(destination); r = Assembler.Assemble(lexed, writer); writer.Flush(); destination.Flush(); writer.Close(); } Console.WriteLine("Finished with code " + r); } /*case "emulate": { var source = System.IO.File.Open(options.inFile, System.IO.FileMode.Open); var emulator = new IN8(); source.Read(emulator.MEM, 0, 0xFFFF); // Attach devices var teletypeTerminal = new TT3(); emulator.AttachHardware(teletypeTerminal, 0x04); while (emulator.STATE_FLAGS == 0x00) emulator.Step(); Console.WriteLine(String.Format("Finished in state {0:X2}", emulator.STATE_FLAGS)); Console.WriteLine(String.Format("{0:X2} {1:X2} {2:X2} {3:X2} {4:X2} {5:X2} {6:X2} {7:X2}", emulator.A, emulator.B, emulator.C, emulator.D, emulator.E, emulator.H, emulator.L, emulator.O)); Console.WriteLine(String.Format("{0:X4} {1:X4} {2:X8}", emulator.IP, emulator.SP, emulator.CLOCK)); break; } } }*/ catch (Exception e) { Console.WriteLine("An error occured."); Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); } }
byte[] WriteString(string s) { var ms = new System.IO.MemoryStream(); var bw = new System.IO.BinaryWriter(ms); bw.Write(s); bw.Flush(); var bytes = ms.ToArray(); return(bytes); }
/// <summary>output methods: </summary> public override void FlushBuffer(byte[] b, int offset, int size) { file.Write(b, offset, size); // {{dougsale-2.4.0}} // When writing frequently with small amounts of data, the data isn't flushed to disk. // Thus, attempting to read the data soon after this method is invoked leads to // BufferedIndexInput.Refill() throwing an IOException for reading past EOF. // Test\Index\TestDoc.cs demonstrates such a situation. // Forcing a flush here prevents said issue. file.Flush(); }
NumberFormatInfo nfi = NumberFormatInfo.InvariantInfo; // so we are region independent in terms of "." and "," for floats private void RArecordCheckBox_CheckedChanged(object sender, EventArgs e) { header_data = new byte[60]; if (RArecordCheckBox.Checked) { RArecordCheckBox.BackColor = Color.LimeGreen; RArecordCheckBox.ForeColor = Color.Black; RArecordCheckBox.Text = "Stop"; try { writer = new System.IO.BinaryWriter(System.IO.File.Open("RA_data.csv", System.IO.FileMode.Create)); } catch (Exception ex) { MessageBox.Show(ex.Message); } textBox_file_date_time.Visible = false; textBox_file_comment.Visible = false; construct_header(); time0 = Environment.TickCount; sig_level = console.NewMeterData; sig_level2 = console.Rx2MeterData; // initial_sig = sig_level; sig_level_pwr = Math.Pow(10.0, (double)sig_level); sig_level2_pwr = Math.Pow(10.0, (double)sig_level2); sig_max = sig_level + 10; // initial value for sig_max sig_min = sig_max - 10; rescale = true; RA_count = 1; for (int i = 0; i < 10000; i++) // clear any previously acquired data { sig_data[i] = 0; time_data[i] = 0; } data_points = 1; picRAGraph.Invalidate(); // draw data display labelTS10.Text = ""; // data saved msg button_readFile.Enabled = false; RA_timer.Enabled = true; } else { RA_timer.Enabled = false; RArecordCheckBox.BackColor = Color.DarkGreen; RArecordCheckBox.ForeColor = Color.White; RArecordCheckBox.Text = "Start"; writer.Flush(); writer.Close(); labelTS10.BackColor = System.Drawing.SystemColors.InactiveCaptionText; labelTS10.ForeColor = System.Drawing.SystemColors.Highlight; labelTS10.Text = "data written to: RA_data.csv"; button_readFile.Enabled = true; } }
private bool Beep(int volume, int frequency, int duration) { try { double amplitude = volume * 1.27; double a = ((amplitude * (System.Math.Pow(2, 15))) / 1000) - 1; double deltaFt = 2 * System.Math.PI * frequency / 8000; double samples = 441 * (duration / 100); int bytes = Convert.ToInt32(samples) * 4; int[] hdr = { 0x46464952, 36 + bytes, 0x45564157, 0x20746d66, 16, 0x20001, 8000, 176400, 0x100004, 0x61746164, bytes }; using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(44 + bytes)) { using (System.IO.BinaryWriter binaryWriter = new System.IO.BinaryWriter(memoryStream)) { for (int i = 0; i <= hdr.Length - 1; i++) { binaryWriter.Write(hdr[i]); } for (int T = 0; T <= Convert.ToInt32(samples) - 1; T++) { short sample = Convert.ToInt16(a * System.Math.Sin(deltaFt * T)); binaryWriter.Write(sample); binaryWriter.Write(sample); } binaryWriter.Flush(); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); using (System.Media.SoundPlayer sp = new System.Media.SoundPlayer(memoryStream)) { sp.PlaySync(); } } } } catch { return(false); } return(true); }
public override bool Write(System.IO.BinaryWriter bw) { base.Write(bw); bw.Write(aid); bw.Write(lig1); bw.Write(lig2); bw.Write((short)0); bw.Write(sex); bw.Flush(); return(true); }
public override bool Write(System.IO.BinaryWriter bw) { base.Write(bw); bw.Write(aid); bw.Write(gid); bw.Write(auth); bw.Write(0); bw.Write(sex); bw.Flush(); return(true); }
public static SCNGeometry ToSCNGeometry(this Solid csg) { if (csg.Polygons.Count == 0) { return(SCNGeometry.Create()); } else { var verts = csg. Polygons. SelectMany(x => x.Vertices). Select(ToSCNVector3). ToArray(); var norms = csg. Polygons. SelectMany(x => { var n = x.Plane.Normal.ToSCNVector3(); return(x.Vertices.Select(_ => n)); }). ToArray(); var vertsSource = SCNGeometrySource.FromVertices(verts); var normsSource = SCNGeometrySource.FromNormals(norms); var sources = new[] { vertsSource, normsSource }; var triStream = new System.IO.MemoryStream(); var triWriter = new System.IO.BinaryWriter(triStream); var triCount = 0; var vi = 0; foreach (var p in csg.Polygons) { for (var i = 2; i < p.Vertices.Count; i++) { triWriter.Write(vi); triWriter.Write(vi + i - 1); triWriter.Write(vi + i); } triCount += p.Vertices.Count - 2; vi += p.Vertices.Count; } triWriter.Flush(); var triData = NSData.FromArray(triStream.ToArray()); var elem = SCNGeometryElement.FromData(triData, SCNGeometryPrimitiveType.Triangles, triCount, 4); var elements = new[] { elem }; var g = SCNGeometry.Create(sources, elements); g.FirstMaterial.Diffuse.ContentColor = NSColor.LightGray; return(g); } }
private HeightfieldTerrainShape _CreateTerrainShape() { Terrain t = GetComponent <Terrain>(); if (t == null) { Debug.LogError("Needs to be attached to a game object with a Terrain component." + name); return(null); } BTerrainCollisionObject tco = GetComponent <BTerrainCollisionObject>(); if (tco == null) { Debug.LogError("Needs to be attached to a game object with a BTerrainCollisionObject." + name); } TerrainData td = t.terrainData; int width = td.heightmapWidth; int length = td.heightmapHeight; float maxHeight = td.size.y; //generate procedural data byte[] terr = new byte[width * length * sizeof(float)]; System.IO.MemoryStream file = new System.IO.MemoryStream(terr); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(file); for (int i = 0; i < length; i++) { float[,] row = td.GetHeights(0, i, width, 1); for (int j = 0; j < width; j++) { writer.Write(row[0, j] * maxHeight); } } writer.Flush(); file.Position = 0; pinnedTerrainData = GCHandle.Alloc(terr, GCHandleType.Pinned); HeightfieldTerrainShape hs = new HeightfieldTerrainShape(width, length, pinnedTerrainData.AddrOfPinnedObject(), 1f, 0f, maxHeight, upIndex, scalarType, false); hs.SetUseDiamondSubdivision(true); hs.LocalScaling = new BulletSharp.Math.Vector3(td.heightmapScale.x, 1f, td.heightmapScale.z); //just allocated several hundred float arrays. Garbage collect now since 99% likely we just loaded the scene GC.Collect(); return(hs); }
public void SendPacket(PacketHeader header, Payload payload) { System.Diagnostics.Debug.WriteLine("Writing packet of type " + header.Type.ToString()); lock (StateSyncObject) { header.Write(Writer); if (payload != null) { payload.Write(Writer); } Writer.Flush(); } }
/** バイナリファイル書き込み。 */ public static void WriteBinaryFile(Fee.File.Path a_assets_path, byte[] a_binary) { try{ using (System.IO.BinaryWriter t_stream = new System.IO.BinaryWriter(System.IO.File.Open(Fee.File.Path.CreateAssetsPath(a_assets_path, Fee.File.Path.SEPARATOR).GetPath(), System.IO.FileMode.Create))){ t_stream.Write(a_binary); t_stream.Flush(); t_stream.Close(); } Tool.EditorLog("WriteBinaryFile : " + a_assets_path.GetPath()); }catch (System.Exception t_exception) { Tool.EditorLogError(t_exception.Message); } }
public byte[] SaveStateBinary() { var ms = new System.IO.MemoryStream(SaveStateBuff2, true); var bw = new System.IO.BinaryWriter(ms); SaveStateBinary(bw); bw.Flush(); if (ms.Position != SaveStateBuff2.Length) { throw new InvalidOperationException("Unexpected savestate length!"); } bw.Close(); return(SaveStateBuff2); }
public static byte[] ToByteArray(List <string> textData) { using (var ms = new System.IO.MemoryStream()) using (var bw = new System.IO.BinaryWriter(ms)) { bw.Write(textData.Count); for (int i = 0; i < textData.Count; i++) { bw.Write(textData[i]); } bw.Flush(); return(ms.ToArray()); } }
public static string formatHierarchyId(object data) { SqlHierarchyId hier = (SqlHierarchyId)data; byte[] ba; using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(ms)) { hier.Write(w); w.Flush(); ba = ms.ToArray(); } return("0x" + BitConverter.ToString(ba).Replace("-", "")); }
/// <summary> /// 二进制读取文件,任何文件 /// </summary> private void CopyFile(string SourceFile, string AimFile) { byte[] bytTemp = new byte[4096];//字节数组 long lngHad = 0; long lngCount; int z = 5000; //源文件流 System.IO.FileStream fsSource = new System.IO.FileStream(SourceFile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read, 4); //二进制读取器 System.IO.BinaryReader bRead = new System.IO.BinaryReader(fsSource); //定位源文件流的头部 bRead.BaseStream.Seek(0, System.IO.SeekOrigin.Begin); if (fsSource.Position > 0) { fsSource.Position = 0; } lngCount = fsSource.Length; if (System.IO.File.Exists(AimFile)) { System.IO.File.Delete(AimFile); } //目标文件流 System.IO.FileStream fsAim = new System.IO.FileStream(AimFile, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write, System.IO.FileShare.Write, 4); //二进制写入器 System.IO.BinaryWriter bWrite = new System.IO.BinaryWriter(fsAim); while (z >= 4096) { z = (int)bRead.Read(bytTemp, 0, bytTemp.Length); //读入字节数组,返回读取的字节数量,如果小于4096,则到了文件尾 bWrite.Write(bytTemp, 0, bytTemp.Length); //从字节数组写入目标文件流 lngHad += z; string show = "从" + SourceFile + "到" + AimFile; OnCopyFile(lngHad, lngCount, show);//触发事件 来控制主线程 这里是进度条和已完成复制文件字节显示 } bWrite.Flush();//清理缓存区 bWrite.Close(); bRead.Close(); fsAim.Close(); fsSource.Close(); }
/// <summary> /// Simple hash to detect configuration changes /// </summary> /// <param name="doc">Configuration XML document.</param> /// <param name="timestamp">Last time the document has been changed.</param> /// <returns>Hexadecimal string represting hash value</returns> private string ComputeHash(XDocument doc, DateTime timestamp) { using (var stream = new System.IO.MemoryStream()) using (var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider()) using (var w = new System.IO.BinaryWriter(stream)) { w.Write(timestamp.ToBinary()); w.Flush(); doc.Save(stream, SaveOptions.OmitDuplicateNamespaces); stream.Flush(); var hash = md5.ComputeHash(stream.GetBuffer()); string hex = BitConverter.ToString(hash); return(hex.Replace("-", string.Empty)); } }
public string SendLan(string comando) { string rta = string.Empty; if (tcpClient.Connected) { escreve.Write(comando); escreve.Flush(); if (comando.Trim() != "(&I)") { rta = ReceiveLanData(); } } return(rta); }
public override CollisionShape GetCollisionShape() { if (collisionShapePtr == null) { Terrain t = GetComponent<Terrain>(); if (t == null) { Debug.LogError("Needs to be attached to a game object with a Terrain component." + name); return null; } BTerrainCollisionObject tco = GetComponent<BTerrainCollisionObject>(); if (tco == null) { Debug.LogError("Needs to be attached to a game object with a BTerrainCollisionObject." + name); } TerrainData td = t.terrainData; int width = td.heightmapWidth; int length = td.heightmapHeight; float maxHeight = td.size.y; //generate procedural data byte[] terr = new byte[width * length * sizeof(float)]; System.IO.MemoryStream file = new System.IO.MemoryStream(terr); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(file); for (int i = 0; i < length; i++) { float[,] row = td.GetHeights(0, i, width, 1); for (int j = 0; j < width; j++) { writer.Write((float)row[0, j] * maxHeight); } } writer.Flush(); file.Position = 0; pinnedTerrainData = GCHandle.Alloc(terr,GCHandleType.Pinned); collisionShapePtr = new HeightfieldTerrainShape(width, length, pinnedTerrainData.AddrOfPinnedObject(), 1f, 0f, maxHeight, upIndex, scalarType, false); ((HeightfieldTerrainShape)collisionShapePtr).SetUseDiamondSubdivision(true); ((HeightfieldTerrainShape)collisionShapePtr).LocalScaling = new BulletSharp.Math.Vector3(td.heightmapScale.x, 1f, td.heightmapScale.z); //just allocated several hundred float arrays. Garbage collect now since 99% likely we just loaded the scene GC.Collect(); } return collisionShapePtr; }
private void WriteToSocket(byte[] buffer) { try { System.IO.StreamWriter sw = new System.IO.StreamWriter(ns); sw.WriteLine(buffer.Length.ToString()); sw.Flush(); System.IO.BinaryWriter bw = new System.IO.BinaryWriter(ns); System.Console.WriteLine("size of array: " + buffer.Length); bw.Write(buffer); bw.Flush(); } catch (Exception) { Idp.DataChanged -= Idp_DataChanged; ns.Close(); SocketForClient.Close(); } }
public byte[] SaveStateBinary() { var ms = new System.IO.MemoryStream(savebuff2, true); var bw = new System.IO.BinaryWriter(ms); SaveStateBinary(bw); bw.Flush(); ms.Close(); return savebuff2; }
public byte[] SaveStateBinary() { var ms = new System.IO.MemoryStream(SaveStateBuff2, true); var bw = new System.IO.BinaryWriter(ms); SaveStateBinary(bw); bw.Flush(); if (ms.Position != SaveStateBuff2.Length) throw new InvalidOperationException("Unexpected savestate length!"); bw.Close(); return SaveStateBuff2; }
public void connect() { Program.Log("connect"); NetworkStream myClientStream; while (!terminate) { TcpClient server = new TcpClient(); IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000); Program.Log("Attempting to connect to " + serverEndPoint.Address.ToString() + "on port number " + serverEndPoint.Port.ToString()); int sleepTime = 5; // זמן המתנה בין נסיונות התחברות - נתחיל ב 5 שנייה #region CONNECT do { try { Program.Log("Attempting to connect ..."); server.Connect(serverEndPoint); } catch (Exception e) { Program.Log("connect threw: " + e.Message); Program.Log("sleeping " + sleepTime + " sec ..."); System.Threading.Thread.Sleep(sleepTime * 1000); if (sleepTime < 60 * 10) // הכי הרבה נמתין 10 דקות { sleepTime += 10; } } } while (!terminate && !server.Connected); // עד שנתחבר או שהורו למטלה לעצור #endregion Program.Log("I am connected to " + IPAddress.Parse(((IPEndPoint)server.Client.RemoteEndPoint).Address.ToString()) + "on port number " + ((IPEndPoint)server.Client.RemoteEndPoint).Port.ToString()); // Using the LocalEndPoint property. Program.Log("My local IpAddress is :" + IPAddress.Parse(((IPEndPoint)server.Client.LocalEndPoint).Address.ToString()) + "I am connected on port number " + ((IPEndPoint)server.Client.LocalEndPoint).Port.ToString()); myClientStream = server.GetStream(); if (myClientStream.CanWrite && myClientStream.CanRead) #region READ { myClientWriter = new System.IO.BinaryWriter(myClientStream); myClientReader = new System.IO.BinaryReader(myClientStream); // Point point; string tempString = ""; reconnect = false; do { // if (myClientStream.DataAvailable) { Program.Log("reading ..."); try { tempString = myClientReader.ReadString(); } catch (Exception e) { Program.Log("ReadString threw: " + e.Message); reconnect = true; continue; } Program.Log("request is " + tempString); string[] items = tempString.Split('#'); try { switch (items[0]) { case THComm.Tokens.TestRequest: Program.Log("Port" + ((IPEndPoint)server.Client.LocalEndPoint).Port.ToString() + " got Test"); for (int i = 10; i < 101; i += 10) { myClientWriter.Write(THComm.Tokens.Progress); myClientWriter.Write(i); Console.Write(" ... " + i); System.Threading.Thread.Sleep(100); } Console.WriteLine(); break; case THComm.Tokens.ScreenCapRequest: { Program.Log("Port" + ((IPEndPoint)server.Client.LocalEndPoint).Port.ToString() + " got ScreenCap"); THDevice.Device sc = new THDevice.ScreenCap(); byte[] data = sc.GetData(); Program.Log("Port" + ((IPEndPoint)server.Client.LocalEndPoint).Port.ToString() + " acquired ScreenCap length=" + data.Length.ToString()); myClientWriter.Write(THComm.Tokens.Data); myClientWriter.Write(data.Length); myClientWriter.Write(data); Program.Log("Port" + ((IPEndPoint)server.Client.LocalEndPoint).Port.ToString() + " sent ScreenCap "); } break; case THComm.Tokens.CamCapRequest: { Program.Log("Port" + ((IPEndPoint)server.Client.LocalEndPoint).Port.ToString() + " got CamCap"); THDevice.Device device = new THDevice.WebCam(); byte[] data = device.GetData(); myClientWriter.Write(THComm.Tokens.Data); myClientWriter.Write(data.Length); myClientWriter.Write(data); } break; case THComm.Tokens.Terminate: { Program.Log("Port" + ((IPEndPoint)server.Client.LocalEndPoint).Port.ToString() + " got Terminate"); terminate = true; } break; } } catch (Exception e) { Program.Log("process request threw, terminating loop: " + e.Message); reconnect = true; } } } while (!reconnect && !terminate); Program.Log("read loop done"); try { myClientWriter.Write(THComm.Tokens.Terminate); Program.Log("terminate acknowledged"); myClientWriter.Flush(); Program.Log("writer flushed"); myClientWriter.Close(); Program.Log("writer closed"); } catch (Exception e) { Program.Log("closing threw" + e.Message); } server.Close(); } #endregion } }
public static void SaveAssembly2(string assemblyName, string destinationPath) { string sql = @"SELECT af.name, af.content FROM sys.assemblies a INNER JOIN sys.assembly_files af ON a.assembly_id = af.assembly_id WHERE a.name = @assemblyname"; using (System.Data.Common.DbConnection conn = new System.Data.SqlClient.SqlConnection("context connection=true")) //Create current context connection { using (System.Data.Common.DbCommand cmd = new System.Data.SqlClient.SqlCommand(sql, (System.Data.SqlClient.SqlConnection)conn)) { System.Data.Common.DbParameter param = new System.Data.SqlClient.SqlParameter("@assemblyname", System.Data.SqlDbType.NVarChar); param.Value = assemblyName; // param.Size = 128; cmd.Parameters.Add(param); using (System.IO.Stream fs = new System.IO.FileStream("logo" + "pub_id" + ".bmp", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write)) { using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs)) { long startIndex = 0; var buffer = new byte[1024]; int bufferSize = buffer.Length; if(cmd.Connection.State != System.Data.ConnectionState.Open) cmd.Connection.Open(); //Open the context connetion using (System.Data.Common.DbDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) //Iterate through assembly files { string assemblyFileName = reader.GetString(0); //get assembly file name from the name (first) column long retval = reader.GetBytes(1, startIndex, buffer, 0, bufferSize); // Continue reading and writing while there are bytes beyond the size of the buffer. while (retval == bufferSize) { bw.Write(buffer); bw.Flush(); // Reposition the start index to the end of the last buffer and fill the buffer. startIndex += bufferSize; retval = reader.GetBytes(1, startIndex, buffer, 0, bufferSize); } // Whend // Write the remaining buffer. bw.Write(buffer, 0, (int)retval); bw.Flush(); bw.Close(); } // Whend reader.Read } // End Using reader } // End using bw fs.Flush(); fs.Close(); } // End using fs } // End using cmd if (conn.State != System.Data.ConnectionState.Closed) conn.Close(); } // End Using conn }
/// <summary> Evaluates a classifier with the options given in an array of /// strings. <p/> /// /// Valid options are: <p/> /// /// -t name of training file <br/> /// Name of the file with the training data. (required) <p/> /// /// -T name of test file <br/> /// Name of the file with the test data. If missing a cross-validation /// is performed. <p/> /// /// -c class index <br/> /// Index of the class attribute (1, 2, ...; default: last). <p/> /// /// -x number of folds <br/> /// The number of folds for the cross-validation (default: 10). <p/> /// /// -s random number seed <br/> /// Random number seed for the cross-validation (default: 1). <p/> /// /// -m file with cost matrix <br/> /// The name of a file containing a cost matrix. <p/> /// /// -l name of model input file <br/> /// Loads classifier from the given file. <p/> /// /// -d name of model output file <br/> /// Saves classifier built from the training data into the given file. <p/> /// /// -v <br/> /// Outputs no statistics for the training data. <p/> /// /// -o <br/> /// Outputs statistics only, not the classifier. <p/> /// /// -i <br/> /// Outputs detailed information-retrieval statistics per class. <p/> /// /// -k <br/> /// Outputs information-theoretic statistics. <p/> /// /// -p <br/> /// Outputs predictions for test instances (and nothing else). <p/> /// /// -r <br/> /// Outputs cumulative margin distribution (and nothing else). <p/> /// /// -g <br/> /// Only for classifiers that implement "Graphable." Outputs /// the graph representation of the classifier (and nothing /// else). <p/> /// /// </summary> /// <param name="classifier">machine learning classifier /// </param> /// <param name="options">the array of string containing the options /// </param> /// <throws> Exception if model could not be evaluated successfully </throws> /// <returns> a string describing the results /// </returns> public static System.String evaluateModel(Classifier classifier, System.String[] options) { Instances train = null, tempTrain, test = null, template = null; int seed = 1, folds = 10, classIndex = - 1; System.String trainFileName, testFileName, sourceClass, classIndexString, seedString, foldsString, objectInputFileName, objectOutputFileName, attributeRangeString; bool noOutput = false, printClassifications = false, trainStatistics = true, printMargins = false, printComplexityStatistics = false, printGraph = false, classStatistics = false, printSource = false; System.Text.StringBuilder text = new System.Text.StringBuilder(); System.IO.StreamReader trainReader = null, testReader = null; //UPGRADE_TODO: Class 'java.io.ObjectInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioObjectInputStream'" System.IO.BinaryReader objectInputStream = null; System.IO.Stream objectStream=null; CostMatrix costMatrix = null; System.Text.StringBuilder schemeOptionsText = null; Range attributesToOutput = null; long trainTimeStart = 0, trainTimeElapsed = 0, testTimeStart = 0, testTimeElapsed = 0; Classifier classifierBackup; try { // Get basic options (options the same for all schemes) classIndexString = Utils.getOption('c', options); if (classIndexString.Length != 0) { if (classIndexString.Equals("first")) classIndex = 1; else if (classIndexString.Equals("last")) classIndex = - 1; else classIndex = System.Int32.Parse(classIndexString); } trainFileName = Utils.getOption('t', options); objectInputFileName = Utils.getOption('l', options); objectOutputFileName = Utils.getOption('d', options); testFileName = Utils.getOption('T', options); if (trainFileName.Length == 0) { if (objectInputFileName.Length == 0) { throw new System.Exception("No training file and no object " + "input file given."); } if (testFileName.Length == 0) { throw new System.Exception("No training file and no test " + "file given."); } } else if ((objectInputFileName.Length != 0) && ((!(classifier is UpdateableClassifier)) || (testFileName.Length == 0))) { throw new System.Exception("Classifier not incremental, or no " + "test file provided: can't " + "use both train and model file."); } try { if (trainFileName.Length != 0) { //UPGRADE_TODO: The differences in the expected value of parameters for constructor 'java.io.BufferedReader.BufferedReader' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" //UPGRADE_WARNING: At least one expression was used more than once in the target code. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1181'" //UPGRADE_TODO: Constructor 'java.io.FileReader.FileReader' was converted to 'System.IO.StreamReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" trainReader = new System.IO.StreamReader(new System.IO.StreamReader(trainFileName, System.Text.Encoding.Default).BaseStream, new System.IO.StreamReader(trainFileName, System.Text.Encoding.Default).CurrentEncoding); } if (testFileName.Length != 0) { //UPGRADE_TODO: The differences in the expected value of parameters for constructor 'java.io.BufferedReader.BufferedReader' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" //UPGRADE_WARNING: At least one expression was used more than once in the target code. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1181'" //UPGRADE_TODO: Constructor 'java.io.FileReader.FileReader' was converted to 'System.IO.StreamReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" testReader = new System.IO.StreamReader(new System.IO.StreamReader(testFileName, System.Text.Encoding.Default).BaseStream, new System.IO.StreamReader(testFileName, System.Text.Encoding.Default).CurrentEncoding); } if (objectInputFileName.Length != 0) { //UPGRADE_TODO: Constructor 'java.io.FileInputStream.FileInputStream' was converted to 'System.IO.FileStream.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioFileInputStreamFileInputStream_javalangString'" objectStream= new System.IO.FileStream(objectInputFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); if (objectInputFileName.EndsWith(".gz")) { //UPGRADE_ISSUE: Constructor 'java.util.zip.GZIPInputStream.GZIPInputStream' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javautilzipGZIPInputStream'" objectStream= new ICSharpCode.SharpZipLib.GZip.GZipInputStream(objectStream); } //UPGRADE_TODO: Class 'java.io.ObjectInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioObjectInputStream'" objectInputStream = new System.IO.BinaryReader(objectStream); } } catch (System.Exception e) { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" throw new System.Exception("Can't open file " + e.Message + '.'); } if (testFileName.Length != 0) { template = test = new Instances(testReader, 1); if (classIndex != - 1) { test.ClassIndex = classIndex - 1; } else { test.ClassIndex = test.numAttributes() - 1; } if (classIndex > test.numAttributes()) { throw new System.Exception("Index of class attribute too large."); } } if (trainFileName.Length != 0) { if ((classifier is UpdateableClassifier) && (testFileName.Length != 0)) { train = new Instances(trainReader, 1); } else { train = new Instances(trainReader); } template = train; if (classIndex != - 1) { train.ClassIndex = classIndex - 1; } else { train.ClassIndex = train.numAttributes() - 1; } if ((testFileName.Length != 0) && !test.equalHeaders(train)) { throw new System.ArgumentException("Train and test file not compatible!"); } if (classIndex > train.numAttributes()) { throw new System.Exception("Index of class attribute too large."); } } if (template == null) { throw new System.Exception("No actual dataset provided to use as template"); } seedString = Utils.getOption('s', options); if (seedString.Length != 0) { seed = System.Int32.Parse(seedString); } foldsString = Utils.getOption('x', options); if (foldsString.Length != 0) { folds = System.Int32.Parse(foldsString); } costMatrix = handleCostOption(Utils.getOption('m', options), template.numClasses()); classStatistics = Utils.getFlag('i', options); noOutput = Utils.getFlag('o', options); trainStatistics = !Utils.getFlag('v', options); printComplexityStatistics = Utils.getFlag('k', options); printMargins = Utils.getFlag('r', options); printGraph = Utils.getFlag('g', options); sourceClass = Utils.getOption('z', options); printSource = (sourceClass.Length != 0); // Check -p option try { attributeRangeString = Utils.getOption('p', options); } catch (System.Exception e) { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" throw new System.Exception(e.Message + "\nNOTE: the -p option has changed. " + "It now expects a parameter specifying a range of attributes " + "to list with the predictions. Use '-p 0' for none."); } if (attributeRangeString.Length != 0) { // if no test file given, we cannot print predictions if (testFileName.Length == 0) throw new System.Exception("Cannot print predictions ('-p') without test file ('-T')!"); printClassifications = true; if (!attributeRangeString.Equals("0")) attributesToOutput = new Range(attributeRangeString); } // if no training file given, we don't have any priors if ((trainFileName.Length == 0) && (printComplexityStatistics)) throw new System.Exception("Cannot print complexity statistics ('-k') without training file ('-t')!"); // If a model file is given, we can't process // scheme-specific options if (objectInputFileName.Length != 0) { Utils.checkForRemainingOptions(options); } else { // Set options for classifier // if (classifier instanceof OptionHandler) // { // for (int i = 0; i < options.length; i++) // { // if (options[i].length() != 0) // { // if (schemeOptionsText == null) // { // schemeOptionsText = new StringBuffer(); // } // if (options[i].indexOf(' ') != -1) // { // schemeOptionsText.append('"' + options[i] + "\" "); // } // else // { // schemeOptionsText.append(options[i] + " "); // } // } // } // ((OptionHandler)classifier).setOptions(options); // } } Utils.checkForRemainingOptions(options); } catch (System.Exception e) { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" throw new System.Exception("\nWeka exception: " + e.Message + makeOptionString(classifier)); } // Setup up evaluation objects Evaluation trainingEvaluation = new Evaluation(new Instances(template, 0), costMatrix); Evaluation testingEvaluation = new Evaluation(new Instances(template, 0), costMatrix); if (objectInputFileName.Length != 0) { testingEvaluation.useNoPriors(); // Load classifier from file //UPGRADE_WARNING: Method 'java.io.ObjectInputStream.readObject' was converted to 'SupportClass.Deserialize' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" //classifier = (Classifier) SupportClass.Deserialize(objectInputStream); //FileStream fs = new FileStream("DataFile.dat", FileMode.Open); try { BinaryFormatter formatter = new BinaryFormatter(); // Deserialize the hashtable from the file and // assign the reference to the local variable. // addresses = (Hashtable)formatter.Deserialize(fs); classifier = (Classifier)formatter.Deserialize(objectStream); } catch (Exception e) { Console.WriteLine("Failed to deserialize. Reason: " + e.Message); throw; } finally { objectStream.Close(); //fs.Close(); } objectInputStream.Close(); } // backup of fully setup classifier for cross-validation classifierBackup = Classifier.makeCopy(classifier); // Build the classifier if no object file provided if ((classifier is UpdateableClassifier) && (testFileName.Length != 0) && (costMatrix == null) && (trainFileName.Length != 0)) { // Build classifier incrementally trainingEvaluation.Priors = train; testingEvaluation.Priors = train; trainTimeStart = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; if (objectInputFileName.Length == 0) { classifier.buildClassifier(train); } while (train.readInstance(trainReader)) { trainingEvaluation.updatePriors(train.instance(0)); testingEvaluation.updatePriors(train.instance(0)); ((UpdateableClassifier) classifier).updateClassifier(train.instance(0)); train.delete(0); } trainTimeElapsed = (System.DateTime.Now.Ticks - 621355968000000000) / 10000 - trainTimeStart; trainReader.Close(); } else if (objectInputFileName.Length == 0) { // Build classifier in one go tempTrain = new Instances(train); trainingEvaluation.Priors = tempTrain; testingEvaluation.Priors = tempTrain; trainTimeStart = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; classifier.buildClassifier(tempTrain); trainTimeElapsed = (System.DateTime.Now.Ticks - 621355968000000000) / 10000 - trainTimeStart; } // Save the classifier if an object output file is provided if (objectOutputFileName.Length != 0) { //UPGRADE_TODO: Constructor 'java.io.FileOutputStream.FileOutputStream' was converted to 'System.IO.FileStream.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioFileOutputStreamFileOutputStream_javalangString'" System.IO.Stream os = new System.IO.FileStream(objectOutputFileName, System.IO.FileMode.Create); if (objectOutputFileName.EndsWith(".gz")) { //UPGRADE_ISSUE: Constructor 'java.util.zip.GZIPOutputStream.GZIPOutputStream' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javautilzipGZIPOutputStream'" os = new ICSharpCode.SharpZipLib.GZip.GZipOutputStream(os); } //UPGRADE_TODO: Class 'java.io.ObjectOutputStream' was converted to 'System.IO.BinaryWriter' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioObjectOutputStream'" System.IO.BinaryWriter objectOutputStream = new System.IO.BinaryWriter(os); //UPGRADE_TODO: Method 'java.io.ObjectOutputStream.writeObject' was converted to 'SupportClass.Serialize' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioObjectOutputStreamwriteObject_javalangObject'" //SupportClass.Serialize(objectOutputStream, classifier); BinaryFormatter bformatter = new BinaryFormatter(); bformatter.Serialize(os, classifier); objectOutputStream.Flush(); objectOutputStream.Close(); } // If classifier is drawable output string describing graph if ((classifier is Drawable) && (printGraph)) { return ((Drawable) classifier).graph(); } // Output the classifier as equivalent source if ((classifier is Sourcable) && (printSource)) { return wekaStaticWrapper((Sourcable) classifier, sourceClass); } // Output test instance predictions only if (printClassifications) { return toPrintClassifications(classifier, new Instances(template, 0), testFileName, classIndex, attributesToOutput); } // Output model if (!(noOutput || printMargins)) { // if (classifier instanceof OptionHandler) // { // if (schemeOptionsText != null) // { // text.append("\nOptions: "+schemeOptionsText); // text.append("\n"); // } // } //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" text.Append("\n" + classifier.ToString() + "\n"); } if (!printMargins && (costMatrix != null)) { text.Append("\n=== Evaluation Cost Matrix ===\n\n").Append(costMatrix.ToString()); } // Compute error estimate from training data if ((trainStatistics) && (trainFileName.Length != 0)) { if ((classifier is UpdateableClassifier) && (testFileName.Length != 0) && (costMatrix == null)) { // Classifier was trained incrementally, so we have to // reopen the training data in order to test on it. //UPGRADE_TODO: The differences in the expected value of parameters for constructor 'java.io.BufferedReader.BufferedReader' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" //UPGRADE_WARNING: At least one expression was used more than once in the target code. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1181'" //UPGRADE_TODO: Constructor 'java.io.FileReader.FileReader' was converted to 'System.IO.StreamReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" trainReader = new System.IO.StreamReader(new System.IO.StreamReader(trainFileName, System.Text.Encoding.Default).BaseStream, new System.IO.StreamReader(trainFileName, System.Text.Encoding.Default).CurrentEncoding); // Incremental testing train = new Instances(trainReader, 1); if (classIndex != - 1) { train.ClassIndex = classIndex - 1; } else { train.ClassIndex = train.numAttributes() - 1; } testTimeStart = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; while (train.readInstance(trainReader)) { trainingEvaluation.evaluateModelOnce((Classifier) classifier, train.instance(0)); train.delete(0); } testTimeElapsed = (System.DateTime.Now.Ticks - 621355968000000000) / 10000 - testTimeStart; trainReader.Close(); } else { testTimeStart = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; trainingEvaluation.evaluateModel(classifier, train); testTimeElapsed = (System.DateTime.Now.Ticks - 621355968000000000) / 10000 - testTimeStart; } // Print the results of the training evaluation if (printMargins) { return trainingEvaluation.toCumulativeMarginDistributionString(); } else { text.Append("\nTime taken to build model: " + Utils.doubleToString(trainTimeElapsed / 1000.0, 2) + " seconds"); text.Append("\nTime taken to test model on training data: " + Utils.doubleToString(testTimeElapsed / 1000.0, 2) + " seconds"); text.Append(trainingEvaluation.toSummaryString("\n\n=== Error on training" + " data ===\n", printComplexityStatistics)); if (template.classAttribute().Nominal) { if (classStatistics) { text.Append("\n\n" + trainingEvaluation.toClassDetailsString()); } text.Append("\n\n" + trainingEvaluation.toMatrixString()); } } } // Compute proper error estimates if (testFileName.Length != 0) { // Testing is on the supplied test data while (test.readInstance(testReader)) { testingEvaluation.evaluateModelOnce((Classifier) classifier, test.instance(0)); test.delete(0); } testReader.Close(); text.Append("\n\n" + testingEvaluation.toSummaryString("=== Error on test data ===\n", printComplexityStatistics)); } else if (trainFileName.Length != 0) { // Testing is via cross-validation on training data //UPGRADE_TODO: The differences in the expected value of parameters for constructor 'java.util.Random.Random' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" System.Random random = new System.Random((System.Int32) seed); // use untrained (!) classifier for cross-validation classifier = Classifier.makeCopy(classifierBackup); testingEvaluation.crossValidateModel(classifier, train, folds, random); if (template.classAttribute().Numeric) { text.Append("\n\n\n" + testingEvaluation.toSummaryString("=== Cross-validation ===\n", printComplexityStatistics)); } else { text.Append("\n\n\n" + testingEvaluation.toSummaryString("=== Stratified " + "cross-validation ===\n", printComplexityStatistics)); } } if (template.classAttribute().Nominal) { if (classStatistics) { text.Append("\n\n" + testingEvaluation.toClassDetailsString()); } text.Append("\n\n" + testingEvaluation.toMatrixString()); } return text.ToString(); }
public void EnsureLevelDefinition(System.IO.Stream stream) { System.IO.BinaryWriter bw = new System.IO.BinaryWriter(stream); /* File Version Stamp */ bw.Write(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()); /* Level Attributes */ bw.Write(levelName); /* Object Type Palette */ List<FileOps.LevelObjectTypeDefinition> types = new List<FileOps.LevelObjectTypeDefinition>(); foreach (KeyValuePair<String, LevelObjectType> kv in objectPalette) { FileOps.LevelObjectTypeDefinition t = new FileOps.LevelObjectTypeDefinition(); t.TypeId = kv.Value.TypeID; String typeFileName = kv.Value.FileName; if (String.IsNullOrEmpty(typeFileName)) { throw new UnsavedObjectTypeException(); } int idx = typeFileName.LastIndexOf('\\')+1; typeFileName = typeFileName.Substring(idx, typeFileName.Length - idx); t.FileName = typeFileName; types.Add(t); } FileOps.WriteObjectPalette(bw, types); /* Level Terrain */ bw.Write(terrainObjects.Count); foreach (KeyValuePair<String, LevelTerrain> kv in terrainObjects) { LevelTerrain terrain = kv.Value; bw.Write(terrain.Name); FileOps.WriteVec3(terrain.Position, bw); FileOps.WriteVec3(terrain.Scaling.Scales, bw); bw.Write(terrain.HeightMapDimensions.X); bw.Write(terrain.HeightMapDimensions.Y); for (int j = 0; j < terrain.HeightMapDimensions.Y; j++) { for (int i = 0; i < terrain.HeightMapDimensions.X; i++) { int index = j * terrain.HeightMapDimensions.X + i; bw.Write(terrain.HeightMap[index]); } } } /* Level Object Instances */ bw.Write(worldObjects.Count); foreach (KeyValuePair<String, LevelObject> kv in worldObjects) { LevelObject lo = kv.Value; bw.Write(lo.Index); bw.Write(lo.Name); bw.Write(lo.TypeId.ToString()); /* Level Object Transforms */ FileOps.WriteVec3(lo.Rotation, bw); FileOps.WriteVec3(lo.Scale, bw); FileOps.WriteVec3(lo.Position, bw); } bw.Flush(); bw.Close(); }
/// <summary>this method writes the GeneratedClass object to disk</summary> /// <param name="gc">the object to be written to disk /// </param> /// <param name="packageName">representing the packageName /// </param> /// <param name="fileName">representing the file name /// </param> /// <exception cref="IOException">if unable to create file /// </exception> public virtual void storeFile(GeneratedClass gc, System.String packageName, System.String fileName) { //format package name packageName = packageName.Replace('.', '/'); // set the file path fileName = Regex.Replace(fileName, " ", "") + ".java"; System.String filePath = basePath + "/" + packageName + "/" + fileName; System.IO.FileInfo f = new System.IO.FileInfo(filePath); System.Text.StringBuilder dir = new System.Text.StringBuilder(); //check if file exist // TODO: Reactivate this once everything works! //if(f.exists()) // throw new IOException("File already exists"); //create subfolders int i = 0; while (i < filePath.Length) { if (filePath[i] != '/') { dir.Append(filePath[i]); } else { dir.Append(filePath[i]); System.IO.FileInfo d = new System.IO.FileInfo(dir.ToString()); System.IO.Directory.CreateDirectory(d.FullName); } ++i; } System.IO.FileStream fstream = new System.IO.FileStream(f.FullName, System.IO.FileMode.Create); /* open file stream */ System.IO.BinaryWriter ostream = new System.IO.BinaryWriter(fstream); /* open object stream */ ostream.Write(gc.ToString()); /* clean-up */ ostream.Flush(); fstream.Close(); }
// // GET: /Profile/Details/5 public ActionResult Details(string id) { Profile profile = _provider.GetProfileByID(Guid.Parse(id)); ProfileViewModel model = new ProfileViewModel(profile); if (profile.Photo != null && profile.Photo.Length > 0) { // Write photo to disk and set relative path to filename in a property within ProfileViewModel string path = Server.MapPath("~/Content/images"); string filename = profile.ID.ToString(); string extension = profile.PhotoMimeType; string fullFilename = string.Format(@"{0}\{1}.{2}", path, filename, "jpg"); System.IO.FileStream fs = null; System.IO.BinaryWriter bw = null; try { fs = new System.IO.FileStream(fullFilename, System.IO.FileMode.Create); bw = new System.IO.BinaryWriter(fs); bw.Write(profile.Photo); bw.Flush(); } catch { } finally { if (bw != null) bw.Close(); if (fs != null) fs.Close(); } model.PhotoUrl = "/Babylon.Site/Content/images/" + filename + ".jpg"; } else { model.PhotoUrl = "/Babylon.Site/Content/images/blank_profile.jpg"; } return View(model); }
/// <summary> /// Descriptografa um arquivo em outro arquivo. /// </summary> /// <param name="p_inputfilename">Nome do arquivo de entrada.</param> /// <param name="p_outputfilename">Nome do arquivo de saída.</param> public void DecryptFile(string p_inputfilename, string p_outputfilename) { System.IO.FileStream v_inputfile, v_outputfile; System.IO.StreamReader v_reader; System.IO.BinaryWriter v_writer; int v_bytestoread; string v_chunk; byte[] v_decryptedchunk; try { v_inputfile = new System.IO.FileStream(p_inputfilename, System.IO.FileMode.Open, System.IO.FileAccess.Read); v_outputfile = new System.IO.FileStream(p_outputfilename, System.IO.FileMode.Create, System.IO.FileAccess.Write); v_reader = new System.IO.StreamReader(v_inputfile); v_writer = new System.IO.BinaryWriter(v_outputfile); v_bytestoread = (int) v_inputfile.Length; while (! v_reader.EndOfStream) { v_chunk = v_reader.ReadLine(); // descriptografando v_decryptedchunk = this.DecryptToBytes(v_chunk); // escrevendo porcao descriptografada v_writer.Write(v_decryptedchunk); } v_reader.Close(); v_writer.Flush(); v_writer.Close(); } catch (System.IO.IOException e) { throw new Spartacus.Utils.Exception(e); } catch (System.Exception e) { throw new Spartacus.Utils.Exception(e); } }
/// <summary>Creates the ANT build.xml file</summary> /// <param name="baseDir">the directory where the ANT build.xml file will be saved /// </param> /// <param name="name">the name of the project /// </param> public virtual void createAnt(System.String baseDir, System.String name) { this.baseDir = baseDir; this.name = name; System.IO.FileStream fstream; try { System.IO.FileInfo f = new System.IO.FileInfo(baseDir + System.IO.Path.DirectorySeparatorChar.ToString() + "build.xml"); fstream = new System.IO.FileStream(f.FullName, System.IO.FileMode.Create); /* open file stream */ } catch (System.IO.FileNotFoundException e) { System.Console.Out.WriteLine("Filenotfoundexception: " + e.ToString()); return ; } System.IO.BinaryWriter ostream = null; try { ostream = new System.IO.BinaryWriter(fstream); /* open object stream */ ostream.Write(this.antString()); } catch (System.IO.IOException e) { System.Console.Out.WriteLine("IOexception:\n" + e.ToString() + "\n"); } finally { try { /* clean-up */ ostream.Flush(); fstream.Close(); } catch (System.Exception e1) { SupportClass.WriteStackTrace(e1, Console.Error); } } }
// ***** Start pairing (play sound)***** private void button1_Click(object sender, EventArgs e) { if (clsHvcw.GenerateSound(textSSID.Text, textPassword.Text, txtToken) == true) { // Read sound file byte[] buf = System.IO.File.ReadAllBytes(clsHvcw.SoundFile); // Stop when sound playing if (player != null) StopSound(); player = new System.Media.SoundPlayer(); // Wav header definition WAVHDR wavHdr = new WAVHDR(); uint fs = 8000; wavHdr.formatid = 0x0001; // PCM uncompressed wavHdr.channel = 1; // ch=1 mono wavHdr.fs = fs; // Frequency wavHdr.bytespersec = fs * 2; // 16bit wavHdr.blocksize = 2; // 16bit mono so block size (byte/sample x # of channels) is 2 wavHdr.bitspersample = 16; // bit/sample wavHdr.size = (uint)buf.Length; // Wave data byte number wavHdr.fileSize = wavHdr.size + (uint)Marshal.SizeOf(wavHdr); // Total byte number // Play sound through memory stream System.IO.MemoryStream memoryStream = new System.IO.MemoryStream((int)wavHdr.fileSize); System.IO.BinaryWriter bWriter = new System.IO.BinaryWriter(memoryStream); // Write Wav header foreach (byte b in wavHdr.getByteArray()) { bWriter.Write(b); } // Write PCM data foreach (byte data in buf) { bWriter.Write(data); } bWriter.Flush(); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); player.Stream = memoryStream; // Async play player.Play(); // Wait until sound playing is over with following: // player.PlaySync(); } else { MessageBox.Show("Pairing sound creation failed", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private string ComputeHash(XDocument doc, DateTime timestamp) { using (var stream = new System.IO.MemoryStream()) using (var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider()) using (var w = new System.IO.BinaryWriter(stream)) { w.Write(timestamp.ToBinary()); w.Flush(); doc.Save(stream, SaveOptions.OmitDuplicateNamespaces); stream.Flush(); var hash = md5.ComputeHash(stream.GetBuffer()); string hex = BitConverter.ToString(hash); return hex.Replace("-", string.Empty); } }
//save private void button1_Click(object sender, EventArgs e) { if (textBox1.Text.Length < 5) { MessageBox.Show("too short nbame"); return; } SaveFileDialog sfd = new SaveFileDialog(); if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK) return; ResourceCollectorXNA.Engine.EngineLevel level = GameEngine.Instance.gameLevel; level.FillContent(); System.IO.BinaryWriter bw = new System.IO.BinaryWriter(new System.IO.FileStream(sfd.FileName, System.IO.FileMode.OpenOrCreate)); level.levelContent.savebody(bw); bw.Flush(); bw.Close(); bw.Dispose(); }
public void SaveRegistrationInfo(string filename) { string data = RegistrationInfoToString(); System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create); System.IO.BinaryWriter br = new System.IO.BinaryWriter(fs); br.Write(data); br.Flush(); br.Close(); }
public static string formatHierarchyId(object data) { SqlHierarchyId hier = (SqlHierarchyId)data; byte[] ba; using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(ms)) { hier.Write(w); w.Flush(); ba = ms.ToArray(); } return "0x" + BitConverter.ToString(ba).Replace("-", ""); }
/// <summary> /// Emits a return statement and finalizes the generated code. Do not emit any more /// instructions after calling this method. /// </summary> public override unsafe void Complete() { // Check there aren't any outstanding exception blocks. if (this.activeExceptionRegions != null && this.activeExceptionRegions.Count > 0) throw new InvalidOperationException("The current method contains unclosed exception blocks."); Return(); FixLabels(); fixed (byte* bytes = this.bytes) this.dynamicILInfo.SetCode(bytes, this.offset, this.maxStackSize); this.dynamicILInfo.SetLocalSignature(this.LocalSignature); if (this.exceptionRegions != null && this.exceptionRegions.Count > 0) { // Count the number of exception clauses. int clauseCount = 0; foreach (var exceptionRegion in this.exceptionRegions) clauseCount += exceptionRegion.Clauses.Count; var exceptionBytes = new byte[4 + 24 * clauseCount]; var writer = new System.IO.BinaryWriter(new System.IO.MemoryStream(exceptionBytes)); // 4-byte header, see Partition II, section 25.4.5. writer.Write((byte)0x41); // Flags: CorILMethod_Sect_EHTable | CorILMethod_Sect_FatFormat writer.Write(exceptionBytes.Length); // 3-byte data size. writer.Flush(); writer.BaseStream.Seek(4, System.IO.SeekOrigin.Begin); // Exception clauses, see Partition II, section 25.4.6. foreach (var exceptionRegion in this.exceptionRegions) { foreach (var clause in exceptionRegion.Clauses) { switch (clause.Type) { case ExceptionClauseType.Catch: writer.Write(0); // Flags break; case ExceptionClauseType.Filter: writer.Write(1); // Flags break; case ExceptionClauseType.Finally: writer.Write(2); // Flags break; case ExceptionClauseType.Fault: writer.Write(4); // Flags break; } writer.Write(exceptionRegion.Start); // TryOffset writer.Write(clause.ILStart - exceptionRegion.Start); // TryLength writer.Write(clause.ILStart); // HandlerOffset writer.Write(clause.ILLength); // HandlerLength if (clause.Type == ExceptionClauseType.Catch) writer.Write(clause.CatchToken); // ClassToken else if (clause.Type == ExceptionClauseType.Filter) writer.Write(clause.FilterHandlerStart); // FilterOffset else writer.Write(0); } } writer.Flush(); this.dynamicILInfo.SetExceptions(exceptionBytes); } }
private static byte[] toByteArray(System.Object o) { if (o == null) return null; /*need to synchronize use of the shared baos */ System.IO.MemoryStream baos = new System.IO.MemoryStream(); System.IO.BinaryWriter oos = new System.IO.BinaryWriter(baos); SupportClass.Serialize(oos, o); oos.Flush(); return baos.ToArray(); }
/* input image with width = height is suggested to get the best result */ /* png support in icon was introduced in Windows Vista */ public static bool Convert(System.IO.Stream input_stream, System.IO.Stream output_stream, int size, bool keep_aspect_ratio = false) { System.Drawing.Bitmap input_bit = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromStream(input_stream); if (input_bit != null) { int width, height; if (keep_aspect_ratio) { width = size; height = input_bit.Height / input_bit.Width * size; } else { width = height = size; } System.Drawing.Bitmap new_bit = new System.Drawing.Bitmap(input_bit, new System.Drawing.Size(width, height)); if (new_bit != null) { // save the resized png into a memory stream for future use System.IO.MemoryStream mem_data = new System.IO.MemoryStream(); new_bit.Save(mem_data, System.Drawing.Imaging.ImageFormat.Png); System.IO.BinaryWriter icon_writer = new System.IO.BinaryWriter(output_stream); if (output_stream != null && icon_writer != null) { // 0-1 reserved, 0 icon_writer.Write((byte)0); icon_writer.Write((byte)0); // 2-3 image type, 1 = icon, 2 = cursor icon_writer.Write((short)1); // 4-5 number of images icon_writer.Write((short)1); // image entry 1 // 0 image width icon_writer.Write((byte)width); // 1 image height icon_writer.Write((byte)height); // 2 number of colors icon_writer.Write((byte)0); // 3 reserved icon_writer.Write((byte)0); // 4-5 color planes icon_writer.Write((short)0); // 6-7 bits per pixel icon_writer.Write((short)32); // 8-11 size of image data icon_writer.Write((int)mem_data.Length); // 12-15 offset of image data icon_writer.Write((int)(6 + 16)); // write image data // png data must contain the whole png data file icon_writer.Write(mem_data.ToArray()); icon_writer.Flush(); return true; } } return false; } return false; }