ReadLine() public method

public ReadLine ( ) : string
return string
        private static void ReadStudentsInfoFromFile(string filePath, SortedDictionary<string, SortedSet<Student>> courses)
        {
            using (StreamReader reader = new StreamReader(filePath))
            {
                string line = reader.ReadLine();
                while (line != string.Empty && line != null)
                {
                    string[] data = line.Split('|');
                    string firstName = data[0].Trim();
                    string lastName = data[1].Trim();
                    string courseName = data[2].Trim();

                    if (courses.ContainsKey(courseName))
                    {
                        courses[courseName].Add(new Student(firstName, lastName));
                    }
                    else
                    {
                        courses[courseName] = new SortedSet<Student>();
                        courses[courseName].Add(new Student(firstName, lastName));
                    }

                    line = reader.ReadLine();
                }
            }
        }
Beispiel #2
1
        public BoxInfo(int clientID, string fileName)
        {
            StreamReader sr = new StreamReader(fileName);

            sr.ReadLine();// burn the headings

            for (int x = 0; x < 28; x++)
            {
                myCompartments[x] = new Compartment();
            }

            string[] dataLine;

            while (!sr.EndOfStream)
            {
                dataLine = sr.ReadLine().Split(',');
                int curID = int.Parse (dataLine[0].Trim());

                if (curID == clientID)
                { //this dataline is for this client
                    int compartmentNum = int.Parse(dataLine[1]);
                    int hour = int.Parse(dataLine[2]);
                    int minute = int.Parse(dataLine[3]);
                    string pills = dataLine[4].Trim();
                    myCompartments[compartmentNum-1].hour = hour;
                    myCompartments[compartmentNum-1].minute = minute;
                    myCompartments[compartmentNum-1].pills = pills;
                }
           
            }


        }
Beispiel #3
1
        /// Read long numbers and initialize parameters
        /// A0 - The right particle of the first part of the number
        /// A1 - The left particle of the first part of the number
        /// B0 - The right particle of the second part of the number
        /// B1 - The left particle of the second part of the number
        /// K - Middle of the numbers
        /// N - Number of bits
        public static void Read(out BigInteger A0, out BigInteger A1,
                                out BigInteger B0, out BigInteger B1,
                                out int K, out int N)
        {
            using (StreamReader sr = new StreamReader("test.txt"))
            {
                string a, a0, a1, b, b0, b1;
                a = sr.ReadLine();
                b = sr.ReadLine();

                K = a.Length / 2;
                N = a.Length;

                // making strings to parse
                a0 = a.Substring(0, K);
                a1 = a.Substring(K);
                b0 = b.Substring(0, K);
                b1 = b.Substring(K);

                A0 = BigInteger.Parse(a1);
                A1 = BigInteger.Parse(a0);
                B0 = BigInteger.Parse(b1);
                B1 = BigInteger.Parse(b0);
            }

        }
Beispiel #4
0
        //Write a program that reads a text file containing a square matrix of numbers.
        //Find an area of size 2 x 2 in the matrix, with a maximal sum of its elements.
        //The first line in the input file contains the size of matrix N.
        //Each of the next N lines contain N numbers separated by space.
        //The output should be a single number in a separate text file.
        static void Main(string[] args)
        {
            StreamReader reader = new StreamReader(@"..\..\file.txt");

            using (reader)
            {
                string line = reader.ReadLine();
                int number = int.Parse(line);
                int[,] array = new int[number, number];
                for (int i = 0; i < number; i++)
                {
                    string[] numbers = reader.ReadLine().Split(' ');
                    for (int k = 0; k < number; k++)
                    {
                        array[i, k] = int.Parse(numbers[k]);
                    }
                }
                int bestsum = int.MinValue;
                for (int row = 0; row < array.GetLength(0) - 1; row++)
                {
                    for (int col = 0; col < array.GetLength(1) - 1; col++)
                    {
                        int sum = array[row, col] + array[row, col + 1] +
                            array[row + 1, col] + array[row + 1, col + 1];
                        if (sum > bestsum)
                        {
                            bestsum = sum;
                        }
                    }
                }
                Console.WriteLine(bestsum);
            }
        }
        public static void Main(string[] args)
        {
            StreamReader reader = new StreamReader(@"..\..\students.txt");
            using (reader)
            {
                SortedDictionary<string, OrderedBag<Student>> students = new SortedDictionary<string, OrderedBag<Student>>();
                for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
                {
                    var input = line.Split('|');
                    if (!students.ContainsKey(input[2].Trim()))
                    {
                        var grouped = new OrderedBag<Student>();
                        grouped.Add(new Student(input[0].Trim(), input[1].Trim()));
                        students.Add(input[2].Trim(), grouped);
                    }
                    else
                    {
                        students[input[2].Trim()].Add(new Student(input[0].Trim(), input[1].Trim()));
                    }
                }

                foreach (var student in students)
                {
                    Console.WriteLine(student);
                }
            }
        }
Beispiel #6
0
        static void Main(string[] args)
        {
            string line;

             try
             {
            FileStream aFile = new FileStream("Log.txt", FileMode.Open);
            StreamReader sr = new StreamReader(aFile);
            line = sr.ReadLine();
            // Read data in line by line.
            while (line != null)
            {
               Console.WriteLine(line);
               line = sr.ReadLine();
            }
            sr.Close();
             }
             catch (IOException e)
             {
            Console.WriteLine("An IO exception has been thrown!");
            Console.WriteLine(e.ToString());
            return;
             }
             Console.ReadKey();
        }
Beispiel #7
0
        private void button1_Click(object sender, EventArgs e)
        {
            //获得串口参数配置文件的路径
            string CfgFilePath = Application.StartupPath + "\\ConfigFile\\SerialPortCfg";

            //创建写文件流
            StreamWriter sw = new StreamWriter(CfgFilePath, false);

            //将串口参数写入文件
            sw.Write(comboBox1.SelectedItem + "\r\n");
            sw.Write(comboBox2.SelectedItem + "\r\n");
            sw.Write(comboBox3.SelectedItem + "\r\n");
            sw.Write(comboBox4.SelectedItem + "\r\n");
            sw.Write(comboBox5.SelectedItem + "\r\n");

            //关闭流
            sw.Close();

            //创建读文件流
            StreamReader sr = new StreamReader(CfgFilePath);

            //显示串口参数
            label6.Text = sr.ReadLine();
            label7.Text = sr.ReadLine();
            label8.Text = sr.ReadLine();
            label9.Text = sr.ReadLine();
            label10.Text = sr.ReadLine();

            //关闭流
            sr.Close();
            MessageBox.Show(this, "设置成功。   ", "消息",
                MessageBoxButtons.OK, MessageBoxIcon.Information);

            this.Close();   //关串口参数设置窗体
        }
Beispiel #8
0
        internal static List<List<string>> ParseCsvFile(string path)
        {
            var allIssues = new List<List<string>>();
            using (var readFile = new StreamReader(path))
            {
                var header = ParseCsvLine(readFile.ReadLine());

                string line;
                while ((line = readFile.ReadLine()) != null)
                {
                    var newIssue = ParseCsvLine(line);

                    if (string.IsNullOrEmpty(newIssue[0]))
                    {
                        for(int i = 0; i < newIssue.Count; i++)
                        {
                            if (!string.IsNullOrEmpty(newIssue[i]))
                            {
                                allIssues[allIssues.Count - 1][i] += (Environment.NewLine + newIssue[i]);
                            }
                        }
                    }
                    else
                    {
                        ValidateCsvLine(newIssue);
                        allIssues.Add(newIssue);
                    }
                }
            }
            return allIssues;
        }
        // Load an array of training set items from the csv file
        public static List<TrainingItem> Load(string csvFile)
        {
            List<TrainingItem> trainingItems = new List<TrainingItem>();
            string line;
            string[] items;

            // Read the file and display it line by line.
            System.IO.StreamReader file = new System.IO.StreamReader(csvFile);

            // Skip the first line since it is the header
            file.ReadLine();

            while ((line = file.ReadLine()) != null)
            {
                TrainingItem trainingItem = new TrainingItem();
                items = line.Split(',');
                trainingItem.FileName = items[0];
                trainingItem.Label = items[1];
                trainingItems.Add(trainingItem);
            }

            file.Close();

            return trainingItems;
        }
Beispiel #10
0
        private void bnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                client = new TcpClient(txtConnect.Text, 2000);
                ns = client.GetStream();
                sr = new StreamReader(ns);
                sw = new StreamWriter(ns);
                dato = sr.ReadLine()
                    + System.Environment.NewLine
                    + sr.ReadLine()
                    + System.Environment.NewLine
                    + sr.ReadLine();

                DelegadoRespuesta dr = new DelegadoRespuesta(EscribirFormulario);
                Invoke(dr);

            }
            catch (Exception err)
            {
                Console.WriteLine(err.ToString());
                throw;
            }


        }
Beispiel #11
0
        private static void Main()
        {
            var fileOne = new StreamReader(@"..\..\fileOne.txt");
            var fileTwo = new StreamReader(@"..\..\fileTwo.txt");

            using (fileOne)
            {
                using (fileTwo)
                {
                    var fileOneLine = fileOne.ReadLine();
                    var fileTwoLine = fileTwo.ReadLine();
                    var currentLine = 0;
                    var matchingLines = 0;

                    while (fileOneLine != null || fileTwoLine != null)
                    {
                        currentLine++;
                        if (fileTwoLine == fileOneLine)
                        {
                            matchingLines++;
                        }

                        fileOneLine = fileOne.ReadLine();
                        fileTwoLine = fileTwo.ReadLine();
                    }

                    Console.WriteLine(
                        "There are {0} line(s) that are the same and {1} that are different",
                        matchingLines,
                        currentLine - matchingLines);
                }
            }
        }
