Example #1
0
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            if (visualization == false)
            {
                MessageBox.Show("Визуализация выключена!", "Error", MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }

            var str = "";
            //находим файл через диалог, читаем текст

            Stream fileStream =
                new FileStream(@"C:\Users\Denis\source\repos\PathFindingApp\PathFindingApp\29x29Maze.txt",
                               FileMode.Open);

            using (var sr = new StreamReader(fileStream))
            {
                str = sr.ReadToEnd();
            }

            fileStream.Close();
            var data = str.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            InitTable(data.Length, data[0].Length);

            GraphParser.ParsePanel(data, tableLayoutPanel2);
            backstageViewControl1.Close();
        }
Example #2
0
 // Чтение графа из строк файла.
 private Graph ReadGraph(HttpPostedFileBase upload)
 {
     // выделение строк из входного потока
     string[] fileLines = ReadFile(upload.InputStream);
     // парсинг строк
     return(GraphParser.ParseTxtFormat(fileLines));
 }
Example #3
0
        private void UpdateCurrentContent()
        {
            var nodeSelector = RestrictVisibility
                ? OriginalGraph.GetNodeSelector(SelectedNodeIds, NodeVisitStopFunction, NodeVisitAcceptFunction)
                : null;

            CurrentDotContent = OriginalGraph.ToDot(new DotFormatOptions {
                NodeSelector = nodeSelector
            });
            if (UpdateCurrentImage)
            {
                CurrentImage = GraphParser.GetGraphImage(CurrentDotContent);
            }
            CurrentDotLayoutContent = GraphParser.GetGraphLayoutDot(CurrentDotContent);
            CurrentLayoutGraph      = GraphParser.GetGraph(CurrentDotLayoutContent);

            if (CurrentWpfGraph != null)
            {
                CurrentWpfGraph.Changed -= CurrentWpfGraphChanged;
            }
            CurrentWpfGraph          = new WpfGraph(CurrentLayoutGraph, SelectedNodeIds);
            CurrentWpfGraph.Changed += CurrentWpfGraphChanged;

            if (IsConnectedComponentsEnabled)
            {
                CurrentConnectedComponents = GetConnectedComponents(CurrentLayoutGraph);
            }
        }
Example #4
0
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                var    nameValueCollection = (NameValueCollection)ConfigurationManager.GetSection("rrdbfileserver");
                string url = nameValueCollection["url"];

                rrdDbAccessInterface = new ServerAccessor(url);//"tcp://server:8100/GetRrdDbAdapter");
                //string channelName = context.Request.QueryString["c"];
                DateTime start = new DateTime(2005, 12, 19);
                DateTime end   = new DateTime(2006, 12, 12);
                //\Users\miknil\Documents\Visual Studio 2008\Projects\rrd4n\RRDConfigTool\
                string        databaseName = "car_day.rra";
                StringBuilder sb           = new StringBuilder();
                sb.AppendFormat("- --start \"{0}\" --end \"{1}\"", start.ToShortDateString(), end.ToShortDateString());
                sb.Append(" --imgformat PNG");
                sb.AppendFormat(" DEF:myruntime=\"{0}\":milage:AVERAGE", databaseName);
                sb.Append(" CDEF:mil=myruntime,86400,* LINE2:mil#FF0000 -w 800 -h 400 CDEF:km=myruntime,1000,*");
                sb.Append(" SDEF:value_sum=km,TOTAL  GPRINT:myruntime:TOTAL:\"usage {0}\"");
                GraphParser parser   = new GraphParser(sb.ToString());
                RrdGraphDef graphDef = parser.CreateGraphDef();

                RrdGraph     graph_1 = new RrdGraph(graphDef, rrdDbAccessInterface);
                RrdGraphInfo info    = graph_1.getRrdGraphInfo();
                MemoryStream ms      = new MemoryStream(info.getBytes());

                context.Response.ContentType = "image/png";
                context.Response.BinaryWrite(ms.ToArray());
            }
            catch (Exception ex)
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write(ex.Message);
            }
        }
Example #5
0
        private void openFile_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var str = "";

            //находим файл через диалог, читаем текст
            using (var ofd = new OpenFileDialog())
            {
                ofd.Filter      = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
                ofd.FilterIndex = 1;

                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    Stream fileStream = ofd.OpenFile();
                    using (var sr = new StreamReader(fileStream))
                    {
                        str = sr.ReadToEnd();
                    }

                    fileStream.Close();
                }
            }
            //разбиваем текст по строкам

            var data = str.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            if (data.Length > 50)
            {
                MessageBox.Show("Слишком большой лабиринт для редактирования!", "Error", MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }
            InitTable(data.Length, data[0].Length);

            GraphParser.ParsePanel(data, tableLayoutPanel2);
        }
Example #6
0
 public static void Main(string[] args)
 {
     using (var writer = new StreamWriter("stats.csv")
     {
         AutoFlush = true
     })
     {
         writer.WriteLine("fileName, cliqueCount, executionTime");
         var fileNames = Directory.EnumerateFiles(Directory.GetCurrentDirectory()).Where(n => n.Contains("clq"))
                         .ToArray();
         Parallel.ForEach(fileNames,
                          fileName =>
         {
             var graph     = GraphParser.ParseNewGraph(fileName);
             var algorithm = new CplexSolver(graph);
             var timer     = Stopwatch.StartNew();
             var result    = algorithm.FindMaxClique();
             lock (locker)
             {
                 writer.WriteLine(string.Join(", ", fileName, result.Count, timer.Elapsed));
             }
         });
     }
     Console.WriteLine("Done");
     Console.ReadKey(false);
 }
Example #7
0
 // ������ ����� �� ����� �����.
 private Graph ReadGraph(HttpPostedFileBase upload)
 {
     // ��������� ����� �� �������� ������
     string[] fileLines = ReadFile(upload.InputStream);
     // ������� �����
     return(GraphParser.ParseTxtFormat(fileLines));
 }
Example #8
0
        public void CanLoadGraphs(string inputFile, string outputFile)
        {
            var graph = GraphParser.Parse(inputFile);
            //assert that each line produced a node
            var count = File.ReadAllLines(inputFile).Count();

            Assert.AreEqual(graph.Count, count);
        }
    // Use this for initialization
    void Start()
    {
        int[] vertices = { 1, 2, 3, 4, 5 };
        int[,] edges = { { 1, 2 }, { 1, 3 }, { 1, 4 }, { 2, 3 }, { 3, 5 } };
        GameObject  go          = new GameObject();
        GraphParser graphParser = go.AddComponent <GraphParser>();

        graphParser.Parse(vertices, edges);
    }
Example #10
0
        public static GraphBlueprint ParseGraphFromString(string input, Func <string, string> includesFunc)
        {
            var gp = new GraphParser(input, includesFunc);
            var r  = gp.Parse();

            LastParsedIncludedSources = gp.IncludedSources;

            return(r);
        }
Example #11
0
        public void GraphParsingTest(string filename, int expectedVertices, int expectedEdges)
        {
            string filepath = AppDomain.CurrentDomain.BaseDirectory + @"..\..\Templates\" + filename + ".xmile";
            var    parser   = new GraphParser(filepath, false);
            var    graph    = parser.CreateGraph("DEFAULT");

            Assert.AreEqual(graph.VertexCount, expectedVertices);
            Assert.AreEqual(graph.EdgeCount, expectedEdges);
        }
        public void ReadListTest()
        {
            Graph g = GraphParser.ReadFile(@"D:\Documents\computing_science\scriptie\graphs\list_test.txt", 1);

            Assert.AreEqual(6, g.Vertices().Count);
            string s = g.ToString();

            Assert.AreEqual("0 -->  1 2\n1 -->  2\n2 --> \n3 -->  4 5\n4 -->  5\n5 -->  0\n", s);
        }
Example #13
0
        private IList <WpfGraph> GetConnectedComponents(IGraph graph)
        {
            var scc          = graph.GetStronglyConnectedComponents().Where(c => c.Count > 1).ToList();
            var sccGraphs    = scc.Select(graph.GetReducedGraph).ToList();
            var wpfGraphList = sccGraphs
                               .Select(g => new WpfGraph(GraphParser.GetGraphLayout(g.ToDot())))
                               .ToList();

            return(wpfGraphList);
        }
Example #14
0
        public void GeneticAlgorithmTets()
        {
            string[]              lines       = File.ReadAllLines("BarabasiAlbertGraph1_M2.txt");
            GraphParser           graphParser = new GraphParser();
            Graph                 graph       = graphParser.ParseSimpleTxtFormat(lines);
            GeneticAlgorithmCore  ga          = new GeneticAlgorithmCore(graph, 20, 0.4, 0.4);
            FindingVertexResponse result      = ga.StartAlgorithm();

            Console.WriteLine(result.R);
        }
Example #15
0
    void Start()
    {
        string fileName = "level";

        GraphParser.OpenFile(fileName);
        Graph graph = GraphParser.GetGraph();

        GraphView.Instance.Draw(graph);

        //Dictionary<Unit, List<Distance>> pathDictionary = graph.GetDistances();
    }
Example #16
0
        public override GraphBlueprint Process(GraphPackage input, ContentProcessorContext context)
        {
            var parser = new GraphParser(input.Content, x => input.Includes.FirstOrDefault(p => GraphBlueprint.IsIncludeMatch(p.Key, x)).Value);

            var gf = parser.Parse();

            BlueprintPreprocessor.ProcessGraph(gf);

            Console.WriteLine("Parsing file with " + gf.LevelNodes.Count + " node definitions");

            return(gf);
        }
Example #17
0
        public static GraphBlueprint ParseGraphFromFile(string f)
        {
            var path = Path.GetDirectoryName(f) ?? "";

            var includesFunc = GetIncludesFunc(f);

            var gp = new GraphParser(File.ReadAllText(f), includesFunc);
            var r  = gp.Parse();

            LastParsedIncludedSources = gp.IncludedSources;

            return(r);
        }
Example #18
0
        private void loadButton_Click(object sender, EventArgs e)
        {
            try
            {
                // "- --start \"" + startDateTime.ToString() + "\" --end \"" + endDateTime.ToString() + "\" --imgformat PNG DEF:myspeed=" + rrdPath + ":speed:AVERAGE LINE2:myspeed#FF0000"
                GraphParser parser   = new GraphParser(graphCommandTextBox.Text);
                RrdGraphDef graphDef = parser.CreateGraphDef();

                DateTime startDate = DateTime.MinValue;
                DateTime endDate   = DateTime.MinValue;
                string   startTimeString;
                string   endTimeString;
                if (DateTime.TryParse(startTimeTextBox.Text, out startDate))
                {
                    startTimeString = string.Format("{0}:{1} {2}{3}{4}", startDate.Hour, startDate.Minute, startDate.Year,
                                                    startDate.Month, startDate.Day);
                }
                else
                {
                    startTimeString = startTimeTextBox.Text;
                }

                if (DateTime.TryParse(endTimeTextBox.Text, out endDate))
                {
                    endTimeString = string.Format("{0}:{1} {2}{3}{4}", endDate.Hour, endDate.Minute, endDate.Year,
                                                  endDate.Month, endDate.Day);
                }
                else
                {
                    endTimeString = endTimeTextBox.Text;
                }

                long[] timeStamps = Util.getTimestamps(startTimeString, endTimeString);
                graphDef.setStartTime(timeStamps[0]);
                graphDef.setEndTime(timeStamps[1]);
                controller.ShowGraph(graphDef);
            }
            catch (FormatException ex)
            {
                MessageBox.Show("Wrong format. " + ex.Message);
            }
            catch (ArgumentException ex)
            {
                MessageBox.Show("Wrong graph definition. " + ex.Message);
            }
            catch (FileNotFoundException ex)
            {
                MessageBox.Show("Fail to load data from file. " + ex.Message);
            }
        }
Example #19
0
        static void Main(string[] args)
        {
            var graph   = GraphParser.Parse("dijkstraData.txt");
            var results = Search.CalculateShortestPaths(graph);

            var ids = new[] { 7, 37, 59, 82, 99, 115, 133, 165, 188, 197 };

            foreach (var id in ids)
            {
                Console.WriteLine($"id: {id}, distance: {results[id].Distance}");
            }

            Console.ReadLine();
        }
Example #20
0
        public void concurrencySampleGraphTwoTest()
        {
            foreach (SCCDetector detector in this.concurrentDetectors)
            {
                Graph g        = GraphParser.ReadFile(@"D:\Documents\computing_science\scriptie\graphs\test_graph2.txt", 4);
                Graph original = new Graph(g.GetMap());

                ResultSet results = detector.Compute(g);

                for (int i = 0; i < results.List.Count; i++)
                {
                    Assert.IsTrue(original.IsSCC(results.List[i]));
                }
            }
        }
Example #21
0
        static void Main(string[] args)
        {
            var parser         = new GraphParser(@"in.txt");
            var graph          = parser.ParseGraph();
            var result         = graph.FindCycles();
            var state          = result == null ? "A" : "N";
            var stringsToWrite = new List <string>();

            stringsToWrite.Add(state);
            if (result != null)
            {
                stringsToWrite.Add(string.Join(" ", result.OrderBy(n => n.NodeNumber).Select(n => n.NodeNumber)));
            }
            File.WriteAllLines(@"out.txt", stringsToWrite);
        }
Example #22
0
File: graph.cs Project: ningit/vaed
    public static int Main(string[] args)
    {
        if (args.Length != 1)
        {
            Console.Error.WriteLine("No input file.");

            return(3);
        }

        if (!File.Exists(args[0]))
        {
            Console.Error.WriteLine(args[0] + ": no such file.");
        }

        // Parses the file and calls Floyd algorithm

        try {
            var parser = new GraphParser();

            // Gets input data from file
            xreal [,] datos = parser.Parse(File.OpenText(args[0]));

            xreal[,] res = null;

            Console.WriteLine("Input data:");
            Console.WriteLine(String.Join("\t", parser.VertNames));

            PrintMatrix(datos);

            __default.Floyd(datos, out res);

            Console.WriteLine();
            Console.WriteLine("Output data:");

            PrintMatrix(res);
        }

        catch (Exception e)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.Error.WriteLine("Error: " + e.Message);
            Console.ResetColor();
        }

        return(0);
    }
        // �����, ������������ ��������� �������� ���� ������, �� ����
        // ����� ��������� ������ � ������
        protected override void Seed(GraphContext context)
        {
            string workPath = HostingEnvironment.MapPath("~");
            string folder   = "Graphs";

            foreach (var description in _graphDescriptions)
            {
                string   fullPath = Path.Combine(workPath, folder, description.FileName);
                string[] lines    = File.ReadAllLines(fullPath);
                Graph    graph    = GraphParser.ParseTxtFormat(lines);
                context.Graphs.Add(graph);
                graph.Name = description.GraphName;
                graph.R    = description.RealR;
                context.Graphs.Add(graph);
            }
            context.SaveChanges();
        }
Example #24
0
        public void CanCalculatePaths(string inputFile, string outputFile)
        {
            var ids       = new[] { 7, 37, 59, 82, 99, 115, 133, 165, 188, 197 };
            var distances = File.ReadAllLines(outputFile)
                            .First()
                            .Split('\t', ' ', ',')
                            .Where(n => !string.IsNullOrWhiteSpace(n))
                            .Select(int.Parse)
                            .ToList();
            var graph   = GraphParser.Parse(inputFile);
            var results = Search.CalculateShortestPaths(graph);

            for (int i = 0; i < ids.Length; i++)
            {
                Assert.AreEqual(distances[i], results[ids[i]].Distance);
            }
        }
Example #25
0
        public SimpleController()
        {
            if (Environment.GetCommandLineArgs().Length <= 1)
            {
                throw new ArgumentException("No filename argument given!");
            }
            var filename   = Environment.GetCommandLineArgs()[1];
            var dotContent = File.ReadAllText(filename);

            try {
                GraphParser.CheckSyntax(dotContent);
            } catch (Exception e) {
                throw new ArgumentException("Invalid graph syntax:" + Environment.NewLine + e.Message);
            }
            var graph       = GraphParser.GetGraph(dotContent);
            var layoutGraph = GraphParser.GetGraphLayout(graph.ToDot());

            Graph = new WpfGraph(layoutGraph);
        }
Example #26
0
 private void UpdateOriginalGraphFromDotContent()
 {
     try {
         var graph = GraphParser.GetGraph(OriginalDotContent);
         GraphParser.CheckSyntax(OriginalDotContent);
         OriginalGraph       = graph;
         ParseFailureMessage = "";
     } catch (Exception e) {
         ParseFailureMessage = e.Message;
     }
     if (OriginalGraph == null)
     {
         OriginalGraph = Graph.CreateGraph();
     }
     if (string.IsNullOrEmpty(ParseFailureMessage))
     {
         RestrictSelection();
         RaiseContentChanged();
     }
 }
Example #27
0
        private static void Main(string[] args)
        {
            var file = args.Length > 0 ? new FileInfo(args[0]) : new FileInfo(DefaultInputFile);

            if (!file.Exists)
            {
                throw new FileNotFoundException(FormattableString.Invariant($"File {file.FullName} not found!"));
            }

            var graph    = GraphParser.GetGraph(file);
            var graphDot = graph.ToDot();

            Console.Write(graphDot);
            Console.WriteLine("Press any key...");
            Console.ReadKey();

            try {
                var originalDot = file.OpenText().ReadToEnd();
                var initialDot  = GraphParser.GetGraphLayoutDot(originalDot);
                var reparsedDot = GraphParser.GetGraphLayoutDot(graphDot);
                var diff        = DiffHelper.GetDiff(initialDot, reparsedDot);
                //var initialReparsed = GraphParser.GraphParser.GetGraph(initialDot).ToDot();
                //var reparsedReparsed = GraphParser.GraphParser.GetGraph(reparsedDot).ToDot();
                //var diff = DiffHelper.GetDiff(initialReparsed, reparsedReparsed);
                Console.Clear();
                Console.Write(diff);
                Console.WriteLine("Press any key to generate outOriginal.png, out.png and layout.gv...");
                Console.ReadKey();

                GenerateOutput(originalDot, graphDot, reparsedDot);

                Console.Clear();
                Console.WriteLine("Press any key...");
                Console.ReadKey();
            } catch (Exception e) {
                Console.Clear();
                Console.Write(e.Message);
                Console.WriteLine("Press any key...");
                Console.ReadKey();
            }
        }
Example #28
0
        private static void Main(string[] args)
        {
#if DEBUG
            string filepath = AppDomain.CurrentDomain.BaseDirectory + @"..\..\Templates\Borneo.xmile";
#else
            if (args.Length != 1)
            {
                Console.WriteLine("Программе требуется один аргумент командной строки.");
                Exit(ErrorCode.ArgumentsError);
            }
            string filepath = args[0];
#endif
            Console.WriteLine("Выполнить валидацию XML? (Y/N)");
            ConsoleKey key            = Console.ReadKey(true).Key;
            bool       shouldValidate = key == ConsoleKey.Y;
#if !DEBUG
            try
#endif
            {
                Console.WriteLine("Парсинг графа...");
                var parser = new GraphParser(filepath, shouldValidate);
                var graph  = parser.CreateGraph("[GLOBAL]");
                Console.WriteLine("Граф считан.");

                Process(graph);
            }
#if !DEBUG
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                Exit(ErrorCode.Fail);
            }
#endif
            Exit(ErrorCode.Success);
        }
Example #29
0
 public static void load(string fileName, Graph graph, GraphParser parser)
 {
     StreamReader reader = null;
     try
     {
         reader = new StreamReader(File.Open(fileName, FileMode.Open));
         String line = "";
         while ((line = reader.ReadLine()) != null)
         {
             graph.add(parser(graph, line));
         }
     }
     catch (System.Exception e)
     {
         throw new BadFileFormatException("Unexpected error while parsing '" + fileName + "'.", e);
     }
     finally
     {
         if (reader != null)
         {
             reader.Close();
         }
     }
 }
Example #30
0
 private static Graph CreateFileGraph(string filename, string filetype, SCCDetector[] detectors, int threads)
 {
     return(filetype == "SNAP" ? GraphParser.ReadFileSNAP(filename, threads) : GraphParser.ReadFile(filename, threads));
 }
Example #31
0
        static void Main(string[] args)
        {
            DateTime EPOC = new DateTime(1970, 01, 1);
            long     startTimeInSeconds = 920804400;
            DateTime startTime          = EPOC.AddSeconds(startTimeInSeconds);
            long     endTimeInSeconds   = 920808000;
            string   rrdPath            = @"net_test.rrd";
            String   imgPath            = @"net_test.png";

            Console.WriteLine("== Starting demo");

            RrdDb        rrdDb;
            FetchRequest request;
            FetchData    fetchData;


            //List<FetchedData> unified = ReadAndUnifyData(@"C:\Development\CS_Project\rrd4n\RrDbTest\el.csv",
            //                                             new TimeSpan(0, 10, 0));

            bool createDb = true;

            if (createDb)
            {
                rrdDb = BuildRRd(rrdPath, startTime);
                Console.WriteLine(rrdDb.dump());
                rrdDb.close();
                //rrdDb = new RrdDb(rrdPath, false);

                int[] values = new int[] {
                    12345, 12357, 12363, 12363, 12363, 12373, 12383, 12393, 12399, 12405, 12411, 12415, 12420, 12422, 12423
                };

                //rrdtool update net_test.rrd 920804700:12345 920805000:12357 920805300:12363
                //rrdtool update net_test.rrd 920805600:12363 920805900:12363 920806200:12373
                //rrdtool update net_test.rrd 920806500:12383 920806800:12393 920807100:12399
                //rrdtool update net_test.rrd 920807400:12405 920807700:12411 920808000:12415
                //rrdtool update net_test.rrd 920808300:12420 920808600:12422 920808900:12423

                for (int i = 0; i < 15; i++)
                {
                    UpdateRRd(rrdPath, 920804700 + (i * 300), "speed", values[i]);
                }
                //rrdDb.close();

                // Read back test
                rrdDb = new RrdDb(rrdPath, true);
                Console.WriteLine("File reopen in read-only mode");
                Console.WriteLine("== Last update time was: " + rrdDb.getLastUpdateTime());
                Console.WriteLine("== Last info was: " + rrdDb.getInfo());

                // fetch data
                Console.WriteLine("== Fetching data");
                request = rrdDb.createFetchRequest(new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE), startTimeInSeconds, endTimeInSeconds);
                Console.WriteLine(request.dump());
                fetchData = rrdDb.fetchData(request);
                Console.WriteLine("== Data fetched. " + fetchData.getRowCount() + " points obtained");
                Console.WriteLine(fetchData.toString());
                Console.WriteLine("== Fetch completed");
            }


            DateTime startDateTime = rrd4n.Common.Util.getDate(920804400);
            DateTime endDateTime   = rrd4n.Common.Util.getDate(920808000);

            GraphParser parser = new GraphParser("net_speed_1.png --start \"" + startDateTime.ToString() + "\" --end \"" + endDateTime.ToString() + "\" --imgformat PNG DEF:myspeed=" + rrdPath + ":speed:AVERAGE LINE2:myspeed#FF0000");
            RrdGraphDef gDef_1 = parser.CreateGraphDef();

            RrdDbAccessInterface rrdDbAccess = container["databaseaccessor.local"] as RrdDbAccessInterface;
            RrdGraph             graph_1     = new RrdGraph(gDef_1, rrdDbAccess);

            // Create graph
            // rrdtool graph net_speed.png --start 920804400 --end 920808000
            //  DEF:myspeed=net_test.rrd:speed:AVERAGE
            //  LINE2:myspeed#FF0000
            //  --font "DEFAULT:0:C:\Windows\fonts\cour.ttf"
            Console.WriteLine("Creating graph ");
            RrdGraphDef gDef = new RrdGraphDef();

            gDef.setWidth(IMG_WIDTH);
            gDef.setHeight(IMG_HEIGHT);
            gDef.setFilename(imgPath);
            gDef.setStartTime(startTimeInSeconds);
            gDef.setEndTime(endTimeInSeconds);
            gDef.setTitle("Speed");
            //            gDef.setVerticalLabel("temperature");
            gDef.datasource("myspeed", rrdPath, "speed", new rrd4n.Common.ConsolFun(rrd4n.Common.ConsolFun.ConsolFunTypes.AVERAGE));
            gDef.line("myspeed", Color.Red, "My sPeedj", 2);
            gDef.hrule(0.02, Color.Red, "Maximum 200", 3);

            //            gDef.print("shade", new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE), "avgShade = %.3f%S\\r");
            //            gDef.setImageInfo("<img src='%s' width='%d' height = '%d'>");
            gDef.setPoolUsed(false);
            gDef.setImageFormat("png");
            //Console.WriteLine("Rendering graph " + rrd4n.Common.Util.getLapTime());
            // create graph finally
            RrdGraph graph = new RrdGraph(gDef, rrdDbAccess);

            // Create bar chart test graph
            //rrdtool graph speed3.png --start 920804400 --end 920808000 --vertical-label km/h DEF:myspeed=test.rrd:speed:AVERAGE "CDEF:kmh=myspeed,3600,*" CDEF:fast=kmh,100,GT,kmh,0,IF CDEF:good=kmh,100,GT,0,kmh,IF HRULE:100#0000FF:"Maximum allowed" AREA:good#00FF00:"Good speed" AREA:fast#FF0000:"Too fast" --font "DEFAULT:0:C:\Windows\fonts\cour.ttf"
            imgPath = @"net_test_bar.png";

            Console.WriteLine("Creating bar graph ");
            gDef = new RrdGraphDef();
            gDef.setWidth(IMG_WIDTH);
            gDef.setHeight(IMG_HEIGHT);
            gDef.setFilename(imgPath);
            gDef.setStartTime(startTimeInSeconds);
            gDef.setEndTime(endTimeInSeconds + 900);
            gDef.setTitle("Speed");
            gDef.setVerticalLabel("km/h");
            //DEF:myspeed=test.rrd:speed:AVERAGE
            gDef.datasource("myspeed", rrdPath, "speed", new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE));
            //"CDEF:kmh=myspeed,3600,*"
            gDef.datasource("kmh", "myspeed,3600,*");
            //CDEF:fast=kmh,100,GT,kmh,0,IF
            gDef.datasource("fast", "kmh,100,GT,kmh,0,IF");
            //CDEF:good=kmh,100,GT,0,kmh,IF HRULE:100#0000FF:"Maximum allowed" AREA:good#00FF00:"Good speed" AREA:fast#FF0000:"Too fast"
            gDef.datasource("good", "kmh,100,GT,0,kmh,IF");
            //HRULE:100#0000FF:"Maximum allowed"
            gDef.hrule(100, Color.Red, "Maximum allowed", 3);
            gDef.hrule(200, Color.Red, "Maximum 200", 3);
            // AREA:good#00FF00:"Good speed"
            gDef.area("good", Color.Green, "Good speed");
            // AREA:fast#FF0000:"Too fast"
            gDef.area("fast", Color.Red, "Too fast");
            gDef.setPoolUsed(false);
            gDef.setImageFormat("png");
            //Console.WriteLine("Rendering graph " + Util.getLapTime());
            // create graph finally
            graph = new RrdGraph(gDef, rrdDbAccess);

            //rrdtool graph speed4.png --start 920804400 --end 920808000 --vertical-label km/h DEF:myspeed=test.rrd:speed:AVERAGE CDEF:nonans=myspeed,UN,0,myspeed,IF CDEF:kmh=nonans,3600,* CDEF:fast=kmh,100,GT,100,0,IF CDEF:over=kmh,100,GT,kmh,100,-,0,IF CDEF:good=kmh,100,GT,0,kmh,IF HRULE:100#0000FF:"Maximum allowed" AREA:good#00FF00:"Good speed" AREA:fast#550000:"Too fast"  STACK:over#FF0000:"Over speed" --font "DEFAULT:0:C:\Windows\fonts\cour.ttf"
            Console.WriteLine("Creating stack graph ");
            imgPath = @"net_test_stack.png";
            gDef    = new RrdGraphDef();
            gDef.setWidth(IMG_WIDTH);
            gDef.setHeight(IMG_HEIGHT);
            gDef.setFilename(imgPath);
            gDef.setStartTime(startTimeInSeconds + 300);
            gDef.setEndTime(endTimeInSeconds + 1200);
            gDef.setTitle("Speed");
            //--vertical-label km/h
            gDef.setVerticalLabel("km/h");
            // DEF:myspeed=test.rrd:speed:AVERAGE
            gDef.datasource("myspeed", rrdPath, "speed", new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE));
            // CDEF:nonans=myspeed,UN,0,myspeed,IF
            gDef.datasource("nonans", "myspeed,UN,0,myspeed,IF");
            //CDEF:kmh=nonans,3600,*
            gDef.datasource("kmh", "nonans,3600,*");
            //CDEF:fast=kmh,100,GT,100,0,IF
            gDef.datasource("fast", "kmh,100,GT,100,0,IF");
            //CDEF:over=kmh,100,GT,kmh,100,-,0,IF
            gDef.datasource("over", "kmh,100,GT,kmh,100,-,0,IF");
            //CDEF:good=kmh,100,GT,0,kmh,IF
            gDef.datasource("good", "kmh,100,GT,0,kmh,IF");
            //HRULE:100#0000FF:"Maximum allowed"
            gDef.hrule(100, Color.Blue, "Maximum allowed", 3);
            // AREA:good#00FF00:"Good speed"
            gDef.area("good", Color.Green, "Good speed");
            // AREA:fast#550000:"Too fast"
            gDef.area("fast", Color.Black, "Too fast");
            //STACK:over#FF0000:"Over speed"
            gDef.stack("over", Color.Red, "Over speed");

            gDef.setPoolUsed(false);
            gDef.setImageFormat("png");
            //Console.WriteLine("Rendering graph " + Util.getLapTime());
            // create graph finally
            graph = new RrdGraph(gDef, rrdDbAccess);



            long startMillis = DateTime.Now.Millisecond;

            return;
            //if (args.Length > 0)
            //{
            //   Console.WriteLine("Setting default backend factory to " + args[0]);
            //   RrdDb.setDefaultFactory(args[0]);
            //}
            //long start = START;
            //long end = END;
            ////rrdPath = Util.getRrd4nDemoPath(FILE + ".rrd");
            ////String xmlPath = Util.getRrd4nDemoPath(FILE + ".xml");
            ////String rrdRestoredPath = Util.getRrd4nDemoPath(FILE + "_restored.rrd");
            ////imgPath = Util.getRrd4nDemoPath(FILE + ".png");
            ////String logPath = Util.getRrd4nDemoPath(FILE + ".log");
            ////PrintWriter log = new PrintWriter(new BufferedOutputStream(new FileOutputStream(logPath, false)));
            //// creation
            ////Console.WriteLine("== Creating RRD file " + rrdPath);
            ////RrdDef rrdDef = new RrdDef(rrdPath, start - 1, 300);
            ////rrdDef.addDatasource("sun", new DsType(DsType.DsTypes.GAUGE), 600, 0, Double.NaN);
            ////rrdDef.addDatasource("shade", new DsType(DsType.DsTypes.GAUGE), 600, 0, Double.NaN);
            ////rrdDef.addArchive(new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE), 0.5, 1, 600);
            ////rrdDef.addArchive(new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE), 0.5, 6, 700);
            ////rrdDef.addArchive(new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE), 0.5, 24, 775);
            ////rrdDef.addArchive(new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE), 0.5, 288, 797);
            ////rrdDef.addArchive(new ConsolFun(ConsolFun.ConsolFunTypes.MAX), 0.5, 1, 600);
            ////rrdDef.addArchive(new ConsolFun(ConsolFun.ConsolFunTypes.MAX), 0.5, 6, 700);
            ////rrdDef.addArchive(new ConsolFun(ConsolFun.ConsolFunTypes.MAX), 0.5, 24, 775);
            ////rrdDef.addArchive(new ConsolFun(ConsolFun.ConsolFunTypes.MAX), 0.5, 288, 797);
            ////Console.WriteLine(rrdDef.dump());
            //////log.Console.WriteLine(rrdDef.dump());
            ////Console.WriteLine("Estimated file size: " + rrdDef.getEstimatedSize());
            ////RrdDb rrdDb = new RrdDb(rrdDef);
            ////Console.WriteLine("== RRD file created.");
            ////if (rrdDb.getRrdDef().equals(rrdDef))
            ////{
            ////    Console.WriteLine("Checking RRD file structure... OK");
            ////}
            ////else
            ////{
            ////    Console.WriteLine("Invalid RRD file created. This is a serious bug, bailing out");
            ////    return;
            ////}
            ////rrdDb.close();
            ////Console.WriteLine("== RRD file closed.");

            ////// update database
            ////GaugeSource sunSource = new GaugeSource(1200, 20);
            ////GaugeSource shadeSource = new GaugeSource(300, 10);
            ////Console.WriteLine("== Simulating one month of RRD file updates with step not larger than " +
            ////        MAX_STEP + " seconds (* denotes 1000 updates)");
            ////long t = start;
            ////int n = 0;
            ////rrdDb = new RrdDb(rrdPath);
            ////Sample sample = rrdDb.createSample();

            ////while (t <= end + 86400L)
            ////{
            ////    sample.setTime(t);
            ////    sample.setValue("sun", sunSource.getValue());
            ////    sample.setValue("shade", shadeSource.getValue());
            ////    //log.Console.WriteLine(sample.dump());
            ////    sample.update();
            ////    t += (long)(RANDOM.NextDouble() * MAX_STEP) + 1;
            ////    if (((++n) % 1000) == 0)
            ////    {
            ////        Console.Write("*");
            ////    }
            ////}

            ////rrdDb.close();

            ////Console.WriteLine("");
            ////Console.WriteLine("== Finished. RRD file updated " + n + " times");

            //// test read-only access!
            //rrdDb = new RrdDb(rrdPath, true);
            //Console.WriteLine("File reopen in read-only mode");
            //Console.WriteLine("== Last update time was: " + rrdDb.getLastUpdateTime());
            //Console.WriteLine("== Last info was: " + rrdDb.getInfo());

            //// fetch data
            //Console.WriteLine("== Fetching data for the whole month");
            //request = rrdDb.createFetchRequest(new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE), start, end);
            //Console.WriteLine(request.dump());
            ////  log.Console.WriteLine(request.dump());
            //fetchData = request.fetchData();
            //Console.WriteLine("== Data fetched. " + fetchData.getRowCount() + " points obtained");
            //Console.WriteLine(fetchData.toString());
            //Console.WriteLine("== Dumping fetched data to XML format");
            ////  Console.WriteLine(fetchData.exportXml());
            //Console.WriteLine("== Fetch completed");

            //// dump to XML file
            //Console.WriteLine("== Dumping RRD file to XML file " + xmlPath + " (can be restored with RRDTool)");
            ////  rrdDb.exportXml(xmlPath);
            //Console.WriteLine("== Creating RRD file " + rrdRestoredPath + " from XML file " + xmlPath);
            ////  RrdDb rrdRestoredDb = new RrdDb(rrdRestoredPath, xmlPath);

            //// close files
            //Console.WriteLine("== Closing both RRD files");
            //rrdDb.close();
            //Console.WriteLine("== First file closed");
            ////  rrdRestoredDb.close();
            //Console.WriteLine("== Second file closed");

            //// create graph
            //Console.WriteLine("Creating graph " + Util.getLapTime());
            //Console.WriteLine("== Creating graph from the second file");
            //gDef = new RrdGraphDef();
            //gDef.setWidth(IMG_WIDTH);
            //gDef.setHeight(IMG_HEIGHT);
            //gDef.setFilename(imgPath);
            //gDef.setStartTime(start);
            //gDef.setEndTime(end);
            //gDef.setTitle("Temperatures in May 2003");
            //gDef.setVerticalLabel("temperature");
            //gDef.datasource("sun", rrdPath/*rrdRestoredPath*/, "sun", new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE));
            //gDef.datasource("shade", rrdPath/*rrdRestoredPath*/, "shade", new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE));
            //gDef.datasource("median", "sun,shade,+,2,/");
            //gDef.datasource("diff", "sun,shade,-,ABS,-1,*");
            //gDef.datasource("sine", "TIME," + start + ",-," + (end - start) +
            //        ",/,2,PI,*,*,SIN,1000,*");
            //gDef.line("sun", Color.Green, "sun temp");
            //gDef.line("shade", Color.Blue, "shade temp");
            //gDef.line("median", Color.Magenta, "median value");
            //gDef.area("diff", Color.Yellow, "difference\\r");
            //gDef.line("diff", Color.Red, null);
            //gDef.line("sine", Color.Cyan, "sine function demo\\r");
            //gDef.hrule(2568, Color.Green, "hrule");
            //gDef.vrule((start + 2 * end) / 3, Color.Magenta, "vrule\\r");
            //gDef.gprint("sun", new ConsolFun(ConsolFun.ConsolFunTypes.MAX), "maxSun = %.3f%s");
            //gDef.gprint("sun", new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE), "avgSun = %.3f%S\\r");
            //gDef.gprint("shade", new ConsolFun(ConsolFun.ConsolFunTypes.MAX), "maxShade = %.3f%S");
            //gDef.gprint("shade", new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE), "avgShade = %.3f%S\\r");
            //gDef.print("sun", new ConsolFun(ConsolFun.ConsolFunTypes.MAX), "maxSun = %.3f%s");
            //gDef.print("sun", new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE), "avgSun = %.3f%S\\r");
            //gDef.print("shade", new ConsolFun(ConsolFun.ConsolFunTypes.MAX), "maxShade = %.3f%S");
            //gDef.print("shade", new ConsolFun(ConsolFun.ConsolFunTypes.AVERAGE), "avgShade = %.3f%S\\r");
            //gDef.setImageInfo("<img src='%s' width='%d' height = '%d'>");
            //gDef.setPoolUsed(false);
            //gDef.setImageFormat("png");
            //Console.WriteLine("Rendering graph " + Util.getLapTime());
            //// create graph finally
            //graph = new RrdGraph(gDef);

            //Console.WriteLine(graph.getRrdGraphInfo().dump());
            //Console.WriteLine("== Graph created " + Util.getLapTime());
            //// locks info
            ////Console.WriteLine("== Locks info ==");
            ////Console.WriteLine(RrdSafeFileBackend.getLockInfo());
            //// demo ends
            ////log.close();
            //Console.WriteLine("== Demo completed in " +
            //        ((DateTime.Now.Millisecond - startMillis) / 1000.0) + " sec");
        }
 public void Initialize()
 {
     this.graphParser = new GraphParser();
 }