コード例 #1
0
        public void Connect()
        {
            var ip   = ConfigurationManager.AppSettings["SimIP"];
            int port = Int32.Parse(ConfigurationManager.AppSettings["SimTcpPort"].ToString());

            try
            {
                client = new TcpClient();
                client.ReceiveTimeout = 10000;
                client.Connect(new IPEndPoint(IPAddress.Parse(ip), port));

                networkStream = client.GetStream();

                writer           = new System.IO.StreamWriter(networkStream);
                writer.AutoFlush = true;
                reader           = new System.IO.StreamReader(networkStream);
                IsConnected      = true;
                writer.WriteLine("data\n");
                reader.DiscardBufferedData();
                Debug.WriteLine("");
            }
            catch (Exception e)
            {
                Console.WriteLine("Error..... " + e.StackTrace);
            }
        }
コード例 #2
0
ファイル: currentFile.cs プロジェクト: sammikulski/ATM
        } // end Sub

        // Rewind the input file
        public void rewindFile()
        {
            recordReadCount = 0;
            currentFileSR   = new System.IO.StreamReader(currentFilePath);
            currentFileSR.DiscardBufferedData();
            currentFileSR.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
        } // end rewindFile
コード例 #3
0
        static void Main(string[] args)
        {
            string greeting = "";
            Dictionary <string, Func <string, string> > commands = new Dictionary <string, Func <string, string> >();

            commands.Add("init", (empty) => { return("\"ok\""); });
            commands.Add("hello", (name) =>
            {
                string who = name.Equals("") ? "unknown person or bot" : name;
                greeting   = $"\"Meaningless clightning plugin presented to {who}\"";
                return(greeting);
            });
            commands.Add("getmanifest", (empty) =>
            {
                return("{\"options\":[{\"name\": \"greeting\",\"type\": \"string\",\"default\":\"greeting\",\"description\": \"What name should I call you?\"},],\"rpcmethods\":[{\"name\":\"hello\",\"description\": \"Returns a personalized greeting for name\",},{\"name\": \"fail\",\"description\": \"Always returns a failure for testing\"}]}");
            });

            var stdin  = Console.OpenStandardInput();
            var stdout = Console.OpenStandardOutput();
            var reader = new System.IO.StreamReader(stdin);
            var writer = new System.IO.StreamWriter(stdout);

            while (true)
            {
                string        line;
                StringBuilder builder = new StringBuilder();
                while ((line = reader.ReadLine()) != null)
                {
                    builder.Append(line);
                    try {
                        var j      = JsonConvert.DeserializeObject <JObject>(builder.ToString());
                        var method = j.GetValue("method").ToString();
                        if (commands.ContainsKey(method))
                        {
                            var paramz = j.GetValue("params");
                            var arr    = new List <string> {
                                ""
                            };
                            try {
                                // this is all I care about for now, but ignore errors if other type
                                // the init message sends the following object
                                //  "params": {"options": {      "greeting": "greeting"    },
                                //  "configuration": {    "lightning-dir": "/home/richard/.lightning",       "rpc-file":"lightning-rpc"    }  }
                                arr = paramz.ToObject <List <string> >();
                            } catch (Exception) {}
                            var str = arr.Count > 0  ? arr[0] : "";
                            writer.Write($"{{\"jsonrpc\":\"2.0\",\"id\":\"{j.GetValue("id").ToString()}\",\"result\":{commands.GetValueOrDefault(method)(str)}}}\n");
                            builder.Clear();
                            writer.Flush();
                            reader.DiscardBufferedData();
                        }
                    } catch (Exception) {}
                    System.Threading.Thread.Sleep(50);
                }
                System.Threading.Thread.Sleep(50);
            }
        }
コード例 #4
0
        public static async Task <Dictionary <string, string> > GetUserCampaignBtcAddress(Campaign campaign, IProgress <ProgressStatus> progressinfo)
        {
            Dictionary <string, string> addressList = new Dictionary <string, string>();

            System.IO.StreamReader fileRead =
                new System.IO.StreamReader(campaign.SpreadSheet);
            string line;
            int    totalLines       = 0;
            int    currentLine      = 0;
            bool   foundUser        = false;
            string userForumProfile = "";

            // Find the total lines for the report
            var file = await fileRead.ReadToEndAsync();  // big string

            var lines = file.Split(new char[] { '\n' }); // big array

            totalLines  = lines.Count();
            currentLine = 1;
            fileRead.DiscardBufferedData();
            fileRead.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);

            line = await fileRead.ReadLineAsync();

            while (line != null)
            {
                if (foundUser == false)
                {
                    userForumProfile = getUserIdBitcointalk(line);
                    if (userForumProfile != "")
                    {
                        foundUser = true;
                    }
                }

                string lineBtcAddress = getBtcAddress(line);

                if (lineBtcAddress != "" && addressList.ContainsKey(lineBtcAddress) == false && foundUser == true)
                {
                    addressList.Add(lineBtcAddress, userForumProfile);
                    foundUser = false;
                }

                line = await fileRead.ReadLineAsync();


                ReportProgressStatus(progressinfo, totalLines, currentLine,
                                     campaign.Name + " - Read line " + currentLine + "/" + totalLines,
                                     Report.LineParser);
                currentLine++;
            }

            fileRead.Close();


            return(addressList);
        }
コード例 #5
0
        /// <summary>
        /// Scan existing trace file (within Stream) for last Line and last Pair value, store its into
        /// </summary>
        /// <param name="reader"></param>
        private void _TraceAnalyse(System.IO.StreamReader reader)
        {
            if (reader.BaseStream == null)
            {
                return;
            }
            if (!reader.BaseStream.CanSeek)
            {
                return;
            }

            long chunk  = 4096L;
            long lenght = reader.BaseStream.Length;
            long offset = lenght - chunk;

            if (offset < 0L)
            {
                offset = 0L;
            }
            int?scanToLine = null;

            while (true)
            {
                reader.DiscardBufferedData();
                reader.BaseStream.Seek(offset, System.IO.SeekOrigin.Begin);
                if (offset > 0L)
                {
                    reader.ReadLine();      // Partial row, not readed from row.begin, discard it
                }
                int?firstLine = null;       // First line number, readed in this chunk
                while (!reader.EndOfStream) // && reader.pos reader.BaseStream.Position < scanTo)
                {                           // Read lines from offset, and analyse its:
                    int?line = this._TraceAnalyseLine(reader.ReadLine());
                    if (line.HasValue && scanToLine.HasValue && line.Value >= scanToLine.Value)
                    {
                        break;
                    }
                    if (line.HasValue && !firstLine.HasValue)
                    {
                        firstLine = line;
                    }
                }
                if (offset == 0L || (this._LastLine > 0L && this._LastScope > 0L))
                {
                    break;
                }

                // Scan previous chunk:
                offset -= chunk;
                if (offset < 0)
                {
                    offset = 0;
                }
                scanToLine = firstLine;
            }
        }
コード例 #6
0
        private void openEmissions_Click(object sender, EventArgs e)
        {
            // Set filter options and filter index.
            openFileDialog.FileName    = "";
            openFileDialog.Filter      = "Emission Files (.emit)|*.emit|All Files (*.*)|*.*";
            openFileDialog.FilterIndex = 1;
            openFileDialog.Multiselect = false;

            // Call the ShowDialog method to show the dialog box.
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string line;
                B = new MySparse2DMatrix();
                emissionsSymbols = new Id2Str();
                var separator = '\t';

                System.IO.StreamReader sr = new System.IO.StreamReader(openFileDialog.FileName);
                emissionsRichTextBox.Text = "";

                if ((line = sr.ReadLine()) != null)
                {
                    if (line.Split(separator).Length == 1)
                    {
                        separator = ' ';
                    }
                    sr.DiscardBufferedData();
                    sr.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
                    sr.BaseStream.Position = 0;
                }

                while ((line = sr.ReadLine()) != null)
                {
                    emissionsRichTextBox.Text += line + "\n";

                    string[] stateValue = line.Split(separator);
                    if (stateValue.Length == 3)
                    {
                        int row = stateSymbols.setId(stateValue[0]);
                        int col = emissionsSymbols.setId(stateValue[1]);
                        B.setValue(row, col, Double.Parse(stateValue[2], CultureInfo.InvariantCulture));
                    }
                }
                sr.Close();
                if (B.Count > 0)
                {
                    buttonCreateHMM.Enabled = true;
                    openObservationsToolStripMenuItem.Enabled = true;
                }
                else
                {
                    buttonCreateHMM.Enabled = false;
                    openObservationsToolStripMenuItem.Enabled = false;
                    MessageBox.Show("Error! Parsed emissions matrix resulted empty. Check your input file please.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
コード例 #7
0
        static StackObject *DiscardBufferedData_3(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 1);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.IO.StreamReader instance_of_this_method = (System.IO.StreamReader) typeof(System.IO.StreamReader).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            instance_of_this_method.DiscardBufferedData();

            return(__ret);
        }
コード例 #8
0
        private void Reset(object sender, RoutedEventArgs e)
        {
            streamReader.DiscardBufferedData();
            streamReader.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
            myCanvas2.Children.Clear();

            for (int i = 0; i < 10; i++)
            {
                word[i] = null;
                line    = null;
            }
            lblWrongLetters.Content = "";
            lblOutput.Content       = "";
            counter  = 5;
            lblWrong = null;
        }
コード例 #9
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            /*
             * 对用户名、密码进行数据校验,这里我们省略
             * using (AuthRepository _repo = new AuthRepository())
             * {
             *  IdentityUser user = await _repo.FindUser(context.UserName, context.Password);
             *
             *  if (user == null)
             *  {
             *      context.SetError("invalid_grant", "The user name or password is incorrect.");
             *      return;
             *  }
             * }*/

            string loginType = "1";

            System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.Body);
            sr.DiscardBufferedData();
            sr.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
            sr.BaseStream.Position = 0;
            string param = sr.ReadToEnd();

            string[] arr = param.Split(new char[] { '&' });
            foreach (var pair in arr)
            {
                string[] kv = pair.Split(new char[] { '=' });
                if (kv.Length == 2)
                {
                    if (kv[0].ToLower() == "logintype")
                    {
                        loginType = kv[1];
                    }
                }
            }

            if (loginType != "2")
            {
                NormalLogin(context);
            }
            else
            {
                MobileLogin(context);
            }
        }
コード例 #10
0
ファイル: Program.cs プロジェクト: ankel/Heart-Anomalies
        /// <summary>
        /// Counting function
        /// </summary>
        /// <param name="learningData">input csv file</param>
        /// <returns>a [3,x] int array contains all counts</returns>
        static int[,] Learn(string learningData)
        {
            int [,] counts;
            string[] line;
            int[] fields;
            int featuresCount;
            using (System.IO.StreamReader inFile = new System.IO.StreamReader(learningData))
            {
                line = inFile.ReadLine().Split(',');        // read first line to determine the number of features
                featuresCount = line.Length;                // number of features
                counts = new int[3, featuresCount];
                fields = new int[featuresCount];

                inFile.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);      // reset stream
                inFile.DiscardBufferedData();

                while (!inFile.EndOfStream)
                {
                    line = inFile.ReadLine().Split(',');
                    ParseFields(line, fields);
                    ++counts[fields[0], 0];         // increase the respective counts
                    ++counts[2, 0];                 //increase the total counts
                    for (int i = 1; i < featuresCount; ++i)
                    {
                        counts[fields[0], i] += fields[i];  // increase the respective counts
                        counts[2, i] += fields[i];          // increase the total counts
                    }
                }
            }

            //double[,] learned = new double[2, featuresCount];
            //learned[0, 0] = MEstimate(counts[0, 0], counts[2, 0]);
            //learned[1, 0] = MEstimate(counts[1, 0], counts[2, 0]);
            //for (int i = 1; i < featuresCount; ++i)
            //{
            //    learned[0, i] = MEstimate(counts[0, i], counts[0, 0]);
            //    learned[1, i] = MEstimate(counts[1, i], counts[1, 0]);
            //}

            if (debug)
            {
                PrintArr(counts, debugFile);
                //PrintArr(learned, debugFile);
            }

            return counts;
        }
コード例 #11
0
        private void BtnReplay_Click(object sender, RoutedEventArgs e)
        {
            counter = 7;
            WordList.DiscardBufferedData();
            WordList.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
            HangMan.Children.Clear();
            lblLetters.Content     = " ";
            lblWrongLetter.Content = " ";

            for (int i = 0; i < 10; i++)
            {
                RightAnswer = null;
            }
            lblOutput.Text = "";
            counter        = 5;
            lblWrong       = null;
        }
コード例 #12
0
        static void Main(string[] args)
        {
            int    i = 0, j;
            string line;
            string markers;

            Console.WriteLine("Choose the markers: ");
            markers = Console.ReadLine();// it should not contain spaces between markers to work properly



            System.IO.StreamReader file = new System.IO.StreamReader("intrare.txt");//the input string is read from a file
            Console.WriteLine("Input string: ");
            while ((line = file.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }

            Console.WriteLine("\n");

            file.DiscardBufferedData();
            file.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
            Console.WriteLine("The string after stripping the text that succedes the markers : ");
            while ((line = file.ReadLine()) != null)// start reading again from the file, from the first line
            {
                for (j = 0; j < markers.Length; j++)
                {
                    i = line.IndexOf(markers[j], 0);
                    if (i != -1)// IndexOf returns -1 in case it doesn't find the character in the string
                    {
                        break;
                    }
                }
                if (i != -1)
                {
                    Console.WriteLine(line.Remove(i));
                }
                else
                {
                    Console.WriteLine(line);
                }
            }
            file.Close();

            Console.ReadLine();
        }
コード例 #13
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="data"></param>
 /// <returns></returns>
 protected override System.IO.MemoryStream getStreamDataPortion(System.IO.MemoryStream data)
 {
     System.IO.StreamReader reader = new System.IO.StreamReader(data, System.Text.ASCIIEncoding.ASCII);
     System.String          line   = reader.ReadLine();
     if (line.StartsWith("*"))
     {
         int size = this.parseInteger((line.Substring(line.LastIndexOf('{'))).Trim(new Char[] { '{', '}' }));
         if (size > 0)
         {
             int offset = System.Text.ASCIIEncoding.ASCII.GetByteCount(line + "\r\n");
             reader.DiscardBufferedData();
             reader = null;
             data.Seek(offset, System.IO.SeekOrigin.Begin);
             data.SetLength(offset + size);
         }
     }
     return(data);
 }
コード例 #14
0
        public static void Run2()
        {
            const Int32 BufferSize = 128;

            int frequency   = 0;
            var frequencies = new HashSet <int> {
                frequency
            };

            using (var fileStream = System.IO.File.OpenRead(@"..\..\AdventOfCode\AdventOfCode1.txt"))
                using (var streamReader = new System.IO.StreamReader(fileStream, Encoding.UTF8, true, BufferSize))
                {
                    String line;
                    while (true)
                    {
                        line = streamReader.ReadLine();

                        if (line == null)
                        {
                            fileStream.Position = 0;
                            streamReader.DiscardBufferedData();
                            line = streamReader.ReadLine();
                        }

                        frequency += Int32.Parse(line);
                        Console.WriteLine(frequency);

                        if (frequencies.Contains(frequency))
                        {
                            Console.ReadLine();
                            return;
                        }
                        else
                        {
                            frequencies.Add(frequency);
                        }
                    }
                }
        }
コード例 #15
0
        private void openEmissions_Click(object sender, EventArgs e)
        {
            // Set filter options and filter index.
            openFileDialog.FileName = "";
            openFileDialog.Filter = "Emission Files (.emit)|*.emit|All Files (*.*)|*.*";
            openFileDialog.FilterIndex = 1;
            openFileDialog.Multiselect = false;

            // Call the ShowDialog method to show the dialog box.
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string line;
                B = new MySparse2DMatrix();
                emissionsSymbols = new Id2Str();
                var separator = '\t';

                System.IO.StreamReader sr = new System.IO.StreamReader(openFileDialog.FileName);
                emissionsRichTextBox.Text = "";

                if ((line = sr.ReadLine()) != null)
                {
                    if (line.Split(separator).Length == 1)
                        separator = ' ';
                    sr.DiscardBufferedData();
                    sr.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
                    sr.BaseStream.Position = 0;
                }

                while ((line = sr.ReadLine()) != null)
                {
                    emissionsRichTextBox.Text += line + "\n";

                    string[] stateValue = line.Split(separator);
                    if (stateValue.Length == 3)
                    {
                        int row = stateSymbols.setId(stateValue[0]);
                        int col = emissionsSymbols.setId(stateValue[1]);
                        B.setValue(row, col, Double.Parse(stateValue[2], CultureInfo.InvariantCulture));
                    }
                }
                sr.Close();
                if (B.Count > 0)
                {
                    buttonCreateHMM.Enabled = true;
                    openObservationsToolStripMenuItem.Enabled = true;
                }
                else
                {
                    buttonCreateHMM.Enabled = false;
                    openObservationsToolStripMenuItem.Enabled = false;
                    MessageBox.Show("Error! Parsed emissions matrix resulted empty. Check your input file please.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
コード例 #16
0
 //bricht den Ladevorgang ab
 private void Button_LadeStop_Click(object sender, RoutedEventArgs e)
 {
     reader.DiscardBufferedData();
     reader.Close();
     button_speichern.IsEnabled = true;
 }
コード例 #17
0
 static void SetPosition(this System.IO.StreamReader reader, long position)
 {
     reader.BaseStream.Position = position;
     reader.DiscardBufferedData();
 }
コード例 #18
0
ファイル: HashCracker.cs プロジェクト: SethBorder/AOOPProject
        public static void DoCracking()
        {
            AllocConsole();
            genDict = false;
            System.IO.StreamReader inFile;
            System.IO.StreamWriter outFile;
            try
            {
                inFile = new System.IO.StreamReader("hashdictionary.txt");
            }
            catch (System.IO.FileNotFoundException)
            {
                genDict = true;
            }

            if (genDict)
            {
                using (inFile = new System.IO.StreamReader("dictionary.txt"))
                    using (outFile = new System.IO.StreamWriter("hashdictionary.txt"))
                    {
                        //System.IO.StreamReader inFile = new System.IO.StreamReader("dictionary.txt");
                        //System.IO.StreamWriter outFile = new System.IO.StreamWriter("hashdictionary.txt");

                        string word = inFile.ReadLine();
                        while (!inFile.EndOfStream)
                        {
                            long hash = Hash(word);
                            outFile.WriteLine(hash.ToString() + ": " + word);
                            word = word.Substring(0, 1).ToUpper() + word.Substring(1, word.Length - 1);
                            hash = Hash(word);
                            outFile.WriteLine(hash.ToString() + ": " + word);
                            word = inFile.ReadLine();
                        }
                        long hash2 = Hash("");
                        outFile.WriteLine(hash2.ToString() + ": [blank]");
                    }
                outFile.Close();
                inFile.Close();
            }
            using (inFile = new System.IO.StreamReader("hashdictionary.txt"))
            {
                long hashIn    = 0;
                bool keepGoing = false;
                bool found     = false;

                Console.WriteLine("Hash to lookup?");
                try
                {
                    hashIn    = Convert.ToInt64(Console.ReadLine());
                    keepGoing = true;
                }
                catch
                {
                    Console.WriteLine("Invalid input.");
                    keepGoing = true;
                }

                while (hashIn != -1)
                {
                    threadFound = false;
                    found       = false;
                    //inFile = new System.IO.StreamReader("hashdictionary.txt");
                    while (!inFile.EndOfStream && keepGoing)
                    {
                        string line = inFile.ReadLine();
                        try
                        {
                            if (Convert.ToInt64(line.Substring(0, 10)) == hashIn)
                            {
                                Console.WriteLine(line.Substring(12));
                                found = true;
                            }
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            Console.WriteLine("Too short to be a valid hash.");
                        }
                    }
                    if (!found && keepGoing)
                    {
                        char inChar;
                        Console.WriteLine("No hashes found in dictionary. Attempt brute force? (Y/N)");
                        inChar = Convert.ToChar(Console.Read());
                        Console.ReadLine(); // Eat endline character from the previous read.
                        if (inChar == 'Y')
                        {
                            bruteList.Add(0);
                            conQ.Enqueue("a");
                            System.Diagnostics.Stopwatch howLong = new System.Diagnostics.Stopwatch();
                            howLong.Start();
                            bool loop = true;
                            //string bruteHash = "a";
                            threadHashIn = hashIn;
                            conBruteHash.Enqueue("a");

                            //var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
                            //var random = new Random();
                            for (int i = 0; i < 8; i++)
                            {
                                System.Threading.Thread newThread = new System.Threading.Thread(new System.Threading.ThreadStart(GenThreadFunc));
                                newThread.Start();
                                //conBruteHash.Enqueue(new string(
                                //    Enumerable.Repeat(chars, 6)
                                //              .Select(s => s[random.Next(s.Length)])
                                //              .ToArray()));
                            }
                            for (int i = 0; i < 24; i++)
                            {
                                System.Threading.Thread newThread = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadFunc));
                                newThread.Start();
                            }
                            //int garColl = 15000;
                            while (loop && !threadFound)
                            {
                                //conQ.Enqueue(bruteHash);
                                //IncrementString(ref bruteHash);

                                //System.Threading.Thread newThread = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadFunc));
                                //newThread.Start();

                                //if (Hash(bruteHash) == hashIn)
                                //{
                                //    Console.WriteLine("Match found: " + bruteHash);
                                //    //loop = false;
                                //}
                                //if (howLong.ElapsedMilliseconds % 1000 == 0)
                                //    Console.WriteLine(lastTested);

                                //if (howLong.ElapsedMilliseconds > garColl)
                                //{
                                //    GC.Collect();
                                //    garColl += 15000;
                                //}
                                if (howLong.ElapsedMilliseconds > 240000)
                                {
                                    loop        = false;
                                    threadFound = true;
                                    Console.WriteLine("Time limit exceeded. " + numTested + " hashes tried.");
                                }
                                System.Threading.Thread.Sleep(25);
                                //    IncrementString(ref bruteHash);
                                //    ++numTested;
                                //    if (numTested % 100000 == 0)
                                //        Console.WriteLine(bruteHash);
                            }
                        }
                        else
                        {
                            Console.WriteLine("Skipping brute force.");
                        }
                    }
                    inFile.DiscardBufferedData();
                    inFile.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
                    inFile.BaseStream.Position = 0;
                    Console.WriteLine("Hash to lookup?");
                    try
                    {
                        hashIn = Convert.ToInt64(Console.ReadLine());
                        if (hashIn != -1)
                        {
                            keepGoing = true;
                        }
                    }
                    catch
                    {
                        Console.WriteLine("Invalid input.");
                        keepGoing = false;
                    }
                }
            }
        }
コード例 #19
0
ファイル: Form1.cs プロジェクト: JanHerca/urantiapedia
        private void buttonNombres_Click(object sender, EventArgs e)
        {
            this.lblNumResult.Text = "0";
            //Obtenemos lista de ficheros LaTEX
            string currentFolder = AppDomain.CurrentDomain.BaseDirectory;

            string[] latexFiles = null;
            try {
                latexFiles = System.IO.Directory.GetFiles(currentFolder, "*.tex");
            } catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }
            //Comprobaciones
            if (latexFiles == null)
            {
                MessageBox.Show("No se han encontrado ficheros LaTEX en la carpeta de la aplicación.");
                return;
            }

            List <string> exclusiones = new List <string>();

            string[] vocablos = new string[] {
                "\\Textit", "\\Textdegree", "\\Textordmasculine", "A", "Aquel",
                "Aquél", "Aquella", "Aquellas", "Aquello", "Aquellos", "C", "E", "El",
                "Él", "Ella", "En", "Es", "Éste", "Este", "Ésta", "I", "La", "Las", "Le", "Les",
                "Lo", "Los", "O", "Oh", "U", "Un", "Una", "Unos", "Unas", "Y"
            };
            for (int n = 0; n < vocablos.Length; n++)
            {
                exclusiones.Add(vocablos[n]);
            }

            if (this.txtExcluded.Text != string.Empty)
            {
                string[] vocablos2 = this.txtExcluded.Text.Split(new char[] { ',' });
                for (int i = 0; i < vocablos2.Length; i++)
                {
                    vocablos2[i] = vocablos2[i].Trim();
                    if (!exclusiones.Contains(vocablos2[i]))
                    {
                        exclusiones.Add(vocablos2[i]);
                    }
                }
            }

            //Leer fichero LateX
            int    contador, total, indice;
            string linea, linea2;
            bool   found = false;

            string[]      palabras;
            string        palabra, palabra_minuscula;
            List <string> resultados          = new List <string>();
            List <string> palabras_minusculas = new List <string>();
            CultureInfo   cultureInfo         = Thread.CurrentThread.CurrentCulture;
            TextInfo      textInfo            = cultureInfo.TextInfo;

            System.IO.StreamReader fichero;

            for (int f = 0; f < latexFiles.Length; f++)
            {
                fichero  = new System.IO.StreamReader(latexFiles[f]);
                contador = 0;
                total    = 0;
                indice   = -1;

                //Contar lineas existentes
                while ((linea = fichero.ReadLine()) != null)
                {
                    total++;
                }
                this.progressBar1.Maximum = total;
                fichero.DiscardBufferedData();
                fichero.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);

                while ((linea = fichero.ReadLine()) != null)
                {
                    if (linea.StartsWith("\\textsuperscript{"))
                    {
                        indice   = linea.IndexOf("}");
                        linea2   = linea.Substring(indice + 1).Trim();
                        palabras = linea2.Split(
                            new char[] { ' ', '.', ',', ';', '¡', '!', '¿', '?',
                                         '<', '>', '{', '}', '(', ')', '`', '\'', '[', ']',
                                         '-', ':', '0', '1', '2', '3', '4', '5', '6', '7',
                                         '8', '9' },
                            StringSplitOptions.RemoveEmptyEntries);
                        for (int n = 0; n < palabras.Length; n++)
                        {
                            palabra_minuscula = palabras[n].ToLower();
                            if (palabra_minuscula == palabras[n] &&
                                !palabras_minusculas.Contains(palabra_minuscula))
                            {
                                palabras_minusculas.Add(palabra_minuscula);
                            }
                            if (palabras[n].ToUpper()[0] == palabras[n][0])
                            {
                                palabra = textInfo.ToTitleCase(palabras[n].ToLower());
                                if (!exclusiones.Contains(palabra) &&
                                    !resultados.Contains(palabra))
                                {
                                    resultados.Add(palabra);
                                }
                            }
                        }
                    }
                    contador++;
                    this.progressBar1.Value = contador;
                }

                fichero.Close();
            }

            //Un resultado es nombre propio si no aparece nunca en otro lugar
            //su versión en minúsculas
            this.progressBar1.Maximum = resultados.Count;
            contador = 0;

            for (int i = resultados.Count - 1; i >= 0; i--)
            {
                if (palabras_minusculas.Contains(resultados[i].ToLower()))
                {
                    resultados.RemoveAt(i);
                }
                contador++;
                this.progressBar1.Value = contador;
            }

            resultados.Sort();

            //Presentar resultados
            StringBuilder sb = new StringBuilder();

            for (int n = 0; n < resultados.Count; n++)
            {
                sb.Append(resultados[n] + "\r\n");
            }
            this.txtLog.Text       = sb.ToString();
            this.lblNumResult.Text = resultados.Count.ToString();
        }
コード例 #20
0
ファイル: Form1.cs プロジェクト: JanHerca/urantiapedia
        private void CorregirParamony()
        {
            string currentFolder = AppDomain.CurrentDomain.BaseDirectory;

            string[] rutas = System.IO.Directory.GetFiles(currentFolder, "Paramony.txt");
            if (rutas.Length == 0)
            {
                MessageBox.Show("No se encuentra Paramony.txt");
                return;
            }
            string ruta = rutas[0];

            //http://www.biblija.net/help.es/abbrevs.es.php

            string[] libros = new string[] {
                "Genesis", "Exodus", "Leviticus", "Numbers", "Deuteronomy", "Joshua",
                "Judges", "Ruth", "1 Samuel", "2 Samuel", "1 Kings", "2 Kings",
                "1 Chronicles", "2 Chronicles", "Ezra", "Nehemiah", "Esther",
                "1 Maccabees", "2 Maccabees", "Job", "Psalms", "Proverbs",
                "Ecclesiastes", "Song of Solomon", "Sirach (Ecclesiasticus)",
                "Wisdom of Solomon", "Isaiah", "Jeremiah", "Lamentations", "Baruch",
                "Ezekiel", "Daniel", "Hosea", "Joel", "Amos", "Obadiah", "Jonah", "Micah",
                "Nahum", "Habakkuk", "Zephaniah", "Haggai", "Zechariah", "Malachi",
                "Matthew", "Mark", "Luke", "John", "Acts of the Apostles", "Romans",
                "1 Corinthians", "2 Corinthians", "Galatians", "Ephesians", "Philippians",
                "Colossians", "1 Thessalonians", "2 Thessalonians", "1 Timothy", "2 Timothy",
                "Titus", "Philemon", "Hebrews", "James", "1 Peter", "2 Peter", "1 John",
                "2 John", "3 John", "Jude", "Revelation", "Bel and the Dragon",
                "Prayer of Manesseh", "Tobit", "Enoch", "Moses Asumption"
            };

            string[] abreviaturas = new string[] {
                "Gn", "Ex", "Lv", "Nm", "Dt", "Jos",
                "Jue", "Rt", "1 S", "2 S", "1 R", "2 R",
                "1 Cr", "2 Cr", "Esd", "Neh", "Est",
                "1 Mac", "2 Mac", "Job", "Sal", "Pr",
                "Ec", "Cnt", "Eclo",
                "Sab", "Is", "Jer", "Lm", "Bar",
                "Ez", "Dn", "Os", "Jl", "Am", "Abd", "Jon", "Miq",
                "Nah", "Hab", "Sof", "Hag", "Zac", "Mal",
                "Mt", "Mc", "Lc", "Jn", "Hch", "Ro",
                "1 Co", "2 Co", "Gl", "Ef", "Flp",
                "Col", "1 Ts", "2 Ts", "1 Ti", "2 Ti",
                "Tit", "Flm", "Heb", "Stg", "1 P", "2 P", "1 Jn",
                "2 Jn", "3 Jn", "Jud", "Ap", "Bel",
                "Man", "Tb", "1 Hen", "AsMo"
            };

            string linea;

            string[]      valores;
            StringBuilder sbErrores = new StringBuilder();
            StringBuilder sbResultados = new StringBuilder();
            bool          errores = false;
            int           total = 0;
            int           contador = 0;
            string        refA, refB, name, biblebook, bibleref, chapter, biblekey, key, content;
            int           bbi;
            SortedDictionary <string, SortedDictionary <string, string> > resultados = new SortedDictionary <string, SortedDictionary <string, string> >();
            SortedDictionary <string, string> items;

            System.IO.StreamReader fichero = new System.IO.StreamReader(ruta);

            //Contar lineas existentes
            while ((linea = fichero.ReadLine()) != null)
            {
                total++;
            }
            this.progressBar1.Maximum = total;
            fichero.DiscardBufferedData();
            fichero.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);

            while ((linea = fichero.ReadLine()) != null)
            {
                valores = linea.Split(new char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
                if (valores.Length != 6)
                {
                    errores = true;
                    sbErrores.Append("Error en " + linea + "\r\n");
                }
                else
                {
                    refA = valores[1];
                    if (refA.Contains("/"))
                    {
                        refB = refA.Split(new char[] { '/' })[0];
                    }
                    else
                    {
                        refB = refA;
                    }
                    name      = valores[2];
                    key       = refB + " " + name;
                    biblebook = valores[3];
                    bbi       = Array.IndexOf(libros, biblebook);
                    chapter   = valores[4];
                    if (bbi != -1)
                    {
                        bibleref = abreviaturas[bbi] + " " + compactarCapituloVersiculo(chapter);
                        biblekey = bbi.ToString() + "|" + chapter;
                        if (!resultados.ContainsKey(key))
                        {
                            items = new SortedDictionary <string, string>();
                            items.Add(biblekey, bibleref);
                            resultados.Add(key, items);
                        }
                        else
                        {
                            items = resultados[key];
                            if (!items.ContainsKey(biblekey))
                            {
                                items.Add(biblekey, bibleref);
                            }
                        }
                    }
                    else
                    {
                        errores = true;
                        sbErrores.Append("Error en " + linea + "\r\n");
                    }
                }
                contador++;
                this.progressBar1.Value = contador;
            }
            fichero.Close();

            if (errores)
            {
                this.txtLog.Text = sbErrores.ToString();
            }
            else
            {
                foreach (KeyValuePair <string, SortedDictionary <string, string> > entry in resultados)
                {
                    StringBuilder sb2   = new StringBuilder();
                    bool          first = true;
                    foreach (KeyValuePair <string, string> entry2 in entry.Value)
                    {
                        if (!first)
                        {
                            sb2.Append("; ");
                        }
                        if (first)
                        {
                            first = !first;
                        }
                        sb2.Append(entry2.Value);
                    }

                    sbResultados.Append(entry.Key + ": " + sb2.ToString() + "\r\n");
                }
                this.txtLog.Text = sbResultados.ToString();
            }
        }
コード例 #21
0
 public void DiscardBufferedData()
 {
     _actual.DiscardBufferedData();
 }
コード例 #22
0
        protected bool readBytes(System.Net.Sockets.NetworkStream ns, System.IO.MemoryStream response, System.String waitFor, bool machresponseend)
        {
            bool error = false;

            byte[] readBytes = new byte[client.ReceiveBufferSize];
            int    nbytes    = 0;

            System.String lastBoundary = System.String.Empty;
            if (log.IsDebugEnabled)
            {
                log.Debug("Reading response");
            }

            System.IAsyncResult result = ns.BeginRead(readBytes, 0, readBytes.Length, null, null);
            for (long waiting = 0; !error && ns.CanRead && result != null; nbytes = 0)
            {
                try {
                    if (!result.IsCompleted)
                    {
                        System.Threading.Thread.Sleep(50);
                        waiting += 50;
                    }
                    if (result.IsCompleted)
                    {
                        nbytes  = ns.EndRead(result);
                        result  = null;
                        waiting = 0;
                    }
                    else if (waiting > this.timeoutResponse)
                    {
                        lastErrorMessage = "Read timeout";
                        if (log.IsErrorEnabled)
                        {
                            log.Error(lastErrorMessage);
                        }
                        result = null;
                        error  = true;
                    }
                } catch (System.Exception e) {
                    error            = true;
                    nbytes           = 0;
                    lastErrorMessage = "Read error";
                    if (log.IsErrorEnabled)
                    {
                        log.Error(lastErrorMessage, e);
                    }
                }
                if (!error && nbytes > 0)
                {
                    if (log.IsDebugEnabled)
                    {
                        log.Debug("Read " + nbytes + " bytes");
                    }
                    response.Write(readBytes, 0, nbytes);
                    // Only test waitfor secuence if there is no data for reading
                    // and there are enouth data available for comparing
                    if (!ns.DataAvailable && response.Length > waitFor.Length)
                    {
                        // The waitfor text must be the last portion of the response
                        if (machresponseend)
                        {
                            response.Seek(response.Length - waitFor.Length, System.IO.SeekOrigin.Begin);
                            response.Read(readBytes, 0, waitFor.Length);
                            lastBoundary = System.Text.Encoding.ASCII.GetString(readBytes, 0, waitFor.Length);
                            // The waitfor text must be in the begining of the last line of the response
                        }
                        else
                        {
                            response.Seek(0, System.IO.SeekOrigin.Begin);
                            System.IO.StreamReader reader = new System.IO.StreamReader(response);
                            System.String          line   = System.String.Empty;
                            for (System.String tmp = reader.ReadLine(); tmp != null; line = tmp, tmp = reader.ReadLine())
                            {
                            }
                            if (line != null && line.Length >= waitFor.Length)
                            {
                                lastBoundary = line.Substring(0, waitFor.Length);
                            }
                            reader.DiscardBufferedData();
                            reader = null;
                            response.Seek(0, System.IO.SeekOrigin.End);
                        }
                    }
                    // We haven't finished, so start a new async read
                    if (lastBoundary != waitFor)
                    {
                        result = ns.BeginRead(readBytes, 0, readBytes.Length, null, null);
                    }
                }
            }
            response.Flush();
            if (log.IsDebugEnabled)
            {
                log.Debug(System.String.Concat("Reading response finished. Error: ", error, ", lenght: ", response.Length));
            }
            // Discard response if there has been a read error.
            if (error)
            {
                response.SetLength(0);
            }
            else if (response.Length == 0)
            {
                error = true;
            }
            return(!error);
        }