コード例 #1
0
ファイル: Client.cs プロジェクト: nstcl/tcp-tftp
        public int PutFile(string filename)
        {
            byte[] txBuf = new byte[516];
            int    txCount;
            string s = System.IO.File.ReadAllText(filename);

            System.IO.StringReader sr = new System.IO.StringReader(s);
            short         blockNumber;
            ASCIIEncoding ae = new ASCIIEncoding();

            sendTftpPacket(Client.OP_CODE.WRQ, filename, null, -1);//send WRQ
            char[] chunk      = new char[512];
            int    dataLength = sr.ReadBlock(chunk, 0, 512);

            do
            {
                txCount = recvTftpPacket(ref txBuf);
                OP_CODE op = (OP_CODE)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(txBuf, 0));
                System.Diagnostics.Debug.Assert(op == OP_CODE.ACK);
                blockNumber = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(txBuf, 2));
                //s += new string(ae.GetChars(rxBuf, sizeof(short) * 2, rxCount - 4 >= 4 ? rxCount - 4 : 0));
                byte[] data = new byte[dataLength];
                int    chrCount, byteCount;
                bool   completed;
                ae.GetEncoder().Convert(chunk, 0, dataLength, data, 0, data.Length, true, out chrCount, out byteCount, out completed);

                sendTftpPacket(Client.OP_CODE.DATA, string.Empty, data, ++blockNumber);
            } while ((dataLength = sr.ReadBlock(chunk, 0, 512)) == 512);
            //sendTftpPacket(Client.OP_CODE.ACK, string.Empty, null, blockNumber);//final ACK
            return(txCount);
        }
コード例 #2
0
ファイル: IO.cs プロジェクト: fenge21/Csharp
        public static double[][][] LoadAllText(string textPath)
        {
            double[][][] dio = new double[2][][];
            string input = File.ReadAllText(textPath);
            StringReader reader = new StringReader(input);
            char[] buffer = new char[(32 + 1) * 32];
            int count = 0;
            List<double[]> ldi = new List<double[]>();
            List<double[]> ldo = new List<double[]>();
            while (true)
            {
                int read = reader.ReadBlock(buffer, 0, buffer.Length);
                string label = reader.ReadLine();

                if (read < buffer.Length || label == null) break;

                double[] d = LoadText(new String(buffer));
                double[] o = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
                o[int.Parse(label)] = 1;

                ldi.Add(d);
                ldo.Add(o);
                count++;
            }

            dio[0] = ldi.ToArray();
            dio[1] = ldo.ToArray();
            return dio;
        }
コード例 #3
0
 /// <summary>
 /// Formats the message string to appear exactly within
 /// the defined number of characters in the ApplicationLog 
 /// class' "fileWidth" parameter. 
 /// </summary>
 /// <param name="message"></param>
 /// <returns></returns>
 private static string GenerateFormatedString(string message)
 {
     string formatedText = "";
     if (message.Length < fileWidth)
     {
         formatedText = message.PadRight(fileWidth);
     }
     else
     {
         int numCharsRead = -1;
         char[] buffer = new char[fileWidth];
         using (StringReader reader = new StringReader(message))
         {
             StringBuilder builder = new StringBuilder();
             while (reader.Peek() != (-1))
             {
                 numCharsRead = reader.ReadBlock(buffer, 0, buffer.Length);
                 if (numCharsRead > 0)
                 {
                     builder.Append(buffer, 0, numCharsRead);
                     builder.Append(Environment.NewLine);
                 }
             }
             formatedText = builder.ToString();
         }
     }
     return formatedText;
 }
コード例 #4
0
ファイル: Optdigits.cs プロジェクト: CanerPatir/framework
        public void Load()
        {
            string input = Properties.Resources.optdigits_tra;

            // Load optdigits dataset into the DataGridView
            StringReader reader = new StringReader(input);

            Training = new ObservableCollection<Sample>();
            Testing = new ObservableCollection<Sample>();

            char[] buffer = new char[(32 + 1) * 32]; // 32 chars + \n
            int count = 0;

            while (true)
            {
                int read = reader.ReadBlock(buffer, 0, buffer.Length);
                string label = reader.ReadLine();

                if (read < buffer.Length || label == null)
                    break;


                ObservableCollection<Sample> set =
                    (count < 1000) ? Training : Testing;

                set.Add(extractSample(buffer, label));

                count++;
            }

            if (IsNormalized)
            {
                double[][] training;
                Training.GetInstances(out training);

                mean = training.Mean();
                dev = training.StandardDeviation();

                double[][] testing;
                Testing.GetInstances(out testing);

                Normalize(training);
                Normalize(testing);
            }
        }
コード例 #5
0
ファイル: Code.cs プロジェクト: xsharper/xsharper
        /// Generate source code of the snippet
        public string GenerateSourceCode(ScriptContext context,bool embedSourceCode, bool isPublic)
        {
            StringBuilder sb=new StringBuilder();
            sb.Append(
            @"        {public}class {class} : {base}
            {
            public override object Execute()
                ");
            sb  .Replace("{class}", GetClassName())
                .Replace("{public}", isPublic?"public ":"")
                .Replace("{ctxclass}", context.Compiler.GetTypeName(context.GetType()))
                .Replace("{base}", context.Compiler.GetTypeName(typeof(ExecutableScriptBase)));

            sb.AppendLine();

            string text = GetTransformedValueStr() ?? string.Empty;

            sb.AppendLine("\t\t\t// ---- User code ----- ");
            var t = text.Trim();
            if (!t.StartsWith("{", StringComparison.Ordinal))
                sb.AppendLine("{");
            sb.Append(t);
            sb.AppendLine();
            sb.AppendLine("\t\t\t// ---- End of user code ----- ");
            if (!t.StartsWith("{", StringComparison.Ordinal))
                sb.AppendLine("\t\t\t;return null;}");

            if (Methods!=null)
                foreach (IScriptAction c in Methods.Items)
                {
                    sb.AppendLine("");
                    string par = "",par2="null";
                    if (c is Sub)
                    {
                        par = "params object[] par";
                        par2 = "par";
                    }
                    sb.AppendLine("\tprivate object  " + c.Id + "(" + par + ") { return XS.ReturnValue.Unwrap(((" + GetType().FullName + ")c.CallStack.Peek().ScriptAction).ExecuteMember(XS.CallIsolation.Default,\"" + c.Id + "\", " + par2 + "));}");
                    sb.AppendLine("\tprivate object  " + c.Id + "_inline(" + par + ") { return ((" + GetType().FullName + ")c.CallStack.Peek().ScriptAction).ExecuteMember(XS.CallIsolation.None,\"" + c.Id + "\", " + par2 + ");}");
                    sb.AppendLine("\tprivate object  " + c.Id + "<T>(" + par + ") { return XS.Utils.To<T>(XS.ReturnValue.Unwrap(((" + GetType().FullName + ")c.CallStack.Peek().ScriptAction).ExecuteMember(XS.CallIsolation.None,\"" + c.Id + "\", " + par2 + ")));}");
                }
            if (embedSourceCode)
            {
                sb.AppendLine("\t\t\tpublic override string GetSourceCode() {");
                sb.Append("\t\t\t\treturn ");

                sb.Append("@\"");
                StringReader reader = new StringReader(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text)));
                char[] buf = new char[80];
                int n;
                while ((n = reader.ReadBlock(buf, 0, buf.Length)) != 0)
                {
                    sb.Append(buf, 0, n);
                    if (n == buf.Length)
                    {
                        sb.AppendLine();
                        sb.Append("\t\t\t\t");
                    }
                }
                sb.Append("\"");
                sb.AppendLine("\t\t\t;}");
            }
            sb.AppendLine("\t\t}");
            return Utils.TransformStr(sb.ToString(), TransformRules.NewLineToCRLF);
        }
コード例 #6
0
ファイル: MainForm.cs プロジェクト: accord-net/framework
        private void btnLoad_Click(object sender, EventArgs e)
        {
            lbStatus.Text = "Loading data. This may take a while...";
            Application.DoEvents();

            // Load optdigits dataset into the DataGridView
            StringReader reader = new StringReader(Resources.optdigits_tra);

            int trainingStart = 0;
            int trainingCount = 500;

            int testingStart = 1000;
            int testingCount = 500;

            dgvAnalysisSource.Rows.Clear();
            dgvAnalysisTesting.Rows.Clear();

            int c = 0;
            while (true)
            {
                char[] buffer = new char[(32 + 1) * 32]; // 32 chars + \n
                int read = reader.ReadBlock(buffer, 0, buffer.Length);
                string label = reader.ReadLine();


                if (read < buffer.Length || label == null) break;

                if (c > trainingStart && c <= trainingStart + trainingCount)
                {
                    Bitmap bitmap = Extract(new String(buffer));
                    double[] features = Extract(bitmap);
                    int clabel = Int32.Parse(label);
                    dgvAnalysisSource.Rows.Add(bitmap, clabel, features);
                }
                else if (c > testingStart && c <= testingStart + testingCount)
                {
                    Bitmap bitmap = Extract(new String(buffer));
                    double[] features = Extract(bitmap);
                    int clabel = Int32.Parse(label);
                    dgvAnalysisTesting.Rows.Add(bitmap, clabel, null, features);
                }

                c++;
            }

            lbStatus.Text = String.Format(
                "Dataset loaded. Click Run analysis to start the analysis.",
                trainingCount, testingCount);

            btnSampleRunAnalysis.Enabled = true;
        }
コード例 #7
0
        public static void MemoryBufferCopy(string source, string destin)
        {

            var stringBuilder = new StringBuilder();

            string content;

            using (var textReader = (TextReader)new StreamReader(new FileStream(source, FileMode.Open))) // TODO: use StreamReader here
            {
                // TODO: read entire file
                content = textReader.ReadToEnd();
            }

            using (var sourceReader = new StringReader(content)) // TODO: Use StringReader here with content
            using (var sourceWriter = new StringWriter(stringBuilder)) // TODO: Use StringWriter here with stringBuilder
            {
                string line = null;

                do
                {
                    line = sourceReader.ReadLine(); // TODO: read line
                    if (line != null)
                    {
                        sourceWriter.WriteLine(line); // TODO: write line
                    }

                } while (line != null);
            }

            Console.WriteLine("MemoryBufferCopy(): chars in StringBuilder {0}", stringBuilder.Length);

            const int blockSize = 1024;

            using (var stringReader = new StringReader(stringBuilder.ToString())) // TODO: Use StringReader to read from stringBuilder.
            using (var memoryStream = new MemoryStream(blockSize))
            using (var streamWriter = new StreamWriter(memoryStream)) // TODO: Compose StreamWriter with memory stream.
            using (var destinStream = new FileStream(destin, FileMode.Append)) // TODO: Use file stream.
            {
                char[] buffer = new char[blockSize];
                int bytesRead;

                do
                {
                    bytesRead = stringReader.ReadBlock(buffer,0, blockSize); // TODO: Read block from stringReader to buffer.
                    streamWriter.WriteLine(buffer); // TODO: Write buffer to streamWriter.

                    //TODO: After implementing everythin check the content of NewTextFile. What's wrong with it, and how this may be fixed?

                     // TODO: write memoryStream.GetBuffer() content to destination stream.
                    destinStream.Write(memoryStream.GetBuffer(), 0, blockSize);
                }
                while (bytesRead == blockSize);
            }
        }
コード例 #8
0
ファイル: MainForm.cs プロジェクト: nguonly/KNNHandwriting
        private void btnLoad_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
              Application.DoEvents();

              // Load optdigits dataset into the DataGridView
              var trainingReader = new StringReader(Properties.Resources.optdigits_tra);
              var testingReader = new StringReader(Properties.Resources.optdigits_test);

              var trainingCount = 500;

              var testingCount = 500;

              dgvAnalysisSource.Rows.Clear();
              dgvAnalysisTesting.Rows.Clear();

              var trainingSet = new List<DigitData>();

              //Load training data
              for (var i = 0; i < trainingCount;i++ )
              {
            char[] buffer = new char[(32 + 2) * 32];
            int read = trainingReader.ReadBlock(buffer, 0, buffer.Length);
            string label = trainingReader.ReadLine();

            if (read < buffer.Length || label == null) break;

            var bitmap = _dataExtractionService.Extract(new String(buffer));
            var features = _dataExtractionService.Extract(bitmap);
            var clabel = label;
            dgvAnalysisSource.Rows.Add(bitmap, clabel, features);

            if (features != null)
              trainingSet.Add(new DigitData { Label = label, Feature = features });
              }

              //Load testing data
              for (var i = 0; i < testingCount;i++ )
              {
            char[] buffer = new char[(32 + 2) * 32];
            int read = testingReader.ReadBlock(buffer, 0, buffer.Length);
            string label = testingReader.ReadLine();

            if (read < buffer.Length || label == null) break;

            var bitmap = _dataExtractionService.Extract(new String(buffer));
            var features = _dataExtractionService.Extract(bitmap);
            var clabel = label;
            dgvAnalysisTesting.Rows.Add(bitmap, clabel, null, features);
              }

              //Assign training set to KNN Service
              _kNNService.SetTrainingSet(trainingSet);
              Cursor = Cursors.Default;
        }
コード例 #9
0
ファイル: Application.cs プロジェクト: hach-que/Pivot.Update
        /// <summary>
        /// Updates the application.
        /// </summary>
        public void Update(Action<UpdateStatus, object> callback)
        {
            callback(UpdateStatus.Starting, null);
            diff_match_patch dmf = new diff_match_patch();
            WebClient client = new WebClient();
            callback(UpdateStatus.RetrievingFileList, null);
            string state = client.DownloadString(this.m_UpdateUri + "/initial");
            string[] lines = state.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
            callback(UpdateStatus.RetrievedFileList, lines.Length);
            int opers = 0;
            foreach (string line in lines)
            {
                Hash hash = Hash.FromString(line.Split(new char[] { ' ' }, 2)[0]);
                string file = line.Split(new char[] { ' ' }, 2)[1];
                callback(UpdateStatus.DeterminingOperation, file);

                // See if file already exists.
                if (File.Exists(Path.Combine(this.m_LocalPath, file)) || hash == Hash.Empty)
                {
                    if (hash == Hash.Empty)
                    {
                        // Delete the local file if it exists.
                        if (File.Exists(Path.Combine(this.m_LocalPath, file)))
                        {
                            callback(UpdateStatus.DeletionStart, file);
                            File.Delete(Path.Combine(this.m_LocalPath, file));
                            callback(UpdateStatus.DeletionFinish, file);
                            opers++;
                        }
                    }
                    else
                    {
                        // Compare hashes, ignore if same.
                        Hash current = Hash.FromFile(Path.Combine(this.m_LocalPath, file));
                        if (current == hash)
                            continue;

                        // Download patch.
                        string patchstream;
                        try
                        {
                            patchstream = client.DownloadString(this.m_UpdateUri + "/patch/" + current + "/" + hash + "/" + file);
                            callback(UpdateStatus.PatchStart, file);
                            int a = 1;
                            using (StringReader reader = new StringReader(patchstream))
                            {
                                while (true)
                                {
                                    string header = reader.ReadLine();
                                    if (header == "--- END OF PATCHES ---")
                                        break;
                                    else if (header.StartsWith("--- NEXT PATCH ("))
                                    {
                                        int count = Convert.ToInt32(header.Substring("--- NEXT PATCH (".Length, header.Length - "--- NEXT PATCH () ---".Length));
                                        char[] data = new char[count];
                                        reader.ReadBlock(data, 0, count);
                                        List<Patch> patches = dmf.patch_fromText(new string(data));
                                        string newText;
                                        using (StreamReader stream = new StreamReader(Path.Combine(this.m_LocalPath, file)))
                                        {
                                            newText = (string)dmf.patch_apply(patches, stream.ReadToEnd())[0];
                                        }
                                        using (StreamWriter stream = new StreamWriter(Path.Combine(this.m_LocalPath, file)))
                                        {
                                            stream.Write(newText);
                                        }
                                        callback(UpdateStatus.PatchApplied, a);
                                        a++;
                                        // Read the empty terminator line.
                                        reader.ReadLine();
                                    }
                                    else
                                        throw new DataMisalignedException();
                                }
                            }
                            callback(UpdateStatus.PatchFinish, file);
                            opers++;
                        }
                        catch (WebException)
                        {
                            // There's no patch list for this file, redownload.
                            string[] coms = file.Split('/');
                            DirectoryInfo di = new DirectoryInfo(this.m_LocalPath);
                            for (int i = 0; i < coms.Length - 1; i++)
                            {
                                DirectoryInfo[] dis = di.GetDirectories(coms[i]);
                                if (dis.Length == 0)
                                    di = di.CreateSubdirectory(coms[i]);
                                else
                                    di = dis[0];
                            }
                            callback(UpdateStatus.DownloadFreshStart, file);
                            client.DownloadFile(this.m_UpdateUri + "/file/" + file, Path.Combine(this.m_LocalPath, file));
                            callback(UpdateStatus.DownloadFreshFinish, file);
                            opers++;
                        }
                    }
                }
                else
                {
                    // File does not exist, download fresh.
                    string[] coms = file.Split('/');
                    DirectoryInfo di = new DirectoryInfo(this.m_LocalPath);
                    for (int i = 0; i < coms.Length - 1; i++)
                    {
                        DirectoryInfo[] dis = di.GetDirectories(coms[i]);
                        if (dis.Length == 0)
                            di = di.CreateSubdirectory(coms[i]);
                        else
                            di = dis[0];
                    }
                    callback(UpdateStatus.DownloadNewStart, file);
                    client.DownloadFile(this.m_UpdateUri + "/file/" + file, Path.Combine(this.m_LocalPath, file));
                    callback(UpdateStatus.DownloadNewFinish, file);
                    opers++;
                }
            }
            callback(UpdateStatus.Complete, opers);

            return;
        }
コード例 #10
0
ファイル: Client.cs プロジェクト: nstcl/tcp-tftp
        public int PutFile(string filename)
        {
            byte[] txBuf = new byte[516];
            int txCount;
            string s = System.IO.File.ReadAllText(filename);
            System.IO.StringReader sr = new System.IO.StringReader(s);
            short blockNumber;
            ASCIIEncoding ae = new ASCIIEncoding();
            sendTftpPacket(Client.OP_CODE.WRQ, filename, null, -1);//send WRQ
            char[] chunk = new char[512];
            int dataLength = sr.ReadBlock(chunk,0,512);
            do
            {
                txCount = recvTftpPacket(ref txBuf);
                OP_CODE op = (OP_CODE)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(txBuf, 0));
                System.Diagnostics.Debug.Assert(op==OP_CODE.ACK);
                blockNumber = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(txBuf, 2));
                //s += new string(ae.GetChars(rxBuf, sizeof(short) * 2, rxCount - 4 >= 4 ? rxCount - 4 : 0));
                byte[] data = new byte[dataLength];
                int chrCount,byteCount;
                bool completed;
                ae.GetEncoder().Convert(chunk,0,dataLength,data,0,data.Length,true,out chrCount,out byteCount,out completed);

                sendTftpPacket(Client.OP_CODE.DATA, string.Empty, data, ++blockNumber);
            } while ((dataLength=sr.ReadBlock(chunk, 0, 512)) == 512);
            //sendTftpPacket(Client.OP_CODE.ACK, string.Empty, null, blockNumber);//final ACK
            return txCount;
        }
コード例 #11
0
 public static string Subsection(string original, int length)
 {
     if (original == null)
     {
         throw new ArgumentNullException("original");
     }
     if (original.Length < length)
     {
         return original;
     }
     StringReader reader = null;
     StringBuilder builder = null;
     try
     {
         builder = new StringBuilder();
         reader = new StringReader(original);
         char[] buffer = new char[length];
         while (true)
         {
             int num = reader.ReadBlock(buffer, 0, buffer.Length);
             if (num == 0)
             {
                 goto Label_0070;
             }
             builder.Append(new string(buffer, 0, num));
             builder.Append("\r\n");
         }
     }
     finally
     {
         if (reader != null)
         {
             try
             {
                 reader.Close();
             }
             catch
             {
             }
             reader = null;
         }
     }
     Label_0070:
     return builder.ToString();
 }
コード例 #12
0
ファイル: Utils.cs プロジェクト: huamouse/Taoqi
		public static string CalDAV_FoldLines(string s)
		{
			StringBuilder sb = new StringBuilder();
			using ( TextReader rdr = new StringReader(s) )
			{
				char[] arr = new char[75];
				int n = 0;
				while ( (n = rdr.ReadBlock(arr, 0, 75)) > 0 )
				{
					if ( sb.Length > 0 )
						sb.Append("\r\n ");
					sb.Append(arr, 0, n);
				}
			}
			return sb.ToString();
		}