Beispiel #12
0
        static void Main(string[] args)
        {
            //Write a program that reads a text file and prints on the console its odd lines.

            string path = @"C:\Users\Ivan\Desktop\test.txt";
            Encoding utf8 = Encoding.GetEncoding("UTF-8");
            Encoding win1251 = Encoding.GetEncoding("Windows-1251");
            try
            {
                StreamReader fileReader = new StreamReader(path, win1251);
                using (fileReader)
                {
                    int lineNum = 0;
                    string line = fileReader.ReadLine();
                    while (line != null)
                    {
                        lineNum++;
                        if (lineNum % 2 != 0)
                        {
                            Console.WriteLine("Line {0}: {1}", lineNum, line);
                        }
                        line = fileReader.ReadLine();
                    }
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Error!");
            }
        }
Beispiel #13
0
        public CMusicHit(String path)
        {
            int counter = 0;
            this._next = 0;
            string line;
            StreamReader hitFile = new StreamReader(path);

            line = hitFile.ReadLine();
            this._length = int.Parse(line);
            line = hitFile.ReadLine();
            this._speed = int.Parse(line);
            line = hitFile.ReadLine();
            this._endTime = int.Parse(line);

            this._time = new int[this._length];
            this._position = new int[this._length];
            while ((line = hitFile.ReadLine()) != null) {
                if (line.Contains('t'))
                {
                    line = line.Substring(line.IndexOf(':')+1);
                    this._time[counter] = int.Parse(line);
                }
                else {
                    line = line.Substring(line.IndexOf(':')+1);
                    this._position[counter] = int.Parse(line);
                    counter++;
                }
            }
        }
        /// <summary>
        /// Carrega as informações do arquivo de configuração do E-mail.
        /// </summary>
        /// <returns></returns>
        public static Email CarregarInformacoesLoginServidor()
        {
            Cryptor cr;
            string CaminhoDoArquivo = String.Format("{0}/Email.dat", Ferramentas.ObterCaminhoDoExecutavel());
            Email EmailBase = new Email();
            StreamReader sr = null;
            cr = new Cryptor("p@$$w0rd");

            try
            {
                sr = new StreamReader(CaminhoDoArquivo);

                EmailBase.email = cr.Decrypt(sr.ReadLine());
                EmailBase.Senha = cr.Decrypt(sr.ReadLine());
                EmailBase.Host = cr.Decrypt(sr.ReadLine());
                EmailBase.Port = int.Parse(cr.Decrypt(sr.ReadLine()));
            }
            catch (System.Exception exc)
            {
                ControllerArquivoLog.GeraraLog(exc);
            }
            finally
            {
                if (sr != null)
                    sr.Close();
            }
            return EmailBase;
        }
Beispiel #15
0
        public void Run()
        {
            using (var reader = new StreamReader("jobs.txt"))
            using (var writer = new StreamWriter("output.txt"))
            {
                var jobs = new List<Job>();
                reader.ReadLine();
                while (true)
                {
                    string row = reader.ReadLine();
                    if (row == null)
                    {
                        break;
                    }

                    var parts = row.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    var numbers = parts.Select(x => int.Parse(x, CultureInfo.InvariantCulture)).ToArray();
                    jobs.Add(new Job(numbers[0], numbers[1]));
                }

                var weightedSum1 = JobScheduler.GetWeightedSumOfCompletionTimes(jobs, JobScheduler.CompareByDifference);
                writer.WriteLine(weightedSum1);

                var weightedSum2 = JobScheduler.GetWeightedSumOfCompletionTimes(jobs, JobScheduler.CompareByRatio);
                writer.WriteLine(weightedSum2);
            }
        }
Beispiel #16
0
        private void ReadFromStream(StreamReader stream)
        {
            int id = 0;
            string nextLine;

            while ((nextLine = stream.ReadLine()) != null)
            {
                string[] records = nextLine.Trim().Split(';');
                if (records.Length == 4)
                {
                    string source = records[0].Trim();
                    string message = records[1].Trim();
                    string messageLevel = records[2].Trim();
                    DateTime timestamp = DateTime.Parse(records[3].Trim());

                    items.Add(new LogItem(id, source, message, messageLevel, timestamp));
                    id++;
                    nextLine = stream.ReadLine();
                }
                else
                {
                    nextLine += stream.ReadLine();
                }
            }
        }
Beispiel #17
0
        public static string[] GetColumnNames(string filename, int nskip, HashSet<string> commentPrefix,
			HashSet<string> commentPrefixExceptions, Dictionary<string, string[]> annotationRows, char separator)
        {
            StreamReader reader = new StreamReader(filename);
            for (int i = 0; i < nskip; i++){
                reader.ReadLine();
            }
            string line = reader.ReadLine();
            if (commentPrefix != null){
                while (IsCommentLine(line, commentPrefix, commentPrefixExceptions)){
                    line = reader.ReadLine();
                }
            }
            string[] titles = line.Split(separator);
            if (annotationRows != null){
                while ((line = reader.ReadLine()) != null){
                    if (!line.StartsWith("#!{")){
                        break;
                    }
                    int end = line.IndexOf('}');
                    if (end == -1){
                        continue;
                    }
                    string name = line.Substring(3, end - 3);
                    string w = line.Substring(end + 1);
                    string[] terms = w.Split(separator);
                    annotationRows.Add(name, terms);
                }
            }
            reader.Close();
            return titles;
        }
 static void Main(string[] args)
 {
     string fileName1 = @"..\..\file1.txt";
     string fileName2 = @"..\..\file2.txt";
     StreamReader reader1 = new StreamReader(fileName1);
     StreamReader reader2 = new StreamReader(fileName2);
     int countEqual = 0;
     int countDifferent = 0;
     string line1 = reader1.ReadLine();
     string line2 = reader2.ReadLine();
     while (line1 != null)
     {
         if (line1 == line2)
         {
             countEqual++;
         }
         else
         {
             countDifferent++;
         }
         line1 = reader1.ReadLine();
         line2 = reader2.ReadLine();
     }
     reader1.Close();
     reader2.Close();
     Console.WriteLine("Equal lines number -> {0}", countEqual);
     Console.WriteLine("Different lines number -> {0}", countDifferent);
 }
Beispiel #19
0
        static void Main()
        {
            StreamWriter writerFirst = new StreamWriter(@"..\..\test.txt",false);
            using (writerFirst)
            {
                StreamReader readFirstDoc = new StreamReader(@"..\..\Concat.cs"); //The first document is the Concat.cs.
                using (readFirstDoc)
                {
                    string lineDoc1 = readFirstDoc.ReadLine();
                        while(lineDoc1!=null)
                        {
                            writerFirst.WriteLine(lineDoc1);
                            lineDoc1=readFirstDoc.ReadLine();
                        }
                }
                
            }
            StreamWriter writerSecond = new StreamWriter(@"..\..\test.txt", true);
            using(writerSecond)
            {
                StreamReader readSecondDoc = new StreamReader(@"..\..\App.config"); //The second document is App.config
                using (readSecondDoc)
                {

                    string lineDoc2 = readSecondDoc.ReadLine();
                    while (lineDoc2 != null)
                    {
                        writerSecond.WriteLine(lineDoc2);
                        lineDoc2 = readSecondDoc.ReadLine();
                    }
                }
            }
            Console.WriteLine("Concatenation finished!");
        }
 /// <summary>
 /// Fetches the list of servers and adds them to serverView's server collection
 /// </summary>
 public void fetchServers()
 {
     WebRequest serverReq = WebRequest.Create("http://kaillera.com/raw_server_list2.php?version=0.9");
     WebResponse serverResp = serverReq.GetResponse();
     using (StreamReader sr = new StreamReader(serverResp.GetResponseStream()))
     {
         while (!sr.EndOfStream)
         {
             try
             {
                 Server currServer = new Server();
                 currServer.name = sr.ReadLine();
                 string[] servInfo = sr.ReadLine().Split(';');
                 string[] ipPort = servInfo[0].Split(':');
                 currServer.ip = IPAddress.Parse(ipPort[0]);
                 currServer.port = int.Parse(ipPort[1]);
                 currServer.users = int.Parse(servInfo[1].Split('/')[0]);
                 currServer.numGames = int.Parse(servInfo[2]);
                 currServer.version = servInfo[3];
                 currServer.location = servInfo[4];
                 addServers(currServer);
             }
             catch (Exception)
             {
                 log.Warn("Invalid server detected!");
             }
         }
     }
 }
Beispiel #21
0
        public Read(Stream myStream)
        {
            string aux;
            string[] pieces;

            //read the file line by line
            StreamReader sr = new StreamReader(myStream);
            aux = sr.ReadLine();
            header = aux.Split(',');
            nColumns = header.Length;
            nLines = 0;
            while ((aux = sr.ReadLine()) != null)
            {
                if (aux.Length > 0) nLines++;
            }

            //read the numerical data from file in an array
            data = new float[nLines, nColumns];
            sr.BaseStream.Seek(0, 0);
            sr.ReadLine();
            for (int i = 0; i < nLines; i++)
            {
                aux = sr.ReadLine();
                pieces = aux.Split(',');
                for (int j = 0; j < nColumns; j++) data[i, j] = float.Parse(pieces[j]);
            }
            sr.Close();
        }
        static void Main(string[] args)
        {
            StreamReader read = StreamReader.Null;
            StreamWriter write = StreamWriter.Null;
            string line;
            int lineNumber = 0;

            try
            {
                read = new StreamReader("../../text.txt");
                write = new StreamWriter("../../numbered_text.txt");
            }
            catch (Exception e)
            {
                Console.WriteLine("The file could not be read/created:");
                Console.WriteLine(e.Message);
            }
            
            using (read)
            using (write)
            {
                line = read.ReadLine();
                while (line != null)
                {
                    write.WriteLine("{0,4}  {1}", lineNumber, line);
                    lineNumber++;
                    line = read.ReadLine();
                }
            }
            Console.WriteLine("Success!");
        }
Beispiel #23
0
        static void Main(string[] args)
        {
             using (StreamReader orig = new StreamReader("orig.txt"))
            {
                int lineNumber = 0;
                string line = orig.ReadLine();

                while (line != null)
                {
                    lineNumber++;
                    if (lineNumber % 2 == 0)
                    {
                        StreamWriter even = new StreamWriter("even.txt", true);
                        {
                            even.WriteLine(line);
                        } even.Close();
                    }
                    else
                    {
                        StreamWriter odd = new StreamWriter("odd.txt", true);
                        {
                            odd.WriteLine(line);
                        } odd.Close();
                    }
                    line = orig.ReadLine();
                }
            }
            Console.WriteLine("Your text is separated by even and odd lines in two separated files.");
            Console.WriteLine("Check your folder to see the result!");
            Console.WriteLine();
        }
		public void Read(Stream s)
		{
			var r = new StreamReader(s);
			this.Reader = r;

			var h = r.ReadLine();

			if (string.IsNullOrEmpty(h))
				return;

			var Method_i = h.IndexOf(" ");
			var Method_key = h.Substring(0, Method_i);
			var Method_value = h.Substring(Method_i + 1, h.IndexOf(" ", Method_i + 1) - (Method_i + 1));

			if (Method != null)
				Method(Method_key, Method_value);

			while (!string.IsNullOrEmpty(h))
			{
				h = r.ReadLine();

				if (!string.IsNullOrEmpty(h))
				{
					var Header_key = h.Substring(0, h.IndexOf(":"));
					var Header_value = h.Substring(h.IndexOf(":") + 1).Trim();

					if (Header != null)
						Header(Header_key, Header_value);
				}
			}
		}
        List<Show> Grab(GrabParametersBase p)
        {
            var pp = (GrabParameters)p;

            var url = string.Format(URL, pp.FromDate.ToString("dd/MM/yyyy"), pp.ToDate.ToString("dd/MM/yyyy"));

            var wr = WebRequest.Create(url);
            _logger.WriteEntry("Grabbing BBCW", LogType.Info);
            var res = (HttpWebResponse)wr.GetResponse();
            using (var sr = new StreamReader(res.GetResponseStream()))
            {
                var lst = new List<Show>();
                sr.ReadLine(); // first line
                while (!sr.EndOfStream)
                {
                    var line = sr.ReadLine();
                    if (!string.IsNullOrEmpty(line) && line.Length > 10)
                    {
                        var show = new Show();
                        show.Channel = "BBC World News";
                        var tokens = line.Split('\t');
                        show.StartTime = DateTime.SpecifyKind(Convert.ToDateTime(tokens[0]) + Convert.ToDateTime(tokens[1]).TimeOfDay, DateTimeKind.Unspecified);
                        show.StartTime = TimeZoneInfo.ConvertTime(show.StartTime, TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time"), TimeZoneInfo.Utc);
                        show.Title = tokens[2];
                        //show.Episode = string.IsNullOrEmpty(tokens[3]) ? null : (int?)Convert.ToInt32(tokens[3]); // not number
                        show.Description = tokens[4];
                        lst.Add(show);
                    }
                }
                return lst;
            }
        }
Beispiel #26
0
        private IEnumerable<Record> ReadRecords(string fileName)
        {
            var stringBuilder = new StringBuilder();

            using (var reader = new StreamReader(fileName))
            {
                ReadOnlyCollection<string> header;
                if (reader.Peek() >= 0)
                {
                    var first = this.ParseLine(reader.ReadLine(), stringBuilder).ToArray();

                    header = new ReadOnlyCollection<string>(first);
                }
                else
                {
                    yield break;
                }

                for (var i = 0; i < this._numberRecordsToSkip && reader.Peek() >= 0; i++)
                {
                    reader.ReadLine();
                }

                while (reader.Peek() >= 0)
                {
                    var items = this.ParseLine(reader.ReadLine(), stringBuilder).ToArray();

                    yield return new Record(header, items);
                }
            }
        }
 private SimpleFileHistoryManager()
 {
     _totalHistoryFilePath = Properties.Settings.Default.UtteranceLibrariesDirectory + @"\history.txt";
     if (!File.Exists(_totalHistoryFilePath)) File.Create(_totalHistoryFilePath).Dispose();
     using (TextReader reader = new StreamReader(_totalHistoryFilePath))
     {
         string line = reader.ReadLine();
         try
         {
             while (line != null)
             {
                 string[] splitted = line.Split(',');
                 _totalHistory.Add(new Utterance(
                     splitted[0],
                     splitted[1],
                     splitted[2],
                     splitted[3],
                     splitted[4],
                     splitted[5],
                     splitted[6]
                     ));
                 line = reader.ReadLine();
             }
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.Message);
         }
     }
     _instance = this;
 }
        private static void ExecuteCommands()
        {
            var reader = new StreamReader("..//..//Commands.txt");
            string line = reader.ReadLine();
            using (reader)
            {
                while (line != null)
                {
                    string[] data =
                        line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToArray();

                    var commandName = data[0];
                    if (commandName.ToLower() == "find")
                    {
                        Console.WriteLine(
                            "The command 'find' with parameters {0} returned the following results:",
                            data.Length == 3 ? string.Join(",", new[] { data[1], data[2] }) : data[1]);
                        if (data.Length == 3)
                        {
                            var result = book.Find(data[1], data[2]);
                            Console.WriteLine(string.Join("\n", result));
                        }
                        else
                        {
                            Console.WriteLine(string.Join("\n", book.Find(data[1])));
                        }
                    }
                    line = reader.ReadLine();
                }
            }
        }
Beispiel #29
0
        static void Main()
        {
            var reader = new StreamReader("..\\..\\Matrix.txt");
            int n = int.Parse(reader.ReadLine());
            int[,] matrix = new int[n, n];
            for (int row = 0; row < n; row++)
            {
                string[] textLine = reader.ReadLine().Split(' ');
                for (int col = 0; col < n; col++)
                {
                    matrix[row, col] = int.Parse(textLine[col]);
                }
            }
            reader.Close();

            int bestSum = int.MinValue;
            int bestRow = 0;
            int bestCol = 0;
            for (int row = 0; row < matrix.GetLength(0) - 1; row++)
            {
                for (int col = 0; col < matrix.GetLength(1) - 1; col++)
                {
                    int sum = matrix[row, col] + matrix[row, col + 1] + matrix[row + 1, col] + matrix[row + 1, col + 1];
                    if (sum > bestSum)
                    {
                        bestSum = sum;
                        bestRow = row;
                        bestCol = col;
                    }
                }
            }
            Console.WriteLine(bestSum);
        }
Beispiel #30
0
        public static List<Path> LoadPath()
        {
            Path pathToLoad = new Path();
            List<Path> pathsList = new List<Path>();

            using (StreamReader reader = new StreamReader(@"..\..\LoadPaths.txt"))
            {
                string newLine = reader.ReadLine();                

                while (newLine != string.Empty)
                {
                    Point3D newPoint = new Point3D();
                    newLine = reader.ReadLine();
                    
                    newPoint.X = int.Parse(newLine);
                    newLine = reader.ReadLine();
                    newPoint.Y = int.Parse(newLine);
                    newLine = reader.ReadLine();
                    newPoint.Z = int.Parse(newLine);

                    pathToLoad.AddPoint(newPoint);
                    newLine = reader.ReadLine();
                    
                    pathsList.Add(pathToLoad);
                    pathToLoad = new Path();
                    
                    
                }
            }

            return pathsList;
        }
Beispiel #31
0
        private void LoadInclusiveKeywordsButton_Click(object sender, RoutedEventArgs e)
        {
            using (var dialog = new System.Windows.Forms.OpenFileDialog())
            {
                dialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                dialog.Filter           = "*.txt|*.*";
                System.Windows.Forms.DialogResult result = dialog.ShowDialog();

                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    string path = dialog.FileName;
                    using (System.IO.StreamReader file = new System.IO.StreamReader(path))
                    {
                        while (!file.EndOfStream)
                        {
                            listBoxInclusiveFilters.Items.Add(file?.ReadLine()?.Trim());
                        }
                    }
                }
            }
        }
    private static void  predict(System.IO.StreamReader input, System.IO.BinaryWriter output, svm_model model, int predict_probability)
    {
        int    correct = 0;
        int    total = 0;
        double error = 0;
        double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0;

        int svm_type = svm.svm_get_svm_type(model);
        int nr_class = svm.svm_get_nr_class(model);

        int[]    labels         = new int[nr_class];
        double[] prob_estimates = null;

        if (predict_probability == 1)
        {
            if (svm_type == svm_parameter.EPSILON_SVR || svm_type == svm_parameter.NU_SVR)
            {
                System.Console.Out.Write("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma=" + svm.svm_get_svr_probability(model) + "\n");
            }
            else
            {
                svm.svm_get_labels(model, labels);
                prob_estimates = new double[nr_class];
                //UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
                output.Write("labels");
                for (int j = 0; j < nr_class; j++)
                {
                    //UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
                    output.Write(" " + labels[j]);
                }
                //UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
                output.Write("\n");
            }
        }
        while (true)
        {
            System.String line = input.ReadLine();
            if ((System.Object)line == null)
            {
                break;
            }

            SupportClass.Tokenizer st = new SupportClass.Tokenizer(line, " \t\n\r\f:");

            double     target = atof(st.NextToken());
            int        m      = st.Count / 2;
            svm_node[] x      = new svm_node[m];
            for (int j = 0; j < m; j++)
            {
                x[j]               = new svm_node();
                x[j].index         = atoi(st.NextToken());
                x[j].value_Renamed = atof(st.NextToken());
            }

            double v;
            if (predict_probability == 1 && (svm_type == svm_parameter.C_SVC || svm_type == svm_parameter.NU_SVC))
            {
                v = svm.svm_predict_probability(model, x, prob_estimates);
                //UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
                output.Write(v + " ");
                for (int j = 0; j < nr_class; j++)
                {
                    //UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
                    output.Write(prob_estimates[j] + " ");
                }
                //UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
                output.Write("\n");
            }
            else
            {
                v = svm.svm_predict(model, x);
                //UPGRADE_ISSUE: Method 'java.io.DataOutputStream.Write' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioDataOutputStreamWrite_javalangString"'
                output.Write(v + "\n");
            }

            if (v == target)
            {
                ++correct;
            }
            error += (v - target) * (v - target);
            sumv  += v;
            sumy  += target;
            sumvv += v * v;
            sumyy += target * target;
            sumvy += v * target;
            ++total;
        }
        System.Console.Out.Write("Accuracy = " + (double)correct / total * 100 + "% (" + correct + "/" + total + ") (classification)\n");
        System.Console.Out.Write("Mean squared error = " + error / total + " (regression)\n");
        System.Console.Out.Write("Squared correlation coefficient = " + ((total * sumvy - sumv * sumy) * (total * sumvy - sumv * sumy)) / ((total * sumvv - sumv * sumv) * (total * sumyy - sumy * sumy)) + " (regression)\n");
    }
    // Use this for initialization
    void Start()
    {
        //ahaha this code is so bad
        float x = 0; //xy coord variables to lay out the track
        float y = 0;

        Score   = 0;
        gemType = 1;



        boardFolder      = new GameObject();
        boardFolder.name = "gameBoard";
        switchList       = new List <GameObject>();
        List <GameObject> trackList = new List <GameObject>();

        GameObject tileObj;
        GameObject startTile;

        System.IO.StreamReader file = new System.IO.StreamReader(@"C:\Users\Michael\Documents\CS_stuff\GameDesign\GemDemo\Assets\Resources\boardSetup.txt");
        String line = file.ReadLine();

        String[] temp = line.Split(' ');
        rows  = Int32.Parse(temp[0]);
        cols  = Int32.Parse(temp[1]);
        board = new GameObject[rows, cols];

        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                line = file.ReadLine();
                if (line.Length == 1)  //need to add in a check for the length of the string
                //get the # and return array of tiles
                {
                    tileObj = setupTile(Int32.Parse(line));
                    if (Int32.Parse(line) < 6)
                    {
                        trackList.Add(tileObj);
                    }
                }
                else
                {
                    //read in line formatted as [<neighbor> <alt1> <alt2>]
                    String[] arr = line.Split(' ');
                    tileObj = setupTile(7);
                    Switch s = tileObj.GetComponent <Switch>();
                    s.init(Int32.Parse(arr[0]), Int32.Parse(arr[1]), Int32.Parse(arr[2]));
                    switchList.Add(tileObj);
                }
                tileObj.GetComponent <Transform>().position = new Vector3(x, y, 0);
                tileObj.transform.parent = boardFolder.transform;
                board[i, j] = tileObj;
                x          += (float)2.56;
            }
            x  = 0;
            y -= (float)2.56;
        }

        //CAN and SHOULD delete these loops and just do the stuff above by passing in a reference to the board array slots

        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                setNeighbors(i, j);

                print("Neighbors: " + board[i, j].GetComponent <Tile>().north + " " +
                      board[i, j].GetComponent <Tile>().east + " " +
                      board[i, j].GetComponent <Tile>().south + " " +
                      board[i, j].GetComponent <Tile>().west);
            }
        }

        /*
         * GameObject test = board[0, 0].GetComponent<Tile>().east
         *  .GetComponent<Tile>().east
         *  .GetComponent<Tile>().east;
         * print("IT'S F*****G THERE WHY ISNT IT SHOWING UP? "+test); */

        setSwitches(switchList);
        trackArray = trackList.ToArray();

        startTile = board[1, 0];
        GameObject train = Instantiate(Resources.Load("Prefabs/trainFab") as GameObject);

        train.GetComponent <Train>().init(startTile, EAST);
        GameObject train2 = Instantiate(Resources.Load("Prefabs/trainFab") as GameObject);
        GameObject train3 = Instantiate(Resources.Load("Prefabs/trainFab") as GameObject);

        train2.GetComponent <Train>().init(board[10, 0], 1);
        train3.GetComponent <Train>().init(board[5, 9], 3);
        trainList.Add(train);
        trainList.Add(train2);
        trainList.Add(train3);


        //Ahaha so spaghetti

        scoreText = gameObject.AddComponent <Text>();

        //set the tile that will act as a trigger to change the start tiles to not start tiles
        BoxCollider2D trigger = board[9, 2].AddComponent <BoxCollider2D>();

        board[9, 2].AddComponent <Trigger>();
        trigger.isTrigger = true;

        scoreText = GameObject.Find("Text").GetComponent <Text>();
    }
Beispiel #34
0
    static void rb_tree(string filename)
    {
        RBTree <string> tree = new RBTree <string>();

        System.Random r = new System.Random();
        System.Collections.Generic.List <string> lines = new System.Collections.Generic.List <string>();
        long ts, tt;

        {
            System.IO.FileStream   fs = new System.IO.FileStream(filename, System.IO.FileMode.Open);
            System.IO.StreamReader sr = new System.IO.StreamReader(fs);
            string line;

            ts = System.DateTime.Now.Ticks;
            while ((line = sr.ReadLine()) != null)
            {
                tree.insert_td(line); lines.Add(line);
            }
            tt = System.DateTime.Now.Ticks - ts;
            { System.Console.WriteLine(new System.TimeSpan(tt)); }

            sr.Close();
            sr.Dispose();
        }

        ts = System.DateTime.Now.Ticks;
        int res = tree.assert();

        tt = System.DateTime.Now.Ticks - ts;
        { System.Console.WriteLine(new System.TimeSpan(tt)); }

        System.Console.WriteLine("height={0}", res);
        System.Console.WriteLine("lines={0}; log2(lines)={1}", lines.Count, System.Math.Log((double)lines.Count, 2.0));

        long total = System.GC.GetTotalMemory(false);

        System.Console.WriteLine("used memory: {0}", total);
        {
            RBTree <string> .iterator it = tree.begin();
            for (; it != tree.end(); ++it)
            {
                System.Console.WriteLine(it.value());
            }
        }

        tt = 0;
        for (int i = 0; i < 500; ++i)
        {
            int idx = r.Next(lines.Count);

            ts = System.DateTime.Now.Ticks;
            tree.remove_td(lines[idx]);
            tt += System.DateTime.Now.Ticks - ts;

            res = tree.assert();
            //System.Console.WriteLine("height={0}", res);
        }
        {
            System.Console.WriteLine("rb_tree total R: {0}", new System.TimeSpan(tt));
            System.Console.WriteLine("rb_tree avg R: {0}", new System.TimeSpan((tt / 500)));
        }

        tt = 0;
        for (int i = 0; i < 500; ++i)
        {
            int idx = r.Next(lines.Count);

            ts = System.DateTime.Now.Ticks;
            tree.insert_td(lines[idx]);
            tt += System.DateTime.Now.Ticks - ts;
        }
        {
            System.Console.WriteLine("rb_tree total I: {0}", new System.TimeSpan(tt));
            System.Console.WriteLine("rb_tree avg I: {0}", new System.TimeSpan((tt / 500)));
        }

        r     = null;
        tree  = null;
        lines = null;
        System.GC.Collect();
    }
Beispiel #35
0
    static void slist(string filename)
    {
        System.Collections.Generic.List <string> slist = new System.Collections.Generic.List <string>();
        System.Random r = new System.Random();
        System.Collections.Generic.List <string> lines = new System.Collections.Generic.List <string>();
        long ts, tt;

        {
            System.IO.FileStream   fs = new System.IO.FileStream(filename, System.IO.FileMode.Open);
            System.IO.StreamReader sr = new System.IO.StreamReader(fs);
            string line;

            ts = System.DateTime.Now.Ticks;
            while ((line = sr.ReadLine()) != null)
            {
                slist.Add(line); lines.Add(line);
            }
            tt = System.DateTime.Now.Ticks - ts;
            { System.Console.WriteLine(new System.TimeSpan(tt)); }

            sr.Close();
            sr.Dispose();
        }

        slist.Sort();
        long total = System.GC.GetTotalMemory(false);

        System.Console.WriteLine("used memory: {0}", total);

        tt = 0;
        for (int i = 0; i < 500; ++i)
        {
            int idx = r.Next(lines.Count);

            ts = System.DateTime.Now.Ticks;
            slist.Remove(lines[idx]);
            tt += System.DateTime.Now.Ticks - ts;
        }
        {
            System.Console.WriteLine("slist total R: {0}", new System.TimeSpan(tt));
            System.Console.WriteLine("slist avg R: {0}", new System.TimeSpan((tt / 500)));
        }

        tt = 0;
        for (int i = 0; i < 500; ++i)
        {
            int idx = r.Next(lines.Count);

            ts = System.DateTime.Now.Ticks;
            int slist_idx = slist.BinarySearch(lines[idx]);

            if (slist_idx < 0)
            {
                slist_idx = ~slist_idx;
            }
            slist.Insert(slist_idx, lines[idx]);
            tt += System.DateTime.Now.Ticks - ts;
        }
        {
            System.Console.WriteLine("slist total I: {0}", new System.TimeSpan(tt));
            System.Console.WriteLine("slist avg I: {0}", new System.TimeSpan((tt / 500)));
        }

        r     = null;
        slist = null;
        lines = null;
        System.GC.Collect();
    }
Beispiel #36
0
    protected void OnOpen(object sender, EventArgs e)
    {
        string foil_name = "";
        Foil   new_f     = null;

        FileChooserDialog fcd = new FileChooserDialog("Open", this, FileChooserAction.Open, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept);

        if (fcd.Run() == (int)ResponseType.Accept)
        {
            // Get File Data

            System.IO.StreamReader nfile = new System.IO.StreamReader(fcd.Filename);

            int length = 0;

            while (!nfile.EndOfStream)
            {
                string line = nfile.ReadLine();
                if (line.Contains("Airfoil"))
                {
                    foil_name = line;
                }
                else
                {
                    length++;
                }
            }

            nfile.Close();
            System.IO.StreamReader file = new System.IO.StreamReader(fcd.Filename);

            double[] ux = new double[length / 2];
            double[] uy = new double[length / 2];
            double[] lx = new double[length / 2];
            double[] ly = new double[length / 2];

            Char[] seperator = { ' ', ',' };

            int len = 0;
            while (len < length / 2)
            {
                String line = file.ReadLine();
                if (!line.Contains("Airfoil"))
                {
                    String[] splits = line.Split(seperator, StringSplitOptions.RemoveEmptyEntries);

                    if (splits.Length == 2)
                    {
                        ux[len] = Convert.ToDouble(splits[0]);
                        uy[len] = -Convert.ToDouble(splits[1]);
                    }
                    else
                    {
                        ux[len] = Convert.ToDouble(splits[1]);
                        uy[len] = -Convert.ToDouble(splits[2]);
                    }

                    len++;
                }
            }

            len = 0;

            while (len < length / 2)
            {
                String   line   = file.ReadLine();
                String[] splits = line.Split(seperator, StringSplitOptions.RemoveEmptyEntries);
                if (splits.Length == 2)
                {
                    lx[len] = Convert.ToDouble(splits[0]);
                    ly[len] = -Convert.ToDouble(splits[1]);
                }
                else
                {
                    lx[len] = Convert.ToDouble(splits[1]);
                    ly[len] = -Convert.ToDouble(splits[2]);
                }

                len++;
            }

            file.Close();

            Foil f = new Foil(ux, uy, lx, ly, foil_name);
            new_f = f;
            foils.Add(f);
        }

        fcd.Destroy();

        // Get Name

        Window name_dialog = new Window("Name Airfoil");

        Entry  ent = new Entry("Airfoil Name");
        Button b1  = new Button("Cancel");
        Button b2  = new Button("Continue");

        void cancel_callback(object obj, EventArgs args)
        {
            new_f.name = "Imported Airfoil";
            name_dialog.Destroy();
            ShowPointData(new_f);
            selected_foil = new_f;
            Redraw();
        }

        void accept_callback(object obj, EventArgs args)
        {
            new_f.name = ent.Text;
            name_dialog.Destroy();
            ShowPointData(new_f);
            selected_foil = new_f;
            Redraw();
        }

        b1.Clicked += cancel_callback;
        b2.Clicked += accept_callback;


        HBox h1 = new HBox
        {
            b1,
            b2
        };
        VBox v1 = new VBox
        {
            ent,
            h1
        };

        name_dialog.Add(v1);
        name_dialog.ShowAll();
    }
Beispiel #37
0
    public bool LoadSetting()
    {
        try
        {
            using (System.IO.StreamReader file = new System.IO.StreamReader(System.AppDomain.CurrentDomain.BaseDirectory + configFileName))
            {
                bool formatError = false;
                // read language index
                if (!Int32.TryParse(file.ReadLine(), out loadedLanguageIndex))
                {
                    formatError = true;
                }
                else
                {
                    // check if the language index is in range
                    if (loadedLanguageIndex < 0 || loadedLanguageIndex > numberOfLanguage)
                    {
                        formatError = true;
                    }
                }

                // read interface name
                loadedInterfaceName = file.ReadLine();


                // read update frequency
                if (!Double.TryParse(file.ReadLine(), out loadedUpdateFrequency))
                {
                    formatError = true;
                }
                // check if the update frequency is in range
                else if (loadedUpdateFrequency < minFrequency || loadedUpdateFrequency > maxFrequency)
                {
                    formatError = true;
                }

                // read speed unit index
                if (!Int32.TryParse(file.ReadLine(), out loadedSpeedUnitIndex))
                {
                    formatError = true;
                }
                else if (loadedSpeedUnitIndex < 0 || loadedSpeedUnitIndex > numberOfSpeedUnit)
                {
                    formatError = true;
                }

                // read speed unit
                loadedSpeedUnit = file.ReadLine();

                // read show method index
                if (!Int32.TryParse(file.ReadLine(), out loadedDisplayMethodIndex))
                {
                    formatError = true;
                }
                else if (loadedDisplayMethodIndex < 0 || loadedDisplayMethodIndex > 3)
                {
                    formatError = true;
                }

                // read floating window size index
                if (!Int32.TryParse(file.ReadLine(), out loadedDisplaySizeIndex))
                {
                    formatError = true;
                }
                else if (loadedDisplaySizeIndex < 0 || loadedDisplaySizeIndex >= numberOfWindowSize)
                {
                    formatError = true;
                }

                // read dark mode index
                if (!Int32.TryParse(file.ReadLine(), out loadedDarkThemeIndex))
                {
                    formatError = true;
                }
                else
                {
                    // check if the dark mode index is in range
                    if (loadedDarkThemeIndex < 0 || loadedDarkThemeIndex > 1)
                    {
                        formatError = true;
                    }
                }

                // read auto start option
                if (!Boolean.TryParse(file.ReadLine(), out loadedAutoStartCheck))
                {
                    formatError = true;
                }

                // read show bubble option
                if (!Boolean.TryParse(file.ReadLine(), out loadedShowBubbleCheck))
                {
                    formatError = true;
                }

                // check if the format of file correct
                if (formatError)
                {
                    // format of the file is wrong, return false
                    return(false);
                }
                else
                {
                    // return true to tell the file readed successfully
                    return(true);
                }
            }
        }
        catch
        {
            // error occur, return false
            return(false);
        }
    }
    public void StartTesting()
    {
        int n_error = 0;

        using (System.IO.StreamWriter wrt_err = new System.IO.StreamWriter(System.IO.Path.Combine(tmp_folder, "errors.txt")))
        {
            foreach (var d in check_data_list)
            {
                string built_lemma = null;
                bool   ok          = table.Test(d.POS_tag, d.wordform, d.lemma, out built_lemma);
                if (!ok)
                {
                    n_error++;
                    wrt_err.WriteLine("wordform={0} required_lemma={1} built_lemma={2}", d.wordform, d.lemma, built_lemma);
                }
            }
        }

        Console.WriteLine("Error rate={0:G4}%", n_error * 100.0 / (float)check_data_list.Count);



        // Делаем лемматизацию текста из файла для визуального контроля.
        if (System.IO.File.Exists(System.IO.Path.Combine(tmp_folder, "lemmatizer_test.txt")))
        {
            using (System.IO.StreamReader rdr = new System.IO.StreamReader(System.IO.Path.Combine(tmp_folder, "lemmatizer_test.txt")))
            {
                using (System.IO.StreamWriter wrt = new System.IO.StreamWriter(System.IO.Path.Combine(tmp_folder, "lemmatizer_output.txt")))
                {
                    while (!rdr.EndOfStream)
                    {
                        string line = rdr.ReadLine();
                        if (line == null)
                        {
                            break;
                        }

                        line = line.Trim();
                        if (line.Length == 0)
                        {
                            continue;
                        }

                        SolarixGrammarEngineNET.AnalysisResults morph = GetGrammarEngine().AnalyzeMorphology(line, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_COMPLETE_ONLY, Constraints);


                        for (int iword = 1; iword < morph.Count - 1; ++iword)
                        {
                            SolarixGrammarEngineNET.SyntaxTreeNode token = morph[iword];

                            string wordform = token.GetWord().ToLower();

                            if (wordform.Contains("  "))
                            {
                                System.Text.RegularExpressions.Regex rx = new System.Text.RegularExpressions.Regex("[ ]{2,}");
                                wordform = rx.Replace(wordform, " ");
                            }

                            string lemma = wordform;
                            if (!IsNumword(lemma))
                            {
                                int POS_tag = tags.MatchTags(token, 0, gren);
                                lemma = table.BuildLemma(POS_tag, wordform);
                            }

                            wrt.Write("{0} ", lemma);
                        }

                        wrt.WriteLine("");
                    }
                }
            }
        }

        return;
    }
Beispiel #39
0
        private void comunica(string txUrl)
        {
            //el texto de la web
            string Texto_Web = "";

            try
            {
                WebRequest             req     = WebRequest.Create(txUrl);
                WebResponse            resul   = req.GetResponse();
                System.IO.Stream       recibir = resul.GetResponseStream();
                Encoding               encode  = Encoding.GetEncoding("utf-8");
                System.IO.StreamReader sr      = new System.IO.StreamReader(recibir, encode);
                // la web funciona
                weberrorcount = 0;
                // leer el estreamer
                while (sr.Peek() >= 0)
                {
                    Texto_Web += sr.ReadLine();
                }
                recibir.Close();
                resul.Close();
            }
            catch (WebException e)
            {
                // casca la web ...
                // se retrasa el tiempo ....
                weberrorcount  = weberrorcount + 1;
                timer.Interval = (weberrorcount * 60000);
            }
            catch (Exception e)
            {
            }

            //ahora interpreta la cadena
            // que viene asi:
            // echo'AVISO$$$'texto.'$$$'.$urlav.'$$$'.$lat.'$$$'.$lon.'$$$'.$radio.'$$$'.$login.'$$$'.'N';
            string       st_Texto = "";
            string       st_URL   = "";
            string       st_TX    = "";
            string       st_lat   = "";
            string       st_lon   = "";
            string       st_login = "";
            string       st_radio = "";
            string       st_pos   = "";
            int          i_a;
            int          i_b;
            int          i_c;
            int          i_d;
            int          i_e;
            int          i_f;
            int          i_g;
            int          i_h;
            DialogResult dlg_c = DialogResult.No;

            //coge el contenido devuelto por hipoqih y lo parsea
            if (Texto_Web != null)
            {
                st_Texto = Texto_Web;
                i_a      = st_Texto.IndexOf("$$$");
                if (i_a > 0)
                {
                    if (st_Texto.Substring(0, 6) == "CODIGO")
                    {
                        //es la respuesta del alta, viene el id seguro
                        i_b      = st_Texto.IndexOf("$$$", i_a + 3);
                        idseguro = st_Texto.Substring(i_a + 3, i_b - i_a - 3);
                        if (idseguro == "ERROR")
                        {
                            timer.Enabled = false; //PDA
                            dlg_c         = MessageBox.Show(lite[2], "hipoqih plugin", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                            bStop_Click();
                            return;
                        }
                        else
                        {
                            lComStatus.Text = lite[3];
                            sw_conect       = true;
                            //bMapa.Enabled = true;
                        }
                    }
                    if (st_Texto.Substring(0, 5) == "AVISO")
                    {
                        // hay un aviso pendiente
                        try
                        {
                            i_b      = st_Texto.IndexOf("$$$", i_a + 3);
                            st_TX    = st_Texto.Substring(i_a + 3, i_b - i_a - 3);
                            i_c      = st_Texto.IndexOf("$$$", i_b + 3);
                            st_URL   = st_Texto.Substring(i_b + 3, i_c - i_b - 3);
                            i_d      = st_Texto.IndexOf("$$$", i_c + 3);
                            st_lat   = st_Texto.Substring(i_c + 3, i_d - i_c - 3);
                            i_e      = st_Texto.IndexOf("$$$", i_d + 3);
                            st_lon   = st_Texto.Substring(i_d + 3, i_e - i_d - 3);
                            i_f      = st_Texto.IndexOf("$$$", i_e + 3);
                            st_radio = st_Texto.Substring(i_e + 3, i_f - i_e - 3);
                            i_g      = st_Texto.IndexOf("$$$", i_f + 3);
                            st_login = st_Texto.Substring(i_f + 3, i_g - i_f - 3);
                            i_h      = st_Texto.IndexOf("$$$", i_g + 3);
                            st_pos   = st_Texto.Substring(i_g + 3, i_h - i_g - 3);
                        }
                        catch
                        { }
                        // mostrar el texto
                        if (st_Texto != "")
                        {
                            if (st_pos == "S")
                            {
                                // muestra el texto del aviso POSICIONAL en el form
                                txAviso.Text = st_login + lite[4] + st_radio + lite[5];
                                txFecha.Text = System.DateTime.Now.ToString();
                                txLogin.Text = "hipoqih";
                                txRadio.Text = "";
                            }
                            else
                            {
                                // muestra el texto del aviso NO POSICIONAL en el form
                                txAviso.Text = st_TX;
                                txFecha.Text = System.DateTime.Now.ToString();
                                txLogin.Text = st_login;
                                txRadio.Text = st_radio;
                            }
                            //lanzar un sonido
                            if (Config.sonido != "NONE")
                            {
                                Sonar(Config.sonido);
                            }
                            this.WindowState = FormWindowState.Normal;
                        }
                        // se va a mostrar.
                        //parche por si acaso
                        if (st_URL.ToUpper() == "HTTP://")
                        {
                            st_URL = "";
                        }
                        if (st_pos == "S")
                        {
                            timer.Enabled = false;
                            dlg_c         = MessageBox.Show(st_login + lite[4] + st_radio + lite[6], lite[7], MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                            timer.Enabled = true;
                        }
                        else
                        {
                            if (st_URL == "" & !Config.avisomapaurl)
                            {
                                // no se saca mensaje si no hay URL y no esta marcado el flag de mapa
                            }
                            else
                            {
                                if (!Config.avisoauto)
                                {
                                    timer.Enabled = false;
                                    dlg_c         = MessageBox.Show(lite[8] + st_login + lite[9], lite[7], MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                                    timer.Enabled = true;
                                }
                            }
                        }
                        if ((Config.avisoauto & st_pos == "N") | dlg_c == DialogResult.Yes)
                        {
                            //al mostrar el aviso se sube el timer a un minuto a huevo
                            timer.Interval = 120000;
                            // mostrar la URL en el mapa si esta configurado para que se muestran en mapa,
                            // si no tiene URL y esta configurado para mapa o si el aviso es posicional
                            if ((Config.avisomapa) | (Config.avisomapaurl & st_URL == "") | (st_pos == "S"))
                            {
                                if (Config.explorador == "hipoqih")
                                {
                                    Abrir_Mapa(st_lat, st_lon, st_TX);
                                }
                                else
                                {
                                    Abrir_URL("http://www.hipoqih.com/mapa_aviso.php?iduser="******"&ancho=" + Config.avisowidth.ToString() + "&alto=" + Config.avisoheight.ToString(), st_TX);
                                }
                            }
                            else
                            {
                                if (st_URL != "")
                                {
                                    Abrir_URL(st_URL, lite[7]);
                                }
                            }
                        }
                    }
                }
            }
        }
Beispiel #40
0
 static string ReadLine() => file == null?Console.ReadLine() : file.ReadLine();
Beispiel #41
0
    public static void Main(string[] args)
    {
        System.IO.StreamReader file = new System.IO.StreamReader("input.txt");
        string line;

        // math coordinate grid
        int direction = 0;
        int pos_x     = 0;
        int pos_y     = 0;

        while ((line = file.ReadLine()) != null)
        {
            char action = line[0];
            int  arg    = Convert.ToInt32(line.Substring(1));

            switch (action)
            {
            case 'N':
                pos_y += arg;
                break;

            case 'S':
                pos_y -= arg;
                break;

            case 'E':
                pos_x += arg;
                break;

            case 'W':
                pos_x -= arg;
                break;

            case 'L':
                direction += arg;
                if (direction >= 360)
                {
                    direction -= 360;
                }
                break;

            case 'R':
                direction -= arg;
                if (direction < 0)
                {
                    direction += 360;
                }
                break;

            case 'F':
                pos_x += (int)(arg * Math.Cos(Math.PI * direction / 180.0));
                pos_y += (int)(arg * Math.Sin(Math.PI * direction / 180.0));
                break;

            default:
                System.Console.Error.WriteLine("invalid action: {0}", action);
                System.Environment.Exit(1);
                break;
            }
        }
        file.Close();

        int mhd = Math.Abs(pos_x) + Math.Abs(pos_y);

        System.Console.WriteLine(mhd);

        // part 2

        file = new System.IO.StreamReader("input.txt");

        int wp_x = 10;
        int wp_y = 1;

        pos_x = 0;
        pos_y = 0;

        while ((line = file.ReadLine()) != null)
        {
            char action = line[0];
            int  arg    = Convert.ToInt32(line.Substring(1));

            switch (action)
            {
            case 'N':
                wp_y += arg;
                break;

            case 'S':
                wp_y -= arg;
                break;

            case 'E':
                wp_x += arg;
                break;

            case 'W':
                wp_x -= arg;
                break;

            case 'L':
            case 'R':
                double angle = (Math.PI * arg) / 180;
                if (action == 'R')
                {
                    angle = -angle;
                }
                double x = wp_x * Math.Cos(angle) - wp_y * Math.Sin(angle);
                double y = wp_x * Math.Sin(angle) + wp_y * Math.Cos(angle);
                wp_x = Convert.ToInt32(x);
                wp_y = Convert.ToInt32(y);
                break;

            case 'F':
                pos_x += wp_x * arg;
                pos_y += wp_y * arg;
                break;

            default:
                System.Console.Error.WriteLine("invalid action: {0}", action);
                System.Environment.Exit(1);
                break;
            }
        }
        file.Close();

        mhd = Math.Abs(pos_x) + Math.Abs(pos_y);
        System.Console.WriteLine(mhd);
    }
Beispiel #42
0
    int iGridSizeX, iGridSizeY, iGridSizeZ; //Size of the Grid in Array units.

    private void Start()                    //Ran once the program starts
    {
        fNodeDiameter = fNodeRadius * 2;
        //---------read coordinates of the obstacles from a file-------
        int    counter = 0;
        string line;

        System.IO.StreamReader file =
            new System.IO.StreamReader(@"E:\Others\Unity\New Unity Project\Assets\MapCoordinates.txt");
        String[] strlist = new String[3];
        while ((line = file.ReadLine()) != null)
        {
            counter++;
            String[] spearator = { "(", ",", ")" };
            Int32    count     = 4;
            strlist = line.Split(spearator, count,
                                 StringSplitOptions.RemoveEmptyEntries);
            cube.transform.localScale = new Vector3(0.9f, float.Parse(strlist[2]), 0.9f);
            Vector3 zeroZero      = transform.position - Vector3.right * vGridWorldSize.x / 2 - Vector3.forward * vGridWorldSize.y / 2;
            Vector3 worldPointObj = zeroZero + Vector3.right * (float.Parse(strlist[0]) * fNodeDiameter + fNodeRadius) + Vector3.forward * (float.Parse(strlist[1]) * fNodeDiameter + fNodeRadius) + Vector3.up * (float.Parse(strlist[2]) / 2 * fNodeDiameter);//Get the world coordinates of the
            print(line + "\t" + worldPointObj.x + ", " + worldPointObj.y + ", " + worldPointObj.z);
            Instantiate(cube, worldPointObj, Quaternion.identity, obstalces);
            cube.layer = 8;
            cube.transform.position = worldPointObj;
            cube.name = "Obj";
        }
        file.Close();
        // ------------------------------

        //---------------------Getting all the GameObjects heights on the map and store them in an array in order
        // to use for the Z paramater of the grid (levels of the grid)----------------------------------------
        heightSet = new HashSet <float> ();
        GameObject[] allObjects = UnityEngine.Object.FindObjectsOfType <GameObject>();
        foreach (GameObject obj in allObjects)
        {
            if (obj.name == "Camera" || obj.name == "Directional Light" || obj.name == "GameManager" || obj.name == "Obstacles" || obj.name == "Plane")
            {
                continue;
            }
            float h = obj.transform.position.y + obj.transform.localScale.y / 2;
            if (!heightSet.Contains(h))
            {
                heightSet.Add(h);
            }
            continue;
        }
        heightList = new List <float>(heightSet);
        heightList.Add(0);
        heights = new float [heightList.Count];
        heights = heightList.ToArray();
        print("array count = " + heights.Length);
        Array.Sort(heights);
        for (int i = 0; i < heights.Length; i++)
        {
            print("heights[" + i + "] = " + heights[i]);
        }

        iGridSizeX = Mathf.RoundToInt(vGridWorldSize.x / fNodeDiameter); //Divide the grids world co-ordinates by the diameter to get the size of the graph in array units.
        iGridSizeY = Mathf.RoundToInt(vGridWorldSize.y / fNodeDiameter); //Divide the grids world co-ordinates by the diameter to get the size of the graph in array units.
        iGridSizeZ = Mathf.RoundToInt(heights.Length / fNodeDiameter);   //Divide the grids world co-ordinates by the diameter to get the size of the graph in array units.

        CreateGrid();                                                    //Draw the grid
    }
Beispiel #43
0
    void OnGUI()
    {
        GUILayout.Label(position + "");
        GUILayout.Space(3);
        int oldValue = GUI.skin.window.padding.bottom;

        GUI.skin.window.padding.bottom = -20;
        Rect windowRect = GUILayoutUtility.GetRect(1, 17);

        windowRect.x     += 4;
        windowRect.width -= 7;
        editorMode        = GUI.SelectionGrid(windowRect, editorMode, modes, 2, "Window");
        GUI.skin.window.padding.bottom = oldValue;

        switch (editorMode)
        {
        case 0:
            selectedCheckType = GUILayout.SelectionGrid(selectedCheckType, checkType, 2, "Toggle");
            GUI.enabled       = selectedCheckType == 0;
            targetComponent   = (MonoScript)EditorGUILayout.ObjectField(targetComponent, typeof(MonoScript), false);
            GUI.enabled       = true;

            if (GUILayout.Button("Check component usage"))
            {
                AssetDatabase.SaveAssets();
                switch (selectedCheckType)
                {
                case 0:
                    componentName = targetComponent.name;
                    string   targetPath = AssetDatabase.GetAssetPath(targetComponent);
                    string[] allPrefabs = GetAllPrefabs();
                    listResult = new List <string>();
                    foreach (string prefab in allPrefabs)
                    {
                        string[] single       = new string[] { prefab };
                        string[] dependencies = AssetDatabase.GetDependencies(single);
                        foreach (string dependedAsset in dependencies)
                        {
                            if (dependedAsset == targetPath)
                            {
                                listResult.Add(prefab);
                            }
                        }
                    }
                    break;

                case 1:
                    List <string> scenesToLoad = new List <string>();
                    existingComponents = new List <ComponentNames>();
                    prefabComponents   = new List <ComponentNames>();
                    notUsedComponents  = new List <ComponentNames>();
                    addedComponents    = new List <ComponentNames>();
                    sceneComponents    = new List <ComponentNames>();

                    if (EditorApplication.SaveCurrentSceneIfUserWantsTo())
                    {
                        string projectPath = Application.dataPath;
                        projectPath = projectPath.Substring(0, projectPath.IndexOf("Assets"));

                        string[] allAssets = AssetDatabase.GetAllAssetPaths();

                        foreach (string asset in allAssets)
                        {
                            int indexCS = asset.IndexOf(".cs");
                            int indexJS = asset.IndexOf(".js");
                            if (indexCS != -1 || indexJS != -1)
                            {
                                ComponentNames newComponent = new ComponentNames(NameFromPath(asset), "", asset);
                                try
                                {
                                    System.IO.FileStream   FS = new System.IO.FileStream(projectPath + asset, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
                                    System.IO.StreamReader SR = new System.IO.StreamReader(FS);
                                    string line;
                                    while (!SR.EndOfStream)
                                    {
                                        line = SR.ReadLine();
                                        int index1 = line.IndexOf("namespace");
                                        int index2 = line.IndexOf("{");
                                        if (index1 != -1 && index2 != -1)
                                        {
                                            line   = line.Substring(index1 + 9);
                                            index2 = line.IndexOf("{");
                                            line   = line.Substring(0, index2);
                                            line   = line.Replace(" ", "");
                                            newComponent.namespaceName = line;
                                        }
                                    }
                                }
                                catch
                                {
                                }

                                existingComponents.Add(newComponent);

                                try
                                {
                                    System.IO.FileStream   FS = new System.IO.FileStream(projectPath + asset, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
                                    System.IO.StreamReader SR = new System.IO.StreamReader(FS);

                                    string line;
                                    int    lineNum = 0;
                                    while (!SR.EndOfStream)
                                    {
                                        lineNum++;
                                        line = SR.ReadLine();
                                        int index = line.IndexOf("AddComponent");
                                        if (index != -1)
                                        {
                                            line = line.Substring(index + 12);
                                            if (line[0] == '(')
                                            {
                                                line = line.Substring(1, line.IndexOf(')') - 1);
                                            }
                                            else if (line[0] == '<')
                                            {
                                                line = line.Substring(1, line.IndexOf('>') - 1);
                                            }
                                            else
                                            {
                                                continue;
                                            }
                                            line  = line.Replace(" ", "");
                                            line  = line.Replace("\"", "");
                                            index = line.LastIndexOf('.');
                                            ComponentNames newComp;
                                            if (index == -1)
                                            {
                                                newComp = new ComponentNames(line, "", "");
                                            }
                                            else
                                            {
                                                newComp = new ComponentNames(line.Substring(index + 1, line.Length - (index + 1)), line.Substring(0, index), "");
                                            }
                                            string pName = asset + ", Line " + lineNum;
                                            newComp.usageSource.Add(pName);
                                            index = addedComponents.IndexOf(newComp);
                                            if (index == -1)
                                            {
                                                addedComponents.Add(newComp);
                                            }
                                            else
                                            {
                                                if (!addedComponents[index].usageSource.Contains(pName))
                                                {
                                                    addedComponents[index].usageSource.Add(pName);
                                                }
                                            }
                                        }
                                    }
                                }
                                catch
                                {
                                }
                            }
                            int indexPrefab = asset.IndexOf(".prefab");

                            if (indexPrefab != -1)
                            {
                                string[] single       = new string[] { asset };
                                string[] dependencies = AssetDatabase.GetDependencies(single);
                                foreach (string dependedAsset in dependencies)
                                {
                                    if (dependedAsset.IndexOf(".cs") != -1 || dependedAsset.IndexOf(".js") != -1)
                                    {
                                        ComponentNames newComponent = new ComponentNames(NameFromPath(dependedAsset), GetNamespaceFromPath(dependedAsset), dependedAsset);
                                        int            index        = prefabComponents.IndexOf(newComponent);
                                        if (index == -1)
                                        {
                                            newComponent.usageSource.Add(asset);
                                            prefabComponents.Add(newComponent);
                                        }
                                        else
                                        {
                                            if (!prefabComponents[index].usageSource.Contains(asset))
                                            {
                                                prefabComponents[index].usageSource.Add(asset);
                                            }
                                        }
                                    }
                                }
                            }
                            int indexUnity = asset.IndexOf(".unity");
                            if (indexUnity != -1)
                            {
                                scenesToLoad.Add(asset);
                            }
                        }

                        for (int i = addedComponents.Count - 1; i > -1; i--)
                        {
                            addedComponents[i].assetPath = GetPathFromNames(addedComponents[i].namespaceName, addedComponents[i].componentName);
                            if (addedComponents[i].assetPath == "")
                            {
                                addedComponents.RemoveAt(i);
                            }
                        }

                        foreach (string scene in scenesToLoad)
                        {
                            EditorApplication.OpenScene(scene);
                            GameObject[] sceneGOs = GetAllObjectsInScene();
                            foreach (GameObject g in sceneGOs)
                            {
                                Component[] comps = g.GetComponentsInChildren <Component>(true);
                                foreach (Component c in comps)
                                {
                                    if (c != null && c.GetType() != null && c.GetType().BaseType != null && c.GetType().BaseType == typeof(MonoBehaviour))
                                    {
                                        SerializedObject   so      = new SerializedObject(c);
                                        SerializedProperty p       = so.FindProperty("m_Script");
                                        string             path    = AssetDatabase.GetAssetPath(p.objectReferenceValue);
                                        ComponentNames     newComp = new ComponentNames(NameFromPath(path), GetNamespaceFromPath(path), path);
                                        newComp.usageSource.Add(scene);
                                        int index = sceneComponents.IndexOf(newComp);
                                        if (index == -1)
                                        {
                                            sceneComponents.Add(newComp);
                                        }
                                        else
                                        {
                                            if (!sceneComponents[index].usageSource.Contains(scene))
                                            {
                                                sceneComponents[index].usageSource.Add(scene);
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        foreach (ComponentNames c in existingComponents)
                        {
                            if (addedComponents.Contains(c))
                            {
                                continue;
                            }
                            if (prefabComponents.Contains(c))
                            {
                                continue;
                            }
                            if (sceneComponents.Contains(c))
                            {
                                continue;
                            }
                            notUsedComponents.Add(c);
                        }

                        addedComponents.Sort(SortAlphabetically);
                        prefabComponents.Sort(SortAlphabetically);
                        sceneComponents.Sort(SortAlphabetically);
                        notUsedComponents.Sort(SortAlphabetically);
                    }
                    break;
                }
            }
            break;

        case 1:
            if (GUILayout.Button("Search!"))
            {
                string[] allPrefabs = GetAllPrefabs();
                listResult = new List <string>();
                foreach (string prefab in allPrefabs)
                {
                    UnityEngine.Object o = AssetDatabase.LoadMainAssetAtPath(prefab);
                    GameObject         go;
                    try
                    {
                        go = (GameObject)o;
                        Component[] components = go.GetComponentsInChildren <Component>(true);
                        foreach (Component c in components)
                        {
                            if (c == null)
                            {
                                listResult.Add(prefab);
                            }
                        }
                    }
                    catch
                    {
                        Debug.Log("For some reason, prefab " + prefab + " won't cast to GameObject");
                    }
                }
            }
            break;
        }
        if (editorMode == 1 || selectedCheckType == 0)
        {
            if (listResult != null)
            {
                if (listResult.Count == 0)
                {
                    GUILayout.Label(editorMode == 0 ? (componentName == "" ? "Choose a component" : "No prefabs use component " + componentName) : ("No prefabs have missing components!\nClick Search to check again"));
                }
                else
                {
                    GUILayout.Label(editorMode == 0 ? ("The following prefabs use component " + componentName + ":") : ("The following prefabs have missing components:"));
                    scroll = GUILayout.BeginScrollView(scroll);
                    foreach (string s in listResult)
                    {
                        GUILayout.BeginHorizontal();
                        GUILayout.Label(s, GUILayout.Width(position.width / 2));
                        if (GUILayout.Button("Select", GUILayout.Width(position.width / 2 - 10)))
                        {
                            Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(s);
                        }
                        GUILayout.EndHorizontal();
                    }
                    GUILayout.EndScrollView();
                }
            }
        }
        else
        {
            showPrefabs = GUILayout.Toggle(showPrefabs, "Show prefab components");
            if (showPrefabs)
            {
                GUILayout.Label("The following components are attatched to prefabs:");
                DisplayResults(ref scroll1, ref prefabComponents);
            }
            showAdded = GUILayout.Toggle(showAdded, "Show AddComponent arguments");
            if (showAdded)
            {
                GUILayout.Label("The following components are AddComponent arguments:");
                DisplayResults(ref scroll2, ref addedComponents);
            }
            showScene = GUILayout.Toggle(showScene, "Show Scene-used components");
            if (showScene)
            {
                GUILayout.Label("The following components are used by scene objects:");
                DisplayResults(ref scroll3, ref sceneComponents);
            }
            showUnused = GUILayout.Toggle(showUnused, "Show Unused Components");
            if (showUnused)
            {
                GUILayout.Label("The following components are not used by prefabs, by AddComponent, OR in any scene:");
                DisplayResults(ref scroll4, ref notUsedComponents);
            }
        }
    }
Beispiel #44
0
    /// <summary>
    /// 通过文件路径读取obj文件
    /// </summary>
    /// <param name="filename">最好用绝对路径</param>
    /// <param name="scale">比例,默认1</param>
    /// <a href="http://www.manew.com/forum-47-453-1.html"></a>
    /// <returns></returns>
    public static Mesh ReadMeshByObj(string filename, float scale = 1f)
    {
        Mesh mesh = new Mesh();

        mesh.name = filename.Substring((int)Mathf.Max(filename.LastIndexOf("/"), filename.LastIndexOf("\\")) + 1);

        List <Vector3> verticies = new List <Vector3>();
        List <Vector2> uvs       = new List <Vector2>();
        List <Vector3> normals   = new List <Vector3>();
        List <int>     triangles = new List <int>();

        Vector2[] uUV   = null;
        Vector3[] uNorm = null;

        System.IO.StreamReader sr = new System.IO.StreamReader(filename);
        string line;
        int    lineNum = 0;

        float left = 1f, right = 0f, up = 0f, down = 1f;

        while ((line = sr.ReadLine()) != null)
        {
            lineNum++;
            if (line.StartsWith("v "))  //顶点
            {
                line = line.Substring(2).Trim();
                string[] pos = line.Split(' ');
                if (pos.Length == 3)
                {
                    verticies.Add(new Vector3(float.Parse(pos[0]) / scale, float.Parse(pos[1]) / scale, float.Parse(pos[2]) / scale));
                }
                else
                {
                    Debug.Log("第" + lineNum + "行数据故障:" + line);
                }
            }
            else if (line.StartsWith("vt "))    //纹理坐标
            {
                line = line.Substring(3).Trim();
                string[] pos = line.Split(' ');
                if (pos.Length == 2)
                {
                    uvs.Add(new Vector2(float.Parse(pos[0]), float.Parse(pos[1])));
                }
                else
                {
                    Debug.Log("第" + lineNum + "行数据故障:" + line);
                }
            }
            else if (line.StartsWith("vn "))
            {
                line = line.Substring(3).Trim();
                string[] pos = line.Split(' ');
                if (pos.Length == 3)
                {
                    normals.Add(new Vector3(float.Parse(pos[0]), float.Parse(pos[1]), float.Parse(pos[2])));
                }
                else
                {
                    Debug.Log("第" + lineNum + "行数据故障:" + line);
                }
            }
            else if (line.StartsWith("f "))
            {
                line = line.Substring(2).Trim();
                string[] pos = line.Split(' ');
                if (uUV == null)
                {
                    uUV = new Vector2[verticies.Count];
                }
                if (uNorm == null)
                {
                    uNorm = new Vector3[verticies.Count];
                }
                if (pos.Length == 3 || pos.Length == 4)
                {
                    if (pos[0].Contains("/"))
                    {
                        //预处理
                        for (int i = 0; i < pos.Length; i++)
                        {
                            pos[i].Replace("//", "/-/");
                            if (pos[i].EndsWith("/"))
                            {
                                pos[i] = pos[i] + "-";
                            }
                        }
                        int[] vIndexes = new int[pos.Length];

                        //解析
                        for (int i = 0; i < pos.Length; i++)
                        {
                            string[] v_vt_vn = pos[i].Split('/');
                            int      vIndex  = int.Parse(v_vt_vn[0]);
                            if (!v_vt_vn[1].Equals("-"))
                            {
                                int vtIndex = int.Parse(v_vt_vn[1]);
                                if (uUV[vIndex - 1].magnitude == 0)
                                {
                                    uUV[vIndex - 1] = uvs[vtIndex - 1];
                                }
                            }
                            if (!v_vt_vn[2].Equals("-"))
                            {
                                int vnIndex = int.Parse(v_vt_vn[2]);
                                if (uNorm[vIndex - 1].magnitude == 0)
                                {
                                    uNorm[vIndex - 1] = normals[vnIndex - 1];
                                }
                            }
                            vIndexes[i] = vIndex;
                        }
                        //加入三角形
                        for (int i = 0; i < 3; i++)
                        {
                            triangles.Add(vIndexes[i] - 1);
                        }
                        if (vIndexes.Length == 4)
                        {
                            triangles.Add(vIndexes[0] - 1);
                            triangles.Add(vIndexes[2] - 1);
                            triangles.Add(vIndexes[3] - 1);
                        }
                    }
                    else
                    {
                        triangles.Add(int.Parse(pos[0]) - 1);
                        triangles.Add(int.Parse(pos[1]) - 1);
                        triangles.Add(int.Parse(pos[2]) - 1);
                        if (pos.Length == 4)
                        {
                            triangles.Add(int.Parse(pos[0]) - 1);
                            triangles.Add(int.Parse(pos[2]) - 1);
                            triangles.Add(int.Parse(pos[3]) - 1);
                        }
                    }
                }
                else
                {
                    Debug.Log("第" + lineNum + "行数据故障:" + line);
                }
            }
        }
        mesh.vertices  = verticies.ToArray();
        mesh.normals   = uNorm;
        mesh.triangles = triangles.ToArray();
        mesh.uv        = uUV;//uvs.ToArray();
        mesh.RecalculateNormals();
        mesh.RecalculateTangents();
        mesh.RecalculateBounds();
        Debug.Log(string.Format("模型加载完成,面数:{0}点数:{1}", triangles.Count / 3, verticies.Count));
        Debug.LogFormat("UV:\nleft:{0}\tright:{1}\tup:{2}\tdown:{3}", left, right, up, down);
        return(mesh);
    }
Beispiel #45
0
    public void Begin(string sKind0)
    {
        //try
        //{
        string[] sArr;
        using (NSysDB.NTSQL.SQL1 query = new NSysDB.NTSQL.SQL1())
        { query.ReturnArr(out sArr); }
        string sFPathN      = sArr[0];
        string sFPathP      = sArr[1];
        string sFPathY      = sArr[2];
        string sPaPartition = sArr[3];

        //Console.WriteLine(sFPathN);

        //抓 D0401D*.* 的所有檔案
        foreach (string OkFName in System.IO.Directory.GetFileSystemEntries(sFPathN, sKind0 + "*.*"))
        {
            Console.WriteLine("檔案名稱1:" + OkFName);
            string sPgSN = DateTime.Now.ToString("yyyyMMddHHmmssfff");

            try
            {
                System.IO.File.Move(OkFName, OkFName.Replace(sFPathN, sFPathP));
                string OkFNameP = OkFName.Replace(sFPathN, sFPathP);

                string line    = "";
                int    counter = 0;

                using (System.IO.StreamReader txtFile = new System.IO.StreamReader(OkFNameP, System.Text.Encoding.Default))
                {
                    Console.WriteLine("檔案名稱2:" + OkFNameP);

                    using (NSysDB.NTSQL.SQL1 query = new NSysDB.NTSQL.SQL1())
                    {
                        //開始匯入
                        query.GoLogsAll(sPgSN, System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName, OkFName, "", "", 1);
                    }

                    while ((line = txtFile.ReadLine()) != null)
                    {
                        if (line.Trim() != "")
                        {
                            //Console.WriteLine(line);
                            string[] CutS  = { sPaPartition };
                            string[] charA = line.Split(CutS, StringSplitOptions.None);

                            //字串尾要分號//共13個分號
                            if (charA.Length == 13)
                            {
                                Console.WriteLine("折讓證明單號碼:" + charA[0].ToString());
                                //for (int i = 0; i < charA.Length-1; i++)
                                //{
                                //    Console.WriteLine("Index : {0}, 字串 : {1}", (i + 1), charA[i]);
                                //}

                                using (NSysDB.NTSQL.SQL1 query = new NSysDB.NTSQL.SQL1())
                                {
                                    try
                                    {
                                        if (query.Kind1SelectTbl3("D0401DSN", "MAllowanceNumber='" + charA[0].ToString() + "' And DAllowanceSequenceNumber='" + charA[10].ToString() + "'", "D0401D") == 0)
                                        {
                                            if (charA[1].ToString().Trim() != "" && charA[2].ToString().Trim() != "")
                                            {
                                                System.Collections.Hashtable data = new System.Collections.Hashtable();
                                                data["MAllowanceNumber"]        = charA[0].ToString().Trim();
                                                data["DOriginalInvoiceDate"]    = charA[1].ToString().Trim();
                                                data["DOriginalInvoiceNumber"]  = charA[2].ToString().Trim();
                                                data["DOriginalSequenceNumber"] = charA[3].ToString().Trim();
                                                data["DOriginalDescription"]    = charA[4].ToString().Trim();
                                                data["DQuantity"]  = charA[5].ToString().Trim();
                                                data["DUnit"]      = charA[6].ToString().Trim();
                                                data["DUnitPrice"] = charA[7].ToString().Trim();
                                                data["DAmount"]    = charA[8].ToString().Trim();
                                                data["DTax"]       = charA[9].ToString().Trim();

                                                data["DAllowanceSequenceNumber"] = charA[10].ToString().Trim();
                                                data["DTaxType"] = charA[11].ToString().Trim();

                                                data["TxFileNmae"] = OkFName.ToString().Trim();
                                                query.InsertDataNonKey("D0401D", data);
                                                data = null;
                                            }
                                            else
                                            {
                                                query.GoLogsAll(sPgSN, System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName, OkFName, "[MAllowanceNumber:" + charA[0].ToString().Trim() + "][DAllowanceSequenceNumber:" + charA[10].ToString().Trim() + "]", (counter + 1).ToString(), 17);

                                                query.GoToSTemp("D0401D", " MAllowanceNumber='" + charA[0].ToString() + "' ");
                                                query.GoToSTemp("D0401H", " MAllowanceNumber='" + charA[0].ToString() + "' ");
                                            }
                                        }
                                        else
                                        {
                                            query.GoLogsAll(sPgSN, System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName, OkFName, "[MAllowanceNumber:" + charA[0].ToString().Trim() + "][DAllowanceSequenceNumber:" + charA[10].ToString().Trim() + "]", (counter + 1).ToString(), 16);

                                            query.GoToSTemp("D0401D", " MAllowanceNumber='" + charA[0].ToString() + "' ");
                                            query.GoToSTemp("D0401H", " MAllowanceNumber='" + charA[0].ToString() + "' ");
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        query.GoLogsAll(sPgSN, System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName, OkFName, ex.ToString(), (counter + 1).ToString(), 11);

                                        query.GoToSTemp("D0401D", " MAllowanceNumber='" + charA[0].ToString() + "' ");
                                        query.GoToSTemp("D0401H", " MAllowanceNumber='" + charA[0].ToString() + "' ");
                                    }
                                }
                            }
                            else
                            {
                                using (NSysDB.NTSQL.SQL1 query = new NSysDB.NTSQL.SQL1())
                                {
                                    query.GoLogsAll(sPgSN, System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName, OkFName, "", (counter + 1).ToString(), 12);
                                }
                            }

                            Console.WriteLine("間隔數:" + charA.Length.ToString());
                            counter++;
                        }
                    }

                    using (NSysDB.NTSQL.SQL1 query = new NSysDB.NTSQL.SQL1())
                    {
                        //結束匯入
                        query.GoLogsAll(sPgSN, System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName, OkFName, "", "", 2);
                    }
                }
                Console.WriteLine("筆數:" + counter.ToString());

                System.IO.File.Move(OkFNameP, OkFNameP.Replace(sFPathP, sFPathY).Replace(".txt", "_" + sPgSN + ".txt"));
            }
            catch (Exception ex)
            {
                using (NSysDB.NTSQL.SQL1 query = new NSysDB.NTSQL.SQL1())
                {
                    query.GoLogsAll(sPgSN, System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName, OkFName, "此檔案已存於:" + sFPathP + " [" + ex + "]", "", 13);
                }
            }
            //try
            //{
            //    //檔案已存在的FileMove
            //    Console.WriteLine(OkFName);
            //    Console.WriteLine(OkFName.Replace(sFPathN, sFPathY));

            //    System.IO.File.Move(OkFName, OkFName.Replace(sFPathN, sFPathY) + sPgSN);
            //    //Exception未處理,檔案已存在時,無法建立該檔案。
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine("檔案已存在!!");
            //    using (NSysDB.NTSQL.SQL1 query = new NSysDB.NTSQL.SQL1())
            //    {
            //        query.GoLogsAll(sPgSN, System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName, OkFName, ex.ToString(), "", 13);
            //    }
            //}
        }

        //}
        //catch (Exception ex)
        //{
        //    using (NSysDB.NTSQL.SQL1 query = new NSysDB.NTSQL.SQL1())
        //    {
        //        // query.GoException(sPgSN, ex.ToString(), "[" + GetType().Assembly.Location + "] [" + System.Reflection.MethodInfo.GetCurrentMethod().ToString() + "]");
        //        query.GoLogsAll(sPgSN, System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName, "", ex.ToString(), "", 14);
        //    }
        //}
    }
Beispiel #46
0
    /* Methods */
    public bool initialize_data(string input_file)
    {
        try
        {
            System.IO.StreamReader sr = new System.IO.StreamReader(input_file);
            string[] line;

            /*If error occured*/
            if (sr == null)
            {
                return(false);
            }

            /*Declare total number of hemes in simulation
             * and assign member variables */
            transfer       = new double[nHemes, nHemes];
            injection      = new double[nHemes];
            ejection       = new double[nHemes];
            currentState   = new bool[nHemes];
            animationState = new bool[nHemes];

            rand = new System.Random();

            /*Start assigning rate values*/
            for (int i = 0; i < nHemes; i++)
            {
                for (int j = 0; j < nHemes; j++)
                {
                    if (i == j)
                    {
                        transfer[i, j] = 0;
                    }
                    else
                    {
                        line = sr.ReadLine().Split(new[] { ' ' });
                        if (line == null)
                        {
                            return(false);
                        }

                        int    row = int.Parse(line[0]) - 1;
                        int    col = int.Parse(line[1]) - 1;
                        double k   = Double.Parse(line[2]);
                        transfer[row, col] = k;
                    }
                }
            }

            /*Assign occupied booleans and injection/ejection rates*/
            for (int i = 0; i < nHemes; i++)
            {
                injection[i]    = 0;
                ejection[i]     = 0;
                currentState[i] = false;
            }

            //sample injection/ejection rates for debugging
            injection[0]         = 150000;
            ejection[nHemes - 1] = 150000;

            //initialize buffer queue
            buffer = new Queue <KineticMonteCarlo.Event>();
        }
        catch (Exception e)
        {
            Debug.Log(e.ToString());
            return(false);
        }

        return(true);
    }
Beispiel #47
0
    public static void Read(string Path)
    {
        var filestream = new System.IO.FileStream(Path,
                                                  System.IO.FileMode.Open,
                                                  System.IO.FileAccess.Read,
                                                  System.IO.FileShare.ReadWrite);
        var file = new System.IO.StreamReader(filestream, System.Text.Encoding.UTF8, true, 128);

        bool Found_Tracks_Header = false;

        Master.Measure_Length  = 0;
        Master.Measure_Lengths = new List <int>();
        bool Pattern_Read = false;
        //int PatternNo = 0;
        List <byte> Instrument_Order  = new List <byte>();
        List <byte> Instrument_Macros = new List <byte>();

        Master.Macros = new List <List <byte> >();
        Master.Instrument_Envelopes = new List <List <byte> >();
        for (int i = 0; i < Constants.Sound_Channels; i++)
        {
            Master.Measure_Order[i] = new List <byte>();
            Master.Final_Note[i]    = new List <byte>();
        }
        Master.Linear_Data = new List <byte>();
        for (int i = 0; i < Master.Measures.Length; i++)
        {
            Master.Measures[i] = new List <SequenceLine[]>();
        }

        List <SequenceLine>[] EntireMeasure;

        EntireMeasure = new List <SequenceLine> [Constants.Sound_Channels];
        for (int i = 0; i < EntireMeasure.Length; i++)
        {
            EntireMeasure[i] = new List <SequenceLine>();
        }

        string lineOfText;

        while ((lineOfText = file.ReadLine()) != null)
        {
            if (lineOfText == "# Tracks")
            {
                Found_Tracks_Header = true;
                continue;
            }
            else if (lineOfText.Contains("ORDER"))
            {
                int position = 11;
                for (int i = 0; i < Constants.Sound_Channels; i++)
                {
                    if (position >= lineOfText.Length)
                    {
                        break;
                    }
                    Master.Measure_Order[i].Add(Master.getByteFromText(lineOfText, position));
                    position += 3;
                }
            }
            else if (lineOfText.Contains("MACRO "))
            {
                int position = 6;
                if (Master.getByteFromDecimalText(lineOfText, ref position) == 0)
                {
                    position  = lineOfText.IndexOf(":");
                    position += 2;
                    byte        decimal_value = Master.getByteFromDecimalText(lineOfText, ref position);
                    List <byte> Macro_Values  = new List <byte>();
                    while (position < lineOfText.Length)
                    {
                        Macro_Values.Add(decimal_value);
                        decimal_value = Master.getByteFromDecimalText(lineOfText, ref position);
                    }
                    byte final_value = Macro_Values[Macro_Values.Count - 1];
                    for (int i = Macro_Values.Count; i < 0x100; i++)
                    {
                        Macro_Values.Add(final_value);                                                                  //continue to extend the volume envelope if the note continues.
                    }
                    Master.Macros.Add(Macro_Values);
                }
            }
            else if (lineOfText.Contains("INST2A03"))
            {
                int position = 8;
                Instrument_Order.Add(Master.getByteFromDecimalText(lineOfText, ref position));
                Instrument_Macros.Add(Master.getByteFromDecimalText(lineOfText, ref position));
            }
            else if (lineOfText.Contains("TRACK"))
            {
                string[] Splitted = lineOfText.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                Master.Speed = int.Parse(Splitted[2]);
            }
            else if (Found_Tracks_Header && !Pattern_Read)
            {
                if (lineOfText.Contains("PATTERN "))
                {
                    int Length = "PATTERN ".Length;
                    //PatternNo = MyConvert.HexToDec(lineOfText.Substring(Length, lineOfText.Length - Length));
                    Master.Measure_Length = 0;
                    Pattern_Read          = true;
                    continue;
                }
            }
            else if (Pattern_Read)
            {
                if (!string.IsNullOrEmpty(lineOfText))
                {
                    string[] Splitted_ = lineOfText.Split(new[] { " : " }, StringSplitOptions.RemoveEmptyEntries);
                    string[] Splitted  = new string[Splitted_.Length - 1];

                    Array.Copy(Splitted_, 1, Splitted, 0, Splitted.Length);
                    Splitted_ = null;

                    int SoundChannel = 0;
                    foreach (string Entry in Splitted)
                    {
                        string[]      Section = Entry.Split(' ');
                        string        Note = "", Instrument = "", Volume = "";
                        List <Effect> l_effect = new List <Effect>();
                        for (int i = 0; i < Section.Length; i++)
                        {
                            string Index = Section[i];
                            switch (i)
                            {
                            case 0:
                                Note = Index.Contains(".") ? "" : Index;
                                break;

                            case 1:
                                Instrument = Index.Contains(".") ? "" : Index;
                                break;

                            case 2:
                                Volume = Index.Contains(".") ? "" : Index;
                                break;

                            default:
                                string EffectName, Argument;
                                if (Section[i] != "...")
                                {
                                    EffectName = Index[0].ToString();
                                    Argument   = Index.Substring(1);
                                    l_effect.Add(new Effect(EffectName, Argument));
                                }
                                break;
                            }
                        }
                        EntireMeasure[SoundChannel++].Add(new SequenceLine(Note, Instrument, Volume, l_effect));
                        foreach (Effect sfx in l_effect)
                        {
                            if (sfx.Effect_Prefix == "D")
                            {
                                Pattern_Read = false;
                            }
                            if (sfx.Effect_Prefix == "B")
                            {
                                Master.Final_Loop_Measure = (byte)sfx.Argument;
                            }
                        }
                    }
                    Master.Measure_Length++;
                }
                else
                {
                    Pattern_Read = false;
                }
                if (!Pattern_Read)
                {
                    int sc = 0;
                    foreach (List <SequenceLine> s in EntireMeasure)
                    {
                        Master.Measures[sc++].Add(s.ToArray());
                    }
                    EntireMeasure = new List <SequenceLine> [Constants.Sound_Channels];
                    for (int i = 0; i < EntireMeasure.Length; i++)
                    {
                        EntireMeasure[i] = new List <SequenceLine>();
                    }
                    Pattern_Read = false;
                    Master.Measure_Lengths.Add(Master.Measure_Length);
                }
            }
        }
        for (int i = 0; i < Instrument_Order.Count; i++)
        {
            for (int j = 0; j < Instrument_Order.Count; j++)
            {
                if (Instrument_Order[j] == i)
                {
                    Master.Instrument_Envelopes.Add(Master.Macros[Instrument_Macros[j]]);
                    break;
                }
            }
        }
    }
Beispiel #48
0
    // Thread Pump for IRC messages
    private void _MessagePump()
    {
        ServerNumericReply snr = new ServerNumericReply();
        ChatMessage        msg = new ChatMessage();

        msg.Nick = Nick;
        snr.Nick = Nick;
        while (_ircTcpClient.Connected && _incomingStream.EndOfStream == false)
        {
            if (_ct.IsCancellationRequested)
            {
                break;
            }
            string _incoming = null;
            try
            {
                _incoming = _incomingStream.ReadLine();
            }
            catch (Exception e)
            {
                badimebot.Program.ConsoleError("Error Reading from server", e);
                System.Threading.Thread.Sleep(50);
                if (_ircTcpClient.Connected == false)
                {
                    lock (_lockobject)
                    {
                        _state = ConnectionState.Disconnected;
                    }
                    Reconnect();
                }
                else
                {
                    break;  // Connected but got a weird error, bail out
                }
            }
            if (_incoming == null)
            {
                badimebot.Program.ConsoleError("Read blank line from irc server");
                break;  // end?
            }
            irclog.WriteLine(_incoming);

            // Parse and fire events
            if (_incoming.StartsWith("PING"))
            {
                WriteToServerStream($"PONG {_incoming.Substring(5)}");
            }
            else
            if (snr.TryParse(_incoming))
            {
                if (snr.ReplyCode == 266)
                {
                    _server_message_connected = true;   // Set volatile flag that indicates connection complete and join established
                }
                if (_LookingforServerResponse && snr.ReplyCode == _LookingforServerResponseCode)
                {
                    _LookingforServerResponse = false;
                    _LookingforServerResponseEvent.Set();
                }
            }
            else
            if (_incoming.Contains("PRIVMSG") && msg.TryParse(_incoming))
            {
                if (msg.Channel == null)
                {
                    this.PrivateMessageReceived?.Invoke(this, new MessageArgs()
                    {
                        From = msg.From, Message = msg.Message
                    });
                }
                else
                {
                    this.ChannelMessageReceived?.Invoke(this, new MessageArgs()
                    {
                        From = msg.From, Message = msg.Message, Channel = msg.Channel
                    });
                }
            }
            else
            {
                // ??
                badimebot.Program.ConsoleError($"Unknown server message: {_incoming}");
            }

            //System.Threading.Thread.Sleep(20);
            System.Threading.Thread.Yield();
        }

        Console.WriteLine("Message pump finished");
    }
Beispiel #49
0
        static void Main(string[] args)
        {
            string          fileLocation = @"C:\Users\nikla\Documents\Visual_studio_code\Addreses.TXT";
            List <Contacts> contact      = new List <Contacts>();
            string          line;

            using (StreamReader read = new System.IO.StreamReader(fileLocation))
            {
                while ((line = read.ReadLine()) != null)
                {
                    string[] words = line.Split('#');
                    contact.Add(new Contacts(words[0], words[1], words[2], words[3], words[4]));
                }
                read.Close();
            }
            string userComand;

            do
            {
                Console.WriteLine("Write your comand: write 'help' to show commands:");
                userComand = Console.ReadLine();
                if (userComand == "add")
                {
                    Add(contact);
                }
                else if (userComand == "show")
                {
                    Show(contact);
                }
                else if (userComand == "save")
                {
                    Save(contact, fileLocation);
                }
                else if (userComand == "delete")
                {
                    Delete(contact);
                }
                else if (userComand == "quit")
                {
                    Console.WriteLine("Do you want to save? yes/no");
                    string ans = Console.ReadLine();
                    if (ans == "yes")
                    {
                        Save(contact, fileLocation);
                    }
                    Console.WriteLine("Good bye");
                }
                else if (userComand == "help")
                {
                    Console.WriteLine("Write 'save' to save your phone book to the pc.");
                    Console.WriteLine("Write 'delete' to delete a contact (remember to save after).");
                    Console.WriteLine("Write 'show' to show the contacts you have.");
                    Console.WriteLine("Write 'add' to add a contact to your contact list (remember to save).");
                    Console.WriteLine("Write 'quit' to quit the pogram obs it will ask you if you want to save or not.");
                }
                else
                {
                    Console.WriteLine("Unknown command: {0}", userComand);
                }
                Console.WriteLine();
            } while (userComand != "quit");
            Console.ReadKey();
        }
Beispiel #50
0
        public JsonResult cargarCSV(HttpPostedFileBase archivoCSV, int lineaNegocio)
        {
            List <string>        listaErrores = new List <string>();
            var                  hoy = DateTime.Now;
            IEnumerable <string> lineas = null;
            object               respuesta = null;
            int                  totalProcesados = 0;
            int                  lineaActual = 1;
            int                  contador = 0;
            bool                 status = false;
            string               ope, fact;
            string               exception = "Error, se presento un error inesperado.";

            try
            {
                List <string> csvData = new List <string>();
                using (System.IO.StreamReader reader = new System.IO.StreamReader(archivoCSV.InputStream, System.Text.Encoding.GetEncoding("ISO-8859-1")))
                {
                    while (!reader.EndOfStream)
                    {
                        csvData.Add(reader.ReadLine());
                    }
                }
                lineas = csvData.Skip(1);

                var datos = (from periodos in db.cargaDocumentoRoaming
                             where periodos.idDocumento == "TAPIN" & periodos.ordenCarga == "A" & periodos.estatusCarga == "PC"
                             group periodos by periodos.periodoCarga into g
                             orderby g.Key ascending
                             select new
                             { Id = g.Key, Periodo = g.Key }).FirstOrDefault();



                var _IdOperador = db.Operador
                                  .Select(p => p.Id_Operador)
                                  .ToArray();

                var _Acreedor = db.Acreedor
                                .Select(p => p.Acreedor1)
                                .ToArray();


                string Activo = "";
                String Valor  = "";

                using (TransactionScope scope = new TransactionScope())
                {
                    foreach (string ln in lineas)
                    {
                        string linea      = ln.Replace('%', ' ');
                        var    lineaSplit = linea.Split('|');
                        ++lineaActual;
                        if (lineaSplit.Count() == 14)
                        {
                            RoamingCancelacionCosto entidad = new RoamingCancelacionCosto();

                            try
                            {
                                contador++;
                                ope  = lineaSplit[2];
                                fact = lineaSplit[11];

                                Activo = ((!_IdOperador.Any(o => o == lineaSplit[3].ToUpper())) ? "0" : "1");

                                if (Activo == "1")
                                {
                                    Activo = ((!_Acreedor.Any(o => o == lineaSplit[6].ToUpper())) ? "0" : "1");
                                }

                                decimal importeMXNtest = 0;
                                decimal difProvFact    = 0;

                                entidad.BanderaConcepto     = lineaSplit[0];
                                entidad.NumeroProvision     = lineaSplit[1];
                                entidad.FechaContable       = datos.Periodo.ToString();
                                entidad.CuentaContable      = lineaSplit[2];
                                entidad.Indat               = lineaSplit[3];
                                entidad.Concepto            = lineaSplit[4];
                                entidad.Grupo               = lineaSplit[5];
                                entidad.Acreedor            = lineaSplit[6];
                                entidad.MontoProvision      = lineaSplit[7];
                                entidad.Moneda              = lineaSplit[8];
                                entidad.Periodo             = lineaSplit[9];
                                entidad.Tipo                = lineaSplit[10];
                                entidad.NumeroDocumentoSap  = lineaSplit[11];
                                entidad.FolioDocumento      = lineaSplit[12];
                                entidad.TipoCambioProvision = lineaSplit[13];
                                //entidad.ImporteMxn = lineaSplit[14];
                                //entidad.ImporteFactura = lineaSplit[15];
                                //entidad.DiferenciaProvisionFactura = lineaSplit[16];
                                //entidad.TipoCambioFactura = lineaSplit[17];
                                //entidad.ExcesoProvisionMxn = lineaSplit[18];
                                //Valor = lineaSplit[19];
                                //entidad.InsuficienciaProvisionMxn = Valor.Replace(",,", "");



                                importeMXNtest     = Convert.ToDecimal(entidad.MontoProvision) * Convert.ToDecimal(entidad.TipoCambioProvision);
                                entidad.ImporteMxn = Convert.ToString(importeMXNtest);

                                var monto = from montodock in db.RoamingDocumentoCosto
                                            where montodock.IdOperador == entidad.Indat & montodock.FolioDocumento == entidad.FolioDocumento
                                            & montodock.FechaConsumo == entidad.Periodo

                                            group montodock by new { montodock.FechaContable }

                                into mygroup
                                select mygroup.FirstOrDefault();

                                foreach (var elemento in monto)
                                {
                                    entidad.ImporteFactura = elemento.Monto;
                                }

                                difProvFact = Convert.ToDecimal(entidad.MontoProvision) + Convert.ToDecimal(entidad.ImporteFactura);
                                entidad.DiferenciaProvisionFactura = Convert.ToString(difProvFact);

                                var tipocambiotest = from tipoCamb in db.RoamingDocumentoCosto
                                                     where tipoCamb.FechaConsumo == entidad.Periodo & tipoCamb.IdOperador == entidad.Indat
                                                     & tipoCamb.FolioDocumento == entidad.FolioDocumento

                                                     group tipoCamb by new { tipoCamb.FechaContable }

                                into mygroup
                                select mygroup.FirstOrDefault();

                                foreach (var elemento in tipocambiotest)
                                {
                                    entidad.TipoCambioFactura = elemento.TipoCambio;
                                }

                                if (float.Parse(entidad.DiferenciaProvisionFactura) < 0)
                                {
                                    decimal excprov = 0;

                                    excprov = Convert.ToDecimal(entidad.DiferenciaProvisionFactura) * Convert.ToDecimal(entidad.TipoCambioProvision);

                                    entidad.ExcesoProvisionMxn = Convert.ToString(excprov);
                                }
                                else
                                {
                                    entidad.ExcesoProvisionMxn = "0";
                                }


                                if (Convert.ToDecimal(entidad.DiferenciaProvisionFactura) > 0)
                                {
                                    decimal insufiProvi = 0;
                                    insufiProvi = Convert.ToDecimal(entidad.DiferenciaProvisionFactura) * Convert.ToDecimal(entidad.TipoCambioFactura);
                                    entidad.InsuficienciaProvisionMxn = Convert.ToString(insufiProvi);
                                }
                                else
                                {
                                    entidad.InsuficienciaProvisionMxn = "0";
                                }

                                //entidad.InsuficienciaProvisionMxn = lineaSplit[18];


                                entidad.Activo       = Activo;
                                entidad.LineaNegocio = "1";
                                entidad.FechaCarga   = DateTime.Now;

                                var flujo = from consuImpo in db.RoamingDocumentoCosto
                                            where consuImpo.IdOperador == entidad.Indat & consuImpo.FolioDocumento == entidad.FolioDocumento
                                            group consuImpo by new { consuImpo.FechaContable }

                                into mygroup
                                select mygroup.FirstOrDefault();

                                foreach (var elemento in flujo)
                                {
                                    if (entidad.BanderaConcepto == "TARIFA")
                                    {
                                        entidad.FechaConsumoTarifa   = elemento.FechaConsumo;
                                        entidad.ImporteFacturaTarifa = elemento.MontoFacturado;
                                    }
                                }

                                totalProcesados++;

                                db.RoamingCancelacionCosto.Add(entidad);
                            }
                            catch (FormatException e)
                            {
                                if (e.Message == "String was not recognized as a valid DateTime.")
                                {
                                    listaErrores.Add("Línea " + lineaActual + ": Campo de Fecha con formato erróneo.");
                                }
                                else
                                {
                                    listaErrores.Add("Línea " + lineaActual + ": Campo con formato erróneo.");
                                }
                            }
                            catch (Exception)
                            {
                                listaErrores.Add("Línea " + lineaActual + ": Error desconocido. ");
                            }
                        }
                        else
                        {
                            listaErrores.Add("Línea " + lineaActual + ": Número de campos insuficiente.");
                        }
                    }
                    db.SaveChanges();
                    scope.Complete();
                    exception = "Datos cargados con éxito";
                    status    = true;
                }

                // LLenar fluctuacion
                if (status)
                {
                    db.Database.CommandTimeout = 3000;
                    db.sp_FluctuacionROM_Insert(DateTime.Parse(datos.Periodo), "COSTO", "FluctuacionCostoROM");

                    using (var anteriores = new Negocio.PeriodosAnteriores())
                        anteriores.CrearPeriodosAnteriores(db);
                }
            }
            catch (FileNotFoundException)
            {
                exception = "El archivo Selecionado aún no existe en el Repositorio.";
                status    = false;
            }
            catch (UnauthorizedAccessException)
            {
                exception = "No tiene permiso para acceder al archivo actual.";
                status    = false;
            }
            catch (IOException e) when((e.HResult & 0x0000FFFF) == 32)
            {
                exception = "Falta el nombre del archivo, o el archivo o directorio está en uso.";
                status    = false;
            }
            catch (TransactionAbortedException)
            {
                exception = "Transacción abortada. Se presentó un error.";
                status    = false;
            }
            catch (Exception err)
            {
                exception = "Error desconocido. " + err.InnerException.ToString();
                status    = false;
            }
            finally
            {
                respuesta = new
                {
                    success         = true,
                    results         = listaErrores,
                    mensaje         = exception,
                    totalProcesados = totalProcesados,
                    status          = status
                };
            }
            return(Json(respuesta, JsonRequestBehavior.AllowGet));
        }
        private string[] ReadCourses(string FileName)
        {
            // Local Variables
            int           ammount = 0;
            string        line;
            StringBuilder temp1 = new StringBuilder();
            StringBuilder temp2 = new StringBuilder();
            char          ch;
            int           num;
            int           course_now = 0;

            try
            {
                // Count the total courses
                System.IO.StreamReader file = new System.IO.StreamReader(FileName);
                while ((line = file.ReadLine()) != null)
                {
                    ammount++;
                }
                file.Close();

                Graph    g           = new Graph(ammount);
                string[] course_code = new string[ammount];

                // Read each course code
                System.IO.StreamReader files = new System.IO.StreamReader(FileName);
                while (!files.EndOfStream)
                {
                    ch = (char)files.Read();
                    if (ch != '.')
                    {
                        if (ch != ',')
                        {
                            temp1.Append(ch);
                        }
                        else
                        {
                            course_code[course_now] = temp1.ToString();
                            course_now++;
                            temp1.Length = 0;
                            while (ch != '.')
                            {
                                ch = (char)files.Read();
                            }
                            ch = (char)files.Read();
                            ch = (char)files.Read();
                        }
                    }
                    else
                    {
                        course_code[course_now] = temp1.ToString();
                        course_now++;
                        temp1.Length = 0;
                        ch           = (char)files.Read();
                        ch           = (char)files.Read();
                    }
                }
                files.Close();
                return(course_code);
            }
            catch (FileNotFoundException e)
            {
                return(null);
            }
        }
Beispiel #52
0
        public static bool ExecuteActions(List <Action> Actions)
        {
            bool bDistccResult = true;

            if (Actions.Count > 0)
            {
                // Time to sleep after each iteration of the loop in order to not busy wait.
                const float LoopSleepTime = 0.1f;

                int    MaxActionsToExecuteInParallel = 0;
                string UserDir              = Environment.GetEnvironmentVariable("HOME");
                string HostsInfo            = UserDir + "/.dmucs/hosts-info";
                System.IO.StreamReader File = new System.IO.StreamReader(HostsInfo);
                string Line = null;
                while ((Line = File.ReadLine()) != null)
                {
                    var HostInfo = Line.Split(' ');
                    if (HostInfo.Count() == 3)
                    {
                        int NumCPUs = 0;
                        if (System.Int32.TryParse(HostInfo [1], out NumCPUs))
                        {
                            MaxActionsToExecuteInParallel += NumCPUs;
                        }
                    }
                }
                File.Close();

                if (BuildConfiguration.bAllowDistccLocalFallback == false)
                {
                    Environment.SetEnvironmentVariable("DISTCC_FALLBACK", "0");
                }

                string DistccExecutable  = BuildConfiguration.DistccExecutablesPath + "/distcc";
                string GetHostExecutable = BuildConfiguration.DistccExecutablesPath + "/gethost";

                Log.TraceInformation("Performing {0} actions ({1} in parallel)", Actions.Count, MaxActionsToExecuteInParallel, DistccExecutable, GetHostExecutable);

                Dictionary <Action, ActionThread> ActionThreadDictionary = new Dictionary <Action, ActionThread>();
                int JobNumber = 1;
                using (ProgressWriter ProgressWriter = new ProgressWriter("Compiling source code...", false))
                {
                    int ProgressValue = 0;
                    while (true)
                    {
                        // Count the number of pending and still executing actions.
                        int NumUnexecutedActions = 0;
                        int NumExecutingActions  = 0;
                        foreach (Action Action in Actions)
                        {
                            ActionThread ActionThread        = null;
                            bool         bFoundActionProcess = ActionThreadDictionary.TryGetValue(Action, out ActionThread);
                            if (bFoundActionProcess == false)
                            {
                                NumUnexecutedActions++;
                            }
                            else if (ActionThread != null)
                            {
                                if (ActionThread.bComplete == false)
                                {
                                    NumUnexecutedActions++;
                                    NumExecutingActions++;
                                }
                            }
                        }

                        // Update the current progress
                        int NewProgressValue = Actions.Count + 1 - NumUnexecutedActions;
                        if (ProgressValue != NewProgressValue)
                        {
                            ProgressWriter.Write(ProgressValue, Actions.Count + 1);
                            ProgressValue = NewProgressValue;
                        }

                        // If there aren't any pending actions left, we're done executing.
                        if (NumUnexecutedActions == 0)
                        {
                            break;
                        }

                        // If there are fewer actions executing than the maximum, look for pending actions that don't have any outdated
                        // prerequisites.
                        foreach (Action Action in Actions)
                        {
                            ActionThread ActionProcess       = null;
                            bool         bFoundActionProcess = ActionThreadDictionary.TryGetValue(Action, out ActionProcess);
                            if (bFoundActionProcess == false)
                            {
                                if (NumExecutingActions < Math.Max(1, MaxActionsToExecuteInParallel))
                                {
                                    // Determine whether there are any prerequisites of the action that are outdated.
                                    bool bHasOutdatedPrerequisites = false;
                                    bool bHasFailedPrerequisites   = false;
                                    foreach (FileItem PrerequisiteItem in Action.PrerequisiteItems)
                                    {
                                        if (PrerequisiteItem.ProducingAction != null && Actions.Contains(PrerequisiteItem.ProducingAction))
                                        {
                                            ActionThread PrerequisiteProcess       = null;
                                            bool         bFoundPrerequisiteProcess = ActionThreadDictionary.TryGetValue(PrerequisiteItem.ProducingAction, out PrerequisiteProcess);
                                            if (bFoundPrerequisiteProcess == true)
                                            {
                                                if (PrerequisiteProcess == null)
                                                {
                                                    bHasFailedPrerequisites = true;
                                                }
                                                else if (PrerequisiteProcess.bComplete == false)
                                                {
                                                    bHasOutdatedPrerequisites = true;
                                                }
                                                else if (PrerequisiteProcess.ExitCode != 0)
                                                {
                                                    bHasFailedPrerequisites = true;
                                                }
                                            }
                                            else
                                            {
                                                bHasOutdatedPrerequisites = true;
                                            }
                                        }
                                    }

                                    // If there are any failed prerequisites of this action, don't execute it.
                                    if (bHasFailedPrerequisites)
                                    {
                                        // Add a null entry in the dictionary for this action.
                                        ActionThreadDictionary.Add(Action, null);
                                    }
                                    // If there aren't any outdated prerequisites of this action, execute it.
                                    else if (!bHasOutdatedPrerequisites)
                                    {
                                        if ((Action.ActionType == ActionType.Compile || Action.ActionType == ActionType.Link) && DistccExecutable != null && GetHostExecutable != null)
                                        {
                                            string NewCommandArguments = "--wait -1 \"" + DistccExecutable + "\" " + Action.CommandPath + " " + Action.CommandArguments;
                                            Action.CommandPath      = GetHostExecutable;
                                            Action.CommandArguments = NewCommandArguments;
                                        }

                                        ActionThread ActionThread = new ActionThread(Action, JobNumber, Actions.Count);
                                        JobNumber++;
                                        ActionThread.Run();

                                        ActionThreadDictionary.Add(Action, ActionThread);

                                        NumExecutingActions++;
                                    }
                                }
                            }
                        }

                        System.Threading.Thread.Sleep(TimeSpan.FromSeconds(LoopSleepTime));
                    }
                }

                Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats, TraceEventType.Information, "-------- Begin Detailed Action Stats ----------------------------------------------------------");
                Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats, TraceEventType.Information, "^Action Type^Duration (seconds)^Tool^Task^Using PCH");

                double TotalThreadSeconds = 0;

                // Check whether any of the tasks failed and log action stats if wanted.
                foreach (KeyValuePair <Action, ActionThread> ActionProcess in ActionThreadDictionary)
                {
                    Action       Action       = ActionProcess.Key;
                    ActionThread ActionThread = ActionProcess.Value;

                    // Check for pending actions, preemptive failure
                    if (ActionThread == null)
                    {
                        bDistccResult = false;
                        continue;
                    }
                    // Check for executed action but general failure
                    if (ActionThread.ExitCode != 0)
                    {
                        bDistccResult = false;
                    }
                    // Log CPU time, tool and task.
                    double ThreadSeconds = Action.Duration.TotalSeconds;

                    Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats,
                                    TraceEventType.Information,
                                    "^{0}^{1:0.00}^{2}^{3}^{4}",
                                    Action.ActionType.ToString(),
                                    ThreadSeconds,
                                    Path.GetFileName(Action.CommandPath),
                                    Action.StatusDescription,
                                    Action.bIsUsingPCH);

                    // Update statistics
                    switch (Action.ActionType)
                    {
                    case ActionType.BuildProject:
                        UnrealBuildTool.TotalBuildProjectTime += ThreadSeconds;
                        break;

                    case ActionType.Compile:
                        UnrealBuildTool.TotalCompileTime += ThreadSeconds;
                        break;

                    case ActionType.CreateAppBundle:
                        UnrealBuildTool.TotalCreateAppBundleTime += ThreadSeconds;
                        break;

                    case ActionType.GenerateDebugInfo:
                        UnrealBuildTool.TotalGenerateDebugInfoTime += ThreadSeconds;
                        break;

                    case ActionType.Link:
                        UnrealBuildTool.TotalLinkTime += ThreadSeconds;
                        break;

                    default:
                        UnrealBuildTool.TotalOtherActionsTime += ThreadSeconds;
                        break;
                    }

                    // Keep track of total thread seconds spent on tasks.
                    TotalThreadSeconds += ThreadSeconds;
                }

                Log.TraceInformation("-------- End Detailed Actions Stats -----------------------------------------------------------");

                // Log total CPU seconds and numbers of processors involved in tasks.
                Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats || BuildConfiguration.bPrintDebugInfo,
                                TraceEventType.Information, "Cumulative thread seconds ({0} processors): {1:0.00}", System.Environment.ProcessorCount, TotalThreadSeconds);
            }
            return(bDistccResult);
        }
Beispiel #53
0
        private void DeliveryForm_Load(object sender, EventArgs e)
        {
            worker = new Worker(this, 1);
#if _delivery
            mapctrl1 = new FleetManager.Map.MapCtrl(this);
#endif
            if (panel1.Controls.Count == 1)
            {
                panel1.Controls.RemoveAt(0);
            }

            panel1.Controls.Add(mapctrl1);

            try
            {
                if (!File.Exists(m_strDBConnectionPath))
                {
                    using (StreamWriter sw = new System.IO.StreamWriter(m_strDBConnectionPath, false, Encoding.Default))
                    {
                        sw.WriteLine("data source=192.168.0.201; database=fleet_db; user id=nickyjo; password=r023866677!; charset=utf8");
                        sw.Close();
                    }
                }

                using (StreamReader sr1 = new System.IO.StreamReader(m_strDBConnectionPath, Encoding.Default))
                {
                    while (sr1.Peek() >= 0)
                    {
                        string strTemp = sr1.ReadLine();


                        m_strDBConnectstring = strTemp;
                    }
                    sr1.Close();
                }

                if (m_strDBConnectstring == "")
                {
                    MessageBox.Show("DB connection file open 에러");
                    return;
                }
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine("FleetManager_MainForm_Load dbconnection file open  err :={0}", ex.Message.ToString());
            }


            cboRobotID.SelectedIndex = 3;

            if (onInitSql() == 0)
            {
                Data.Instance.isDBConnected = true;

                onDBRead_Robotlist("all");
                onRobots_WorkInfo_InitSet();
            }
            else
            {
                Data.Instance.isDBConnected = false;
                MessageBox.Show("데이타베이스 연결 에러, 점검후 사용하세요.");
                return;
            }
        }
        private Graph ReadFile(string FileName)
        {
            // Local Variables
            int           ammount = 0;
            string        line;
            StringBuilder temp1 = new StringBuilder();
            StringBuilder temp2 = new StringBuilder();
            char          ch;
            int           num;
            int           course_now = 0;

            // Count the total courses
            try
            {
                System.IO.StreamReader file = new System.IO.StreamReader(FileName);
                while ((line = file.ReadLine()) != null)
                {
                    ammount++;
                }
                file.Close();
                Graph    g           = new Graph(ammount);
                string[] course_code = new string[ammount];

                // Read each course code
                System.IO.StreamReader files = new System.IO.StreamReader(FileName);
                while (!files.EndOfStream)
                {
                    ch = (char)files.Read();
                    if (ch != '.')
                    {
                        if (ch != ',')
                        {
                            temp1.Append(ch);
                        }
                        else
                        {
                            course_code[course_now] = temp1.ToString();
                            course_now++;
                            temp1.Length = 0;
                            while (ch != '.')
                            {
                                ch = (char)files.Read();
                            }
                            ch = (char)files.Read();
                            ch = (char)files.Read();
                        }
                    }
                    else
                    {
                        course_code[course_now] = temp1.ToString();
                        course_now++;
                        temp1.Length = 0;
                        ch           = (char)files.Read();
                        ch           = (char)files.Read();
                    }
                }
                files.Close();

                // Read each course code pre-requisite
                course_now = 0;
                int sign = 0;
                System.IO.StreamReader filesn = new System.IO.StreamReader(FileName);
                while (!filesn.EndOfStream)
                {
                    ch = (char)filesn.Read();
                    if (ch != '.')
                    {
                        if (ch != ',')
                        {
                            temp2.Append(ch);
                        }
                        else
                        {
                            if (sign == 0)
                            {
                                sign         = 1;
                                temp2.Length = 0;
                            }
                            else
                            {
                                for (num = 0; num < ammount; num++)
                                {
                                    if (string.Equals(course_code[num], temp2.ToString()))
                                    {
                                        g.addEdges(num, course_now);
                                        num = ammount + 1;
                                    }
                                }
                                temp2.Length = 0;
                            }
                            ch = (char)filesn.Read();
                        }
                    }
                    else
                    {
                        if (sign == 0)
                        {
                            temp2.Length = 0;
                            course_now++;
                        }
                        else
                        {
                            sign = 0;
                            for (num = 0; num < ammount; num++)
                            {
                                if (string.Compare(course_code[num], temp2.ToString()) == 0)
                                {
                                    g.addEdges(num, course_now);
                                    num = ammount + 1;
                                }
                            }
                            temp2.Length = 0;
                            course_now++;
                        }
                    }
                }
                filesn.Close();
                return(g);
            }
            catch (FileNotFoundException e)
            {
                return(null);
            }
        }
Beispiel #55
0
        public void GetData(string csv)
        {
            if (File.Exists(csv))
            {
                System.IO.StreamReader file = new System.IO.StreamReader(csv);
                string line;

                while ((line = file.ReadLine()) != null)
                {
                    int j = 0;


                    Regex rx_fin = new Regex(@"fin");
                    Regex rx_5   = new Regex(@"5min");
                    Regex rx_10  = new Regex(@"10min");
                    Regex rx_15  = new Regex(@"15min");

                    List <dsunits_player> pl_list = new List <dsunits_player>();
                    string id        = null;
                    string player_id = null;
                    string bp        = null;
                    List <KeyValuePair <string, int> > bp_list = new List <KeyValuePair <string, int> >();
                    Dictionary <string, List <KeyValuePair <string, int> > > units = new Dictionary <string, List <KeyValuePair <string, int> > >();
                    int fin = 0;

                    foreach (string ent in line.Split(';'))
                    {
                        if (j == 0)
                        {
                            id = ent;
                        }
                        else
                        {
                            string[] entent = ent.Split(',');
                            if (entent.Length == 1)
                            {
                                if (bp != null)
                                {
                                    units.Add(bp, new List <KeyValuePair <string, int> >(bp_list));
                                    dsunits_player pl = new dsunits_player();
                                    pl.ID       = id;
                                    pl.PLAYERID = player_id;
                                    pl.UNITS    = new Dictionary <string, List <KeyValuePair <string, int> > >(units);
                                    pl_list.Add(pl);
                                    if (fin > 0)
                                    {
                                        pl.FIN = fin;
                                    }

                                    bp_list.Clear();
                                    units.Clear();
                                    player_id = null;
                                    bp        = null;
                                }
                                player_id = ent;
                            }
                            else
                            {
                                Match m_fin = rx_fin.Match(ent);
                                Match m_5   = rx_5.Match(ent);
                                Match m_10  = rx_10.Match(ent);
                                Match m_15  = rx_15.Match(ent);
                                if (m_fin.Success || m_5.Success || m_10.Success || m_15.Success)
                                {
                                    if (bp != null)
                                    {
                                        units.Add(bp, new List <KeyValuePair <string, int> >(bp_list));
                                        bp_list.Clear();
                                    }
                                    bp = entent[0];

                                    if (m_fin.Success)
                                    {
                                        fin = int.Parse(entent[1]);
                                    }
                                }
                                else
                                {
                                    if (bp != null && bp.Length > 1)
                                    {
                                        KeyValuePair <string, int> unit = new KeyValuePair <string, int>(entent[0], int.Parse(entent[1]));
                                        bp_list.Add(unit);
                                    }
                                }
                            }
                        }

                        j++;
                    }
                    if (bp != null)
                    {
                        dsunits_player plf = new dsunits_player();
                        plf.ID       = id;
                        plf.PLAYERID = player_id;
                        plf.UNITS    = new Dictionary <string, List <KeyValuePair <string, int> > >(units);
                        pl_list.Add(plf);
                    }
                    if (UNITLIST.ContainsKey(id))
                    {
                    }
                    else
                    {
                        UNITLIST.Add(id, pl_list);
                    }
                }
            }
        }
Beispiel #56
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OpenFileDialog ofd = new OpenFileDialog()
                {
                    Filter = "Text Files (*.txt) | *.txt; Excel Files (*.xls, *.xlsx) | *.xls, *.xlsx;"
                };
                ofd.ShowDialog();
                if (string.IsNullOrWhiteSpace(ofd.FileName))
                {
                    return;
                }

                currDateTime = DateTime.Now.ToString("yyyyMMddHHmmssFFF");
                currFileName = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\HB Factory Programs\\TextToSql\\" + currDateTime + ".txt";
                if (!File.Exists(currFileName))
                {
                    File.Create(currFileName).Close();
                }

                lblFilePath.Content = ofd.FileName;
                rtbOutput.AppendText(">> Clearing items list... ");
                items.Clear();
                rtbOutput.AppendText(Environment.NewLine);
                if (ofd.FileName.Contains(".txt") || ofd.FileName.Contains(".csv"))
                {
                    System.IO.StreamReader file = new System.IO.StreamReader(ofd.FileName);
                    string line;
                    while ((line = file.ReadLine()) != null)
                    {
                        bool          isEmpty   = string.IsNullOrWhiteSpace(tbParams.Text);
                        List <string> numParams = line.Split(',').ToList();
                        if (numParams.Count == 0)
                        {
                            rtbOutput.AppendText(">> Skipping blank line...\n");
                            WriteToTxt(">> Skipping blank line...\n");
                        }
                        else
                        {
                            if (isEmpty)
                            {
                                for (int i = 1; i <= numParams.Count; i++)
                                {
                                    tbParams.Text += "@param" + i;
                                    if (i != numParams.Count)
                                    {
                                        tbParams.Text += ",";
                                    }
                                }
                                rtbOutput.AppendText(">> " + param.Length + " paramater(s) detected!\n");
                                WriteToTxt(">> " + param.Length + " paramater(s) detected!\n");
                                rtbOutput.AppendText(">> Parameters: " + tbParams.Text + "\n");
                                WriteToTxt(">> Parameters: " + tbParams.Text + "\n");
                            }
                            string message = "";
                            message += ">> Adding ";

                            foreach (string s in numParams)
                            {
                                message += s + ", ";
                            }
                            message = message.Substring(0, message.Length - 2);
                            rtbOutput.AppendText(message + "\n");
                            WriteToTxt(message + "\n");
                            items.Add(numParams);
                        }
                    }
                    file.Close();
                }
                else if (ofd.FileName.Contains(".xls") || ofd.FileName.Contains(".xlsx"))
                {
                }
                else
                {
                    throw new Exception("File type not supported!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR!\n" + ex.Message + "\n" + ex.StackTrace);
            }
        }
Beispiel #57
0
        static List <Data> ParseType2(HttpClient client, string filePath, List <Site> sites)
        {
            Site site = GetFileSite(client, filePath, sites);

            if (site == null)
            {
                return(null);
            }

            char   splitter = ';';
            string line     = "EMPTY";

            Dictionary <string /*filecolumn name*/, Varoff> columnXVaroff = new Dictionary <string, Varoff>
            {
                { "Rivlevel from sensor, m", new Varoff {
                      VariableId = 2, OffsetTypeId = 0, OffsetValue = 0
                  } },
                { "Rivlevel BHS, m", null },
                { "AtmPress, mmHg", new Varoff {
                      VariableId = 1249, OffsetTypeId = 102, OffsetValue = 2
                  } },
                { "DewPoint, °C", new Varoff {
                      VariableId = 1350, OffsetTypeId = 102, OffsetValue = 2
                  } },
                { "Rhum, %", new Varoff {
                      VariableId = 1352, OffsetTypeId = 102, OffsetValue = 2
                  } },
                { "Prec, mm", new Varoff {
                      VariableId = 1360, OffsetTypeId = 102, OffsetValue = 2
                  } },
                { "TypePrec", new Varoff {
                      VariableId = -1023, OffsetTypeId = 102, OffsetValue = 2
                  } },                                                                            // Знак минус означает необх. перекодировки (текст->код)
                { "Temp, °C", new Varoff {
                      VariableId = 1300, OffsetTypeId = 102, OffsetValue = 2
                  } },
            };
            Dictionary <string, double> typePrecipitationXCode = new Dictionary <string, double>
            {
                { "нет осадков", 4 },
                { "жидкие", 1 },
                { "ледяной дождь", 6 },
                { "мокрый снег", 5 },
                { "твёрдые", 2 }
            };

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            System.IO.StreamReader sr = new System.IO.StreamReader(filePath, Encoding.GetEncoding("windows-1251"));//.UTF8);//.GetEncoding("windows-1251")) ;

            try
            {
                // READ HEADER

                line = sr.ReadLine();
                string[] cells = line.Split(splitter);

                if (cells[0] != "Datetime")
                {
                    throw new Exception("First column is not Datetime.");
                }

                List <Data> ret = new List <Data>();

                for (int i = 1; i < cells.Length; i++)
                {
                    if (!columnXVaroff.TryGetValue(cells[i], out Varoff varoff))
                    {
                        throw new Exception($"Unknown column {cells[i]}.");
                    }

                    ret.Add(new Data {
                        Site = site, Varoff = varoff, DateValues = varoff == null ? null : new List <DateValue>(100000)
                    });
                }

                // READ DATA BODY
                int iLineCount = 0;
                while (!sr.EndOfStream)
                {
                    iLineCount++;
                    line = sr.ReadLine().Trim();
                    if (string.IsNullOrEmpty(line))
                    {
                        continue;
                    }
                    cells = line.Split(splitter);

                    DateTime date = DateTime.Parse(cells[0]);

                    for (int i = 1; i < cells.Length; i++)
                    {
                        if (ret[i - 1].Varoff != null)
                        {
                            double value = double.NaN;
                            if (ret[i - 1].Varoff.VariableId < 0)
                            {
                                if (ret[i - 1].Varoff.VariableId == -1023)
                                {
                                    if (!typePrecipitationXCode.TryGetValue(cells[i].Trim(), out value))
                                    {
                                        throw new Exception($"Unknown string categorical value {cells[i].Trim()} in column #{i} for variableId ={ret[i - 1].Varoff.VariableId}.");
                                    }
                                }
                                else
                                {
                                    throw new Exception($"Unknown categorical value column #{i} for variableId ={ret[i - 1].Varoff.VariableId}.");
                                }
                            }
                            else
                            {
                                value = StrVia.ParseDouble(cells[i]);
                            }

                            if (double.IsNaN(value))
                            {
                                throw new Exception($"Value for date {date} in column #{i} for variableId ={ret[i - 1].Varoff.VariableId} is NaN.");
                            }

                            ret[i - 1].DateValues.Add(new DateValue {
                                Date = date, Value = value
                            });
                        }
                    }
                    //if (iLineCount == 10) break;
                }
                return(ret);
            }
            catch (Exception ex)
            {
                Console.WriteLine(line + "\n\n" + ex.ToString());
                return(null);
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
            }
        }
Beispiel #58
0
        /// <summary>
        /// Reads the local file.
        /// </summary>
        /// <returns>GeoJSONData in raw format.</returns>
        public GeoJSONData ReadLocalFile()
        {
            GeoJSONData data    = new GeoJSONData();
            string      content = "";

            using (var input = context.Assets.Open(FileName))
                using (StreamReader sr = new System.IO.StreamReader(input))
                {
                    string temp = sr.ReadLine();
                    while (true)
                    {
                        if (string.IsNullOrEmpty(temp))
                        {
                            break;
                        }
                        content += temp + "\n";
                        temp     = sr.ReadLine();
                    }
                }
            var geoData = new GeoJSONData();

            geoData.Data = content;
            var tempList = new List <VenueLocation>();

            using (var input = context.Assets.Open(FileName1))
                using (StreamReader sr = new System.IO.StreamReader(input))
                {
                    string temp      = sr.ReadLine();
                    var    tempList1 = new List <VenueLocation>();
                    while (true)
                    {
                        if (string.IsNullOrEmpty(temp))
                        {
                            break;
                        }
                        var subject = "";
                        var index   = 0;
                        for (int i = 0; i < temp.Length; i++, index++)
                        {
                            if (temp[i] != '[')
                            {
                                subject += temp[i];
                            }
                            else
                            {
                                index++;                         //skip over the '['
                                break;
                            }
                        }
                        var venue = "";
                        subject = new SpaceRemover(subject).RemovedSpaces;
                        for (int a = index; a < temp.Length; a++)
                        {
                            var ch = temp[a];
                            if (temp[a] == ']')
                            {
                                break;
                            }
                            else
                            {
                                venue += temp[index++];
                            }
                        }
                        var Sub = new Subject {
                            Name = subject
                        };
                        bool Added = false;
                        for (int i = 0; i < tempList.Count; i++)
                        {
                            if (tempList[i].Name == venue)
                            {
                                tempList[i].VenueSubjects.Add(Sub);
                                Added = true;
                            }
                        }
                        var tempVenueLoc = new VenueLocation {
                            Name = venue
                        };
                        tempVenueLoc.VenueSubjects.Add(Sub);
                        if (Added == false)
                        {
                            tempList.Add(tempVenueLoc);
                        }
                        temp = sr.ReadLine();
                    }
                }
            var result = string.Join(",", tempList);

            loc = tempList;
            return(geoData);
        }
Beispiel #59
0
        private void btnLeer_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.RestoreDirectory = true;
            openFileDialog1.CheckFileExists  = true;
            openFileDialog1.CheckPathExists  = true;
            openFileDialog1.Title            = "Buscar medición en formato csv";
            openFileDialog1.DefaultExt       = ".csv";
            openFileDialog1.Filter           = "archivos csv (*.csv)|*.csv";
            //openFileDialog1.ShowDialog();

            if (openFileDialog1.ShowDialog() == DialogResult.OK && openFileDialog1.ToString() != "")
            {
                if (File.Exists("" + openFileDialog1.FileName))
                {
                    string line;
                    int    counter = 0;

                    // Read the file and display it line by line.
                    System.IO.StreamReader file =
                        new System.IO.StreamReader(@"" + openFileDialog1.FileName);

                    List <DatosPilot> listaData = new List <DatosPilot>();


                    while ((line = file.ReadLine()) != null)
                    {
                        counter++;
                        int      cantidadColumnas = line.Split(',').Count();
                        string[] columnasCsv      = new string[cantidadColumnas];
                        int[]    columnasUsar     = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 15, 17, 18, 19, 20, 21 };
                        columnasCsv = line.Split(',');

                        DatosPilot filaData = new DatosPilot();

                        if (counter > 1 && counter <= 41)
                        {
                            // this.gridDatos.Rows.Add(1);
                            Random rnd = new Random();

                            for (var i = 0; i < cantidadColumnas; i++)
                            {
                                var texto = SacarTexto(line, i + 1);

                                switch (i)
                                {
                                case 1:
                                    filaData.Time = Convert.ToDateTime(texto);
                                    break;

                                case 2:
                                    filaData.Va = Convert.ToDecimal(texto);
                                    break;

                                case 3:
                                    filaData.Vb = Convert.ToDecimal(texto);
                                    break;

                                case 4:
                                    filaData.Vc = Convert.ToDecimal(texto);
                                    break;

                                case 5:
                                    filaData.Ia = Convert.ToDecimal(texto);
                                    break;

                                case 6:
                                    filaData.Ib = Convert.ToDecimal(texto);
                                    break;

                                case 7:
                                    filaData.Ic = Convert.ToDecimal(texto);
                                    break;

                                case 8:
                                    filaData.Frequency = Convert.ToDecimal(texto);
                                    break;

                                case 9:
                                    filaData.Pa = Convert.ToDecimal(texto);
                                    break;

                                case 10:
                                    filaData.Pb = Convert.ToDecimal(texto);
                                    break;

                                case 11:
                                    filaData.Pc = Convert.ToDecimal(texto);
                                    break;

                                case 15:
                                    filaData.TotalkW = Convert.ToDecimal(texto);
                                    break;

                                case 18:
                                    filaData.Pftot = Convert.ToDecimal(texto);
                                    break;

                                case 19:
                                    filaData.KwhRec = Convert.ToDecimal(texto);
                                    break;

                                case 20:
                                    filaData.KwhDel = Convert.ToDecimal(texto);
                                    break;

                                case 21:
                                    filaData.kVARhDel = Convert.ToDecimal(texto);
                                    break;

                                case 22:
                                    filaData.kVARhRec = Convert.ToDecimal(texto);
                                    break;

                                case 23:
                                    filaData.TotalkWh_del_Rec = (filaData.KwhRec - filaData.KwhDel);
                                    filaData.TotalkVARh       = (filaData.kVARhDel - filaData.kVARhRec);
                                    ////
                                    filaData.Rec_kW = (filaData.KwhRec * 4);
                                    filaData.Del_kW = (filaData.KwhDel * 4);
                                    double a = Convert.ToDouble(filaData.TotalkVARh);
                                    filaData.kVAh_rms = Convert.ToDecimal(a * 0.8);
                                    double b = Convert.ToDouble(filaData.KwhRec);
                                    filaData.Rec_kVAh = Convert.ToDecimal(b * 0.8);
                                    double c = Convert.ToDouble(filaData.KwhDel);
                                    filaData.Rec_kVAh = Convert.ToDecimal(c * 0.8);
                                    break;
                                }
                            }
                            listaData.Add(filaData);
                        }
                    }
                    var bindingList = new BindingList <DatosPilot>(listaData);
                    var source      = new BindingSource(bindingList, null);
                    gridDatos.DataSource = source;
                }
            }
        }
        static void Main(string[] args)
        {
            CollaborativeFiltering cF = new CollaborativeFiltering();

            Console.Write("\nEnter 1 for quality measure or 2 for Webserver: ");
            string input  = Console.ReadLine();
            int    choice = -1;
            bool   result = Int32.TryParse(input, out choice);

            if (!result)
            {
                choice = 1;
            }

            if (choice == 2)
            {
                while (true)
                {
                    IP_BASED = true;
                    var txtFiles = Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*Request.txt", SearchOption.AllDirectories);

                    foreach (string reqFile in txtFiles)
                    {
                        string fileName = reqFile.Substring(Directory.GetCurrentDirectory().Length + 1);

                        string[] requestUrls = File.ReadAllLines(reqFile);
                        string   ip          = "";

                        Regex           reg     = new Regex(@"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(Request)");
                        MatchCollection matches = reg.Matches(fileName);
                        if (matches.Count == 1)
                        {
                            ip = matches[0].Groups[1].Value;

                            System.IO.StreamReader file        = new System.IO.StreamReader(fileName);
                            List <string>          kickAssUrls = new List <string>();
                            string line;
                            while ((line = file.ReadLine()) != null)
                            {
                                kickAssUrls.Add(line);
                            }

                            file.Close();
                            File.Delete(reqFile);

                            List <Tuple <int, double> > predictions = cF.GetPredictionFast(kickAssUrls, ip);

                            predictions.Sort((a, b) => b.Item2.CompareTo(a.Item2));
                            File.Create(ip + "Response.txt").Dispose();
                            TextWriter tw = new StreamWriter(ip + "Response.txt");
                            foreach (Tuple <int, double> t in predictions)
                            {
                                Tuple <string, string, string, string> tuple = cF.GetTorrentDataFromMergeID(t.Item1);
                                tw.WriteLine(t.Item2 + " " + tuple.Item1 + " " + tuple.Item2 + " " + tuple.Item3 + " " + tuple.Item4);
                            }
                            tw.Close();
                        }
                    }
                }
            }
            else
            {
                // Measure recommendation quality
                //cF.CalculateMeanAbsoluteError();
                cF.CalculateRankEvaluation();
                Console.Read();

                // Or show some predictions
                cF.ShowFirstPredictions();
                Console.Read();
            }
        }