private void button1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            var ControllerIPAddress = new IPAddress(new byte[] { 192, 168, 0, 2 });
            var ControllerPort = 40001;
            var ControllerEndPoint = new IPEndPoint(ControllerIPAddress, ControllerPort);
            _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            var header = "@";
            var command = "00C";
            var checksum = "E3";
            var end = "\r\n";
            var data = header + command + checksum + end;
            byte[] bytes = new byte[1024];

            //Start Connect
            _connectDone.Reset();
            watch.Start();
            _client.BeginConnect(ControllerIPAddress, ControllerPort, new AsyncCallback(ConnectCallback), _client);
            //wait 2s
            _connectDone.WaitOne(2000, false);

            var text = (_client.Connected) ? "ok" : "ng";
            richTextBox1.AppendText(text + "\r\n");
            watch.Stop();
            richTextBox1.AppendText("Consumer time: " + watch.ElapsedMilliseconds + "\r\n");
        }
Esempio n. 2
0
        public void MeasureStopwatch()
        {
            var sw = new System.Diagnostics.Stopwatch();
            var measured = new System.Diagnostics.Stopwatch();
            sw.Reset();
            sw.Start();
            measured.Start();
            measured.Stop();
            var warmupTemp = measured.ElapsedMilliseconds;
            sw.Stop();
            var warmupTime = sw.ElapsedMilliseconds;
            measured.Reset();
            sw.Reset();

            sw.Start();
            sw.Stop();
            var originalTime = sw.ElapsedMilliseconds;
            sw.Reset();

            sw.Start();
            for (var i = 0; i < 1000000; i++)
            {
                measured.Start();
                measured.Stop();
                var temp = measured.ElapsedMilliseconds;
            }
            sw.Stop();
            var measuredTime = sw.ElapsedMilliseconds;
            Console.WriteLine(measuredTime - originalTime);
        }
Esempio n. 3
0
        static void Main(string[] args)
        {
            string s = System.IO.File.ReadAllText(@"example.json");
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            for (int i = 0; i < 10000; i++)
                Fairytale.JsonDeserializer.Deserialize(s);
            
            sw.Stop();
            Console.WriteLine(sw.Elapsed);

            sw.Reset();

            sw.Start();

            for (int i = 0; i < 10000; i++)
                Newtonsoft.Json.JsonConvert.DeserializeObject(s);

            sw.Stop();
            Console.WriteLine(sw.Elapsed);

            sw.Reset();

            sw.Start();

            var parser = new System.Text.Json.JsonParser();
            for (int i = 0; i < 10000; i++)
                parser.Parse(s);

            sw.Stop();
            Console.WriteLine(sw.Elapsed);
            Console.ReadLine();
        }
        public void TestExecuteIntersectionQuery()
        {
            NUnit.Framework.Assert.IsTrue(System.IO.File.Exists(GetTestDataFilePath("SPATIAL_F_SKARVMUFF.shp")),
                                          "Specified shapefile is not present!");

            var shp = new SharpMap.Data.Providers.ShapeFile(GetTestDataFilePath("SPATIAL_F_SKARVMUFF.shp"), false, false);
            shp.Open();

            var fds = new SharpMap.Data.FeatureDataSet();
            var bbox = shp.GetExtents();
            //narrow it down
            bbox.ExpandBy(-0.425*bbox.Width, -0.425*bbox.Height);

            //Just to avoid that initial query does not impose performance penalty
            shp.DoTrueIntersectionQuery = false;
            shp.ExecuteIntersectionQuery(bbox, fds);
            fds.Tables.RemoveAt(0);

            //Perform query once more
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            shp.ExecuteIntersectionQuery(bbox, fds);
            sw.Stop();
            System.Console.WriteLine("Queried using just envelopes:\n" + fds.Tables[0].Rows.Count + " in " +
                                     sw.ElapsedMilliseconds + "ms.");
            fds.Tables.RemoveAt(0);

            shp.DoTrueIntersectionQuery = true;
            sw.Reset();
            sw.Start();
            shp.ExecuteIntersectionQuery(bbox, fds);
            sw.Stop();
            System.Console.WriteLine("Queried using prepared geometries:\n" + fds.Tables[0].Rows.Count + " in " +
                                     sw.ElapsedMilliseconds + "ms.");
        }
Esempio n. 5
0
        public void TestFromTxtFile(string file)
        {
            var wordUtil = new WordDict();
            var expectWordCount = 0;
            using (var sr = new StreamReader(file, Encoding.UTF8))
            {
                string line = null;
                while ((line = sr.ReadLine()) != null)
                {
                    if (line == string.Empty) continue;
                    wordUtil.Add(line);
                    expectWordCount++;
                }
            }

            var watcher = new System.Diagnostics.Stopwatch();
            watcher.Start();
            var ms = new MemoryStream();
            wordUtil.SaveTo(ms);
            watcher.Stop();

            Console.WriteLine("build dawg elapsed time:" + watcher.Elapsed.TotalMilliseconds + "'ms");

            watcher.Reset();
            watcher.Start();
            ms.Position = 0;
            wordUtil = WordDict.LoadFrom(ms);
            watcher.Stop();
            Console.WriteLine("load dawg file elapsed time:" + watcher.Elapsed.TotalMilliseconds + "'ms");
            Assert.AreEqual(expectWordCount, wordUtil.Count);
        }
Esempio n. 6
0
        static void Brute(string target, string letters, string algorithm, int start, int end)
        {
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            Query.Letters = letters;
            Query.size = start;
            for (var query = new Query(); query.Length <= end; query.Next())
            {
                var hash = Invoke("brute", "Program", algorithm, new object[]
                {
                    query.ToString()
                });

                if (hash.Equals(target))
                {
                    Console.WriteLine("" + query.ToString() + " is Correct!!\n");
                    Console.WriteLine("[*] " + target + " is " + query.ToString());
                    sw.Stop();
                    Console.WriteLine(sw.Elapsed);
                    return;
                }
                Console.WriteLine(query.ToString() + " is Not Correct...");
            }

            sw.Stop();
            Console.WriteLine(sw.Elapsed);
            Console.WriteLine("[*] Not Found...");
        }
Esempio n. 7
0
        private void button2_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            label3.Text = "???ms";
            label4.Text = "Total is ";
            richTextBox1.Text = "";
            sw.Reset();
            sw.Start();
            List<int> resultList = primeNumbers.LinearSieve((int)numericUpDown1.Value, (int)numericUpDown2.Value);
            sw.Stop();
            label3.Text = (sw.Elapsed.TotalMilliseconds.ToString() + " ms").ToString();
            label4.Text = "Total is " + resultList.Count;
            sw.Start();

            string a = string.Join(",", resultList.ToArray());
                //sw.Stop();
                //Console.WriteLine((sw.Elapsed.TotalMilliseconds.ToString() + " ms").ToString());
                richTextBox1.Invoke((MethodInvoker)delegate {
                    //sw.Reset();
                    //sw.Start();
                    richTextBox1.AppendText(a);
                    sw.Stop();
                    label3.Text = label3.Text + "/" + (sw.Elapsed.TotalMilliseconds.ToString() + " ms").ToString();
                }
            );
        }
Esempio n. 8
0
        public void TestWarpedLineSymbolizer()
        {
            var p = new SharpMap.Data.Providers.ShapeFile(@"d:\\daten\GeoFabrik\\Aurich\\roads.shp", false);

            var l = new SharpMap.Layers.VectorLayer("roads", p);
            var cls = new SharpMap.Rendering.Symbolizer.CachedLineSymbolizer();
            cls.LineSymbolizeHandlers.Add(new SharpMap.Rendering.Symbolizer.PlainLineSymbolizeHandler { Line = new System.Drawing.Pen(System.Drawing.Color.Gold, 2) });
            cls.LineSymbolizeHandlers.Add(new SharpMap.Rendering.Symbolizer.WarpedLineSymbolizeHander { Pattern = SharpMap.Rendering.Symbolizer.WarpedLineSymbolizer.GetGreaterSeries(3, 3), Line = new System.Drawing.Pen(System.Drawing.Color.Firebrick, 1) });
            l.Style.LineSymbolizer = cls;

            var m = new SharpMap.Map(new System.Drawing.Size(720, 540)) {BackColor = System.Drawing.Color.Cornsilk};
            m.Layers.Add(l);

            m.ZoomToExtents();

            var sw = new System.Diagnostics.Stopwatch();

            sw.Start();
            var bmp = m.GetMap();
            sw.Stop();
            System.Console.WriteLine(string.Format("Rendering new method: {0}ms", sw.ElapsedMilliseconds));
            bmp.Save("AurichRoads1.bmp");

            cls.LineSymbolizeHandlers[1] = new SharpMap.Rendering.Symbolizer.WarpedLineSymbolizeHander
            {
                Pattern = SharpMap.Rendering.Symbolizer.WarpedLineSymbolizer.GetTriangleSeries(4, 7),
                Line = new System.Drawing.Pen(System.Drawing.Color.Firebrick, 1),
                Fill = new System.Drawing.SolidBrush(System.Drawing.Color.Firebrick)
            };
            sw.Start();
            bmp = m.GetMap();
            sw.Stop();
            System.Console.WriteLine(string.Format("Rendering new method: {0}ms", sw.ElapsedMilliseconds));
            bmp.Save("AurichRoads2.bmp");

            //cls.LineSymbolizeHandlers[0] = cls.LineSymbolizeHandlers[1];
            cls.LineSymbolizeHandlers[1] = new SharpMap.Rendering.Symbolizer.WarpedLineSymbolizeHander
                                               {
                                                   Pattern = SharpMap.Rendering.Symbolizer.WarpedLineSymbolizer.GetZigZag(4, 4),
                                                   Line = new System.Drawing.Pen(System.Drawing.Color.Firebrick, 1),
                                                   //Fill = new System.Drawing.SolidBrush(System.Drawing.Color.Firebrick)
                                               };
            sw.Start();
            bmp = m.GetMap();
            sw.Stop();
            System.Console.WriteLine(string.Format("Rendering new method: {0}ms", sw.ElapsedMilliseconds));
            bmp.Save("AurichRoads3.bmp");

        }
        private static void Search(int collectionSize, int searchItemsCount)
        {
            Console.WriteLine($"V množině o velikost {collectionSize:n0} hledáno {searchItemsCount:n0}x:");

            #region Sample data
            var sw = new System.Diagnostics.Stopwatch();
            var list = new List<Guid>();
            var dictionary = new Dictionary<Guid, object>();
            foreach (var guid in Enumerable.Range(0, collectionSize).Select(g => Guid.NewGuid()))
            {
                list.Add(guid);
                dictionary.Add(guid, null);
            }
            var lookup = list.ToLookup(i => i);
            var sortedArray = list.ToArray();
            Array.Sort(sortedArray);

            // vytvoření sample-dat, které budeme hledat
            var rand = new Random();
            var hledane = Enumerable.Range(0, searchItemsCount).Select(g => (rand.NextDouble() > 0.5) ? Guid.NewGuid() : list[rand.Next(list.Count)]).ToList();

            #endregion

            // Contains = sekvenční vyhledávání = O(n)
            sw.Start();
            int found = hledane.Count(t => list.Contains(t));
            sw.Stop();
            Console.WriteLine($"\tList<>.Contains():          Nalezeno {found:n0}x, čas {sw.ElapsedTicks,10:n0} ticks");

            // binární půlení = O(log(n))
            sw.Restart();
            found = hledane.Count(t => Array.BinarySearch<Guid>(sortedArray, t) >= 0);
            sw.Stop();
            Console.WriteLine($"\tArray.BinarySearch<>():     Nalezeno {found:n0}x, čas {sw.ElapsedTicks,10:n0} ticks");

            // Dictionary = Hashtable, O(1)
            sw.Restart();
            found = hledane.Count(t => dictionary.ContainsKey(t));
            sw.Stop();
            Console.WriteLine($"\tDictionary<>.ContainsKey(): Nalezeno {found:n0}x, čas {sw.ElapsedTicks,10:n0} ticks");

            // Dictionary = Hashtable, O(1)
            sw.Restart();
            found = hledane.Count(i => lookup.Contains(i));
            sw.Stop();
            Console.WriteLine($"\tLINQ ILookup:               Nalezeno {found:n0}x, čas {sw.ElapsedTicks,10:n0} ticks");

            Console.WriteLine();
        }
Esempio n. 10
0
 static void Main(string[] args)
 {
     System.Diagnostics.Stopwatch tm = new System.Diagnostics.Stopwatch();
     tm.Start();
     byte pow = 1 << 5;
     tm.Stop();
     Console.WriteLine("Left-shift time = {0}", tm.Elapsed.TotalMilliseconds);
     // first time
     tm.Reset();
     tm.Start();
     byte mathPow = (byte)Math.Pow(2, 5);
     tm.Stop();
     Console.WriteLine("Math time = {0}", tm.Elapsed.TotalMilliseconds);
     // second time
 }
Esempio n. 11
0
        /// <summary>
        /// Tests for Vector3D class
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnVector3D_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();

            txtVector3D.Text = "Starting test suite for the Vektor3D class.\r\n\r\n";

            // Sample data
            List<Eksam.Vektor3D> vectors = new List<Vektor3D>{
                new Vektor3D(),
                new Vektor3D(1,1,1),
                new Vektor3D(0,-1,0),
                new Vektor3D(2.2, 1.2, 3.1),
                new Vektor3D(10,4,3),
                null
            };

            // Go over all defined operations and input combinations
            foreach (Vektor3D vector in vectors)
            {
                foreach (Vektor3D secondVector in vectors)
                {
                    txtVector3D.Text += vector + " + " + secondVector + " = " + (vector + secondVector) + "\r\n";
                    txtVector3D.Text += vector + " - " + secondVector + " = " + (vector - secondVector) + "\r\n";
                    txtVector3D.Text += vector + " == " + secondVector + " ... " + (vector == secondVector) + "\r\n";
                    txtVector3D.Text += vector + vector + " (length " + (vector == null ? 0 : vector.Length()) + ") > " + secondVector + " (length " + (secondVector == null ? 0 : secondVector.Length()) + ")" + " ... " + (vector > secondVector) + "\r\n";
                    txtVector3D.Text += vector + vector + " (length " + (vector == null ? 0 : vector.Length()) + ") < " + secondVector + " (length " + (secondVector == null ? 0 : secondVector.Length()) + ")" + " ... " + (vector < secondVector) + "\r\n";
                }
            }

            watch.Stop();
            double elapsed = watch.ElapsedMilliseconds;
            txtVector3D.Text += "\r\nTest suite finished, time elapsed: " + elapsed + "ms.";
        }
        public void HaveTheCorrectMedianDelayIfADelayTimespanIsSpecified()
        {
            // This is only a sanity-test.  I don't need to check
            // that Microsoft's Delay API works properly, I just need
            // to make sure that I called it properly so that I
            // am getting reasonable results.

            const double delayToleranceMs = 2.0;
            const int executionCount = 100;

            var target = new Timing.Threading.Provider();
            var delayInMs = (10.0).GetRandom(5.0);
            var delayTimespan = TimeSpan.FromMilliseconds(delayInMs);
            var minDelayMs = delayInMs - delayToleranceMs;
            var maxDelayMs = delayInMs + delayToleranceMs;

            var results = new List<long>();

            for (int i = 0; i < executionCount; i++)
            {
                var timer = new System.Diagnostics.Stopwatch();
                timer.Start();
                target.Delay(delayTimespan);
                timer.Stop();
                results.Add(timer.ElapsedMilliseconds);
            }

            var actualDelayMs = results.Median();

            TestContext.WriteLine("Delay - Min Allowed: {0}  Max Allowed: {1}  Actual: {2}", minDelayMs, maxDelayMs, actualDelayMs);
            Assert.IsTrue(actualDelayMs <= maxDelayMs);
            Assert.IsTrue(actualDelayMs >= minDelayMs);
        }
Esempio n. 13
0
        public static int Main(string[] args)
        {
            using (BootStrap b = new BootStrap())
            {
                System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
                watch.Start();

                string filename = b.GetInputFile("Tight Binding code", "tb", args);

                TightBinding c = new TightBinding();

                c.LoadTB(filename);
                c.RunTB();

                watch.Stop();
                Output.WriteLine("Total time: {0} s", watch.ElapsedMilliseconds / 1000.0);

                long milliseconds = watch.ElapsedMilliseconds;
                int seconds = (int)(milliseconds / 1000L);
                int minutes = seconds / 60;
                int hours = minutes / 60;
                minutes %= 60;
                seconds %= 60;
                milliseconds %= 1000;

                Output.WriteLine("            {0}:{1:00}:{2:00}.{3:000}", hours, minutes, seconds, milliseconds);
                return 0;
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Testing Requests without response
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            //sm.RemoteRequestWithoutResponse(null);
            var res = sm.RemoteRequest(new byte[] { 9 });
            return;

            //var res = sm.RemoteRequest(new byte[546],
            //    (par) =>
            //    {
            //        Console.WriteLine(par.Item1);
            //    }
            //    ,10000);
            //return;

            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            for (int i = 0; i < 10000; i++)
            {
                //sm.RemoteRequestWithoutResponse(new byte[1]);
                sm.RemoteRequestWithoutResponse(new byte[512]);
                //sm.RemoteRequestWithoutResponse(new byte[10000]);
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
        }
Esempio n. 15
0
 protected void Page_Load( object sender, EventArgs e )
 {
     var url = ConfigurationManager.AppSettings.Get( "CLOUDANT_URL" );
     var connection = new Connection( new Uri( url ) );
     if ( !connection.ListDatabases().Contains( "gmkreports" ) )
     {
         connection.CreateDatabase( "gmkreports" );
     }
     var repository = new Repository<Report>( connection.CreateSession( "gmkreports" ) );
     var report = new Report { ID = Guid.NewGuid(), Type = 1, AccessionNumber = "123", Contents = "abcd" };
     System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
     watch.Reset();
     watch.Start();
     var id = repository.Save( report ).Id;
     var retrievedReport = repository.Get( id );
     watch.Stop();
     if ( retrievedReport.ID == report.ID && retrievedReport.Type == report.Type && retrievedReport.AccessionNumber == report.AccessionNumber && retrievedReport.Contents == report.Contents )
     {
         _label.Text = watch.ElapsedMilliseconds.ToString();
     }
     else
     {
         _label.Text = "Error";
     }
 }
Esempio n. 16
0
        static void Main(string[] args)
        {
            var watch = new System.Diagnostics.Stopwatch();
            watch.Start();

            var reader = new TextFileLineByLineReader(@"Z:\ClueWeb09_WG_50m.graph-txt", 1);
            //reader.PrependLineNumber = true;
            reader.LinesPerRecord = 10000;

            var keyword = "11";

            var mr = new TextMapReduce<string, long>(reader, @"z:\pashm");
            mr.MapFunc = (s, context) =>
            {
                context.Emit("found", Regex.Matches(s, keyword).Count);
            };

            mr.CombineFunc = (list) => { return list.Sum(); };
            mr.ReduceFunc = (reduce_obj, reduce_context) =>
            {
                var all = reduce_obj.ReadAll();
                reduce_context.Emit(reduce_obj.Key + ":" + all.First().ToString());
            };

            mr.Run(1);

            watch.Stop();
            Console.WriteLine("Took: " + watch.Elapsed);
        }
Esempio n. 17
0
        // functions
        static void Main(string[] args)
        {
            if (args.Length < 6 )
            {
                Console.WriteLine("Error --  not enough parameters");
                Console.WriteLine("Usage : DataImporter.exe file[path], ip, port, catalog, id, passwd");
                Console.ReadKey();
                return;
            }
            DbManager.SetConnString(string.Format("Data Source={0},{1};Initial Catalog={2};USER ID={3};PASSWORD={4}", args[1], args[2], args[3], args[4], args[5]));
            // argument가 directory면 파일을 만들고
            string listFileName = "";
            System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(args[0]);
            if( dirInfo.Exists )
            {
                listFileName = args[0] + "\\data_table.lst";
                System.IO.StreamWriter listWriter = new System.IO.StreamWriter(listFileName);
                foreach ( System.IO.FileInfo fileInfo in dirInfo.GetFiles())
                {
                    if(fileInfo.Extension == ".csv" )
                    {
                        listWriter.WriteLine(fileInfo.FullName);
                    }
                }
                listWriter.Close();
            }
            else
            {
                listFileName = args[0];
            }

            // 시간 측정
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Reset();
            sw.Start();

            string[] dataFiles = System.IO.File.ReadAllLines(listFileName, Encoding.Default);
            if( dataFiles.Length == 0)
            {
                Console.WriteLine("Error : invalid file or directory.!");
                Console.ReadLine();
                return;
            }

            // 파일이면 해당 파일의 리스트를 읽어서 사용한다.
            System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
            FileManager.Init(string.Format("{0}\\{1}.log", System.IO.Directory.GetCurrentDirectory(), currentProcess.ProcessName));

            Parallel.For(0, dataFiles.Length, (i) =>
               {
               FileManager fileManager = new FileManager();
               fileManager.ImportToDb(dataFiles[i]);
               });

            FileManager.Release();

            sw.Stop();
            Console.WriteLine("수행시간 : {0}", sw.ElapsedMilliseconds / 1000.0f);
            Console.ReadLine();
        }
Esempio n. 18
0
        private void button_doSegmentation_Click(object sender, EventArgs e)
        {
            if (pictureBox_originImage.Image == null)
            {
                MessageBox.Show("Выберите изображение для сегментации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (numericUpDown_defaultSegmentsNumber.Value <= numericUpDown_requiredSegmentsNumber.Value)
            {
                MessageBox.Show("Начальное количество сегментов должно быть больше желаемого количества сегментов",
                    "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (pictureBox_segmentedImage.Image != null)
                pictureBox_segmentedImage.Image = null; 

            System.Diagnostics.Stopwatch swatch = new System.Diagnostics.Stopwatch();
            swatch.Start();

            SegmentedImage segmentedImage = RegionBasedSegmentation.PerformSegmentation(originImage,
                (int)numericUpDown_defaultSegmentsNumber.Value, (int)numericUpDown_requiredSegmentsNumber.Value);

            swatch.Stop();
            toolStripStatusLabel1.Text = "Вермя сегментации: " + swatch.Elapsed.ToString();

            segmentedImage.AverageRegionPixelsColor();

            pictureBox_segmentedImage.Image = segmentedImage.GetBitmapFromSegments();
        }
Esempio n. 19
0
        public void Given_A_Checklist_Is_Being_Saved_Then_Returns_Status_OK()
        {
            // Given
            var client = new RestClient(Url.AbsoluteUri);
            client.Authenticator = new NtlmAuthenticator( "continuous.int","is74rb80pk52" );

            const int numberOfRequestsToSend = 15;
            var stopWatch = new System.Diagnostics.Stopwatch();
            stopWatch.Start();
            var parallelLoopResult = Parallel.For(0, numberOfRequestsToSend, x =>
                                                                                 {
                                                                                     //GIVEN
                                                                                     var model = CreateChecklistViewModel();
                                                                                     var resourceUrl = string.Format("{0}{1}/{2}", ApiBaseUrl, "checklists", model.Id.ToString());
                                                                                     var request = new RestRequest(resourceUrl);
                                                                                     request.AddHeader("Content-Type", "application/json");
                                                                                     request.RequestFormat = DataFormat.Json;
                                                                                     request.Method = Method.POST;
                                                                                     request.AddBody(model);

                                                                                     // When
                                                                                     var response = client.Execute(request);

                                                                                     //THEN
                                                                                     Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                                                                                 });

            stopWatch.Stop();

            var processingSeconds = TimeSpan.FromMilliseconds(stopWatch.ElapsedMilliseconds).TotalSeconds;
            Assert.That(parallelLoopResult.IsCompleted);
            Console.WriteLine(string.Format("average: {0}", processingSeconds / numberOfRequestsToSend));
        }
Esempio n. 20
0
        static void DevRun()
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();


            var opts = new Options();
            opts.ExecutionMode = ExecutionMode.Serial;
            ProtoCore.Core core = new Core(opts);
            core.Compilers.Add(ProtoCore.Language.Associative, new ProtoAssociative.Compiler(core));
            core.Compilers.Add(ProtoCore.Language.Imperative, new ProtoImperative.Compiler(core));
#if DEBUG
            core.Options.DumpByteCode = true;
            core.Options.Verbose = true;
#else
            core.Options.DumpByteCode = false;
            core.Options.Verbose = false;
#endif
            ProtoFFI.DLLFFIHandler.Register(ProtoFFI.FFILanguage.CSharp, new ProtoFFI.CSModuleHelper());
            ProtoScriptRunner runner = new ProtoScriptRunner();

            // Assuming current directory in test/debug mode is "...\Dynamo\bin\AnyCPU\Debug"
            runner.LoadAndExecute(@"..\..\..\test\core\dsevaluation\DSFiles\test.ds", core);

            long ms = sw.ElapsedMilliseconds;
            sw.Stop();
            Console.WriteLine(ms);
            Console.ReadLine();
        }
Esempio n. 21
0
		protected void SetUp()
		{
	        base_cycle_metric_header header = new base_cycle_metric_header();
		    if(metrics.Count == 0)
		    {
                System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
                timer.Start();
                float[] focus1 = new float[]{2.24664021f, 2.1896739f, 0, 0};
                ushort[] p90_1  = new ushort[]{302, 273, 0, 0};
                for(uint lane = 1;lane <=8;lane++)
                {
                    for(uint tile = 1;tile <=TileCount;tile++)
                    {
                        for(uint cycle = 1;cycle <=318;cycle++)
                        {
                            metrics.Add(new extraction_metric(lane, tile, cycle, new csharp_date_time(9859129975844165472ul), (p90_1), (focus1), 4));
                        }
                    }
                }
                extraction_metric_set = new base_extraction_metrics(metrics, Version, header);
                timer.Stop();
                System.Console.WriteLine("Setup: " + timer.Elapsed.Hours +" : " + timer.Elapsed.Minutes +" : " + timer.Elapsed.Seconds);
                System.Console.WriteLine("Size: " + metrics.Count + " - " + extraction_metric_set.size());
		    }
		}
Esempio n. 22
0
        static private void WorkerEvents()
        {
            Tuple<EventDelegate, Effect, Effect> cEvent;
			System.Diagnostics.Stopwatch cWatch = new System.Diagnostics.Stopwatch();
			while (true)
			{
				try
				{
					cEvent = _aqEvents.Dequeue();
					cWatch.Reset();
					cWatch.Restart();
					cEvent.Item1(cEvent.Item2, cEvent.Item3);
					(new Logger()).WriteDebug3("event sended [hc = " + cEvent.Item3.GetHashCode() + "][" + cEvent.Item1.Method.Name + "]");
					cWatch.Stop();
					if (40 < cWatch.ElapsedMilliseconds)
						(new Logger()).WriteDebug3("duration: " + cWatch.ElapsedMilliseconds + " queue: " + _aqEvents.nCount);
					if (0 < _aqEvents.nCount)
						(new Logger()).WriteDebug3(" queue: " + _aqEvents.nCount);
                }
                catch (System.Threading.ThreadAbortException)
                {
                    break;
                }
                catch (Exception ex)
                {
                    (new Logger()).WriteError(ex);
                }
            }
        }
Esempio n. 23
0
        static void acceptIncomingConnection(IAsyncResult ar)
        {
            Socket mainsock = (Socket)ar.AsyncState;
            Socket incomingsock = mainsock.EndAccept(ar);
            Donify.Set();

            System.Diagnostics.Stopwatch swatch = new System.Diagnostics.Stopwatch();
            swatch.Start();

            logger.log("Got connection from: " + incomingsock.RemoteEndPoint, Logging.Priority.Notice);
            if (socketfunctions.waitfordata(incomingsock, 10000, true))
            {
                string[] incomingstring = socketfunctions.receivestring(incomingsock, true).Replace("\r\n", "\n").Split('\n');
                try
                {
                    string response = bstuff.OnyEvents.NewMessage(incomingstring, (IPEndPoint)incomingsock.RemoteEndPoint);
                    logger.log("got from plugins: " + response, Logging.Priority.Notice);
                    if (response == null || response == "")
                        socketfunctions.sendstring(incomingsock, "Blargh.");
                    else
                        socketfunctions.sendstring(incomingsock, response);
                }
                catch (Exception ex)
                { logger.logerror(ex); }

                incomingsock.Shutdown(SocketShutdown.Both);
                incomingsock.Close();

                swatch.Stop();

                logger.log("Session time: " + swatch.ElapsedMilliseconds, Logging.Priority.Info);

                bstuff.OnyVariables.amountloops++;
            }
        }
Esempio n. 24
0
        private void LoadDatafromAHRS()
        {
            updateTimer.Enabled = false;
            try
            {
                System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
                watch.Start();
                UAVParameter speedparam = (UAVParameter)GPS["lbRMCSpeed"];
                UAVParameter altparam = (UAVParameter)GPS["lbGGAAltitude"];
                UAVParameter phiparam = (UAVParameter)AHRS["phi"];
                UAVParameter thetaparam = (UAVParameter)AHRS["theta"];
                UAVParameter psiparam = (UAVParameter)AHRS["psi"];

                    if (speedparam != null) if (!speedparam.Value.Equals("N/A")) airSpeedIndicator.SetAirSpeedIndicatorParameters(Convert.ToInt32(speedparam.Value));
                    if ((thetaparam != null) && (phiparam != null)) attitudeIndicator.SetAttitudeIndicatorParameters(Convert.ToDouble(thetaparam.Value), Convert.ToDouble(phiparam.Value));
                // Änderungsrate berechnen
                // Turn Quality berechnen
                // this.vspeed = vspeed + Convert.ToInt32(mycore.currentUAV.uavData["lbGGAAltitude"].Value)*0.9;
                    if ((psiparam != null) && (psiparam != null)) this.Compass.SetHeadingIndicatorParameters(Convert.ToInt32(Convert.ToDouble(psiparam.Value)));
                //  if (mycore.currentUAV.uavData.ContainsKey("yaw")) Compass.SetHeadingIndicatorParameters(Convert.ToInt32(mycore.currentUAV.uavData["yaw"].Value));
               //     if (mycore.currentUAV.uavData.ContainsKey("vspeed")) verticalSpeedIndicator.SetVerticalSpeedIndicatorParameters(Convert.ToInt32(mycore.currentUAV.uavData["vspeed"].Value));
                if (altparam != null) altimeter.SetAlimeterParameters(Convert.ToInt32(Convert.ToDouble(altparam.Value)));
            //    if (mycore.currentUAV.uavData.ContainsKey("turnrate") && mycore.currentUAV.uavData.ContainsKey("turnquality")) turnCoordinator.SetTurnCoordinatorParameters(Convert.ToSingle(mycore.currentUAV.uavData["turnrate"].Value), Convert.ToSingle(mycore.currentUAV.uavData["turnquality"].Value));
                this.Invalidate();
                Console.WriteLine("time update:"+watch.ElapsedMilliseconds);
                watch.Stop();
            }
            catch (Exception ex) {

            }
            updateTimer.Enabled = true;
        }
Esempio n. 25
0
 public void InterOpSpeed()
 {
     const int TESTSIZE = 100;
     count = 0;
     // get some random prices
     Tick[] data = RandomTicks.GenerateSymbol(sym, TESTSIZE);
     // track the time
     System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
     int bad = 0;
     sw.Start();
     for (int i = 0; i < data.Length; i++)
     {
         int err = SendOrder(sym, true, 300, (double)data[i].trade, 0, 1, "TESTACCOUNT", "TESTDEST");
         if (err!=0) bad++;
     }
     sw.Stop();
     long elapms = sw.ElapsedMilliseconds;
     double elap = (double)elapms/1000;
     double rate = TESTSIZE / elap;
     Console.WriteLine("InterOpSpeed elap: " + elap.ToString("N1") + " rate: " + rate.ToString("N0") + " orders/sec");
     // make sure orders received
     Assert.AreEqual(data.Length, count);
     // make sure no bad orders
     Assert.AreEqual(0,bad);
     // make sure fast
     Assert.LessOrEqual(elap, .5);
 }
        public void HaveAnAcceptableRangeOfDelaysIfADelayTimespanIsSpecified()
        {
            // This is only a sanity-test.  I don't need to check
            // that Microsoft's Delay API works properly, I just need
            // to make sure that I called it properly so that I
            // am getting reasonable results.

            const double maxDelayRange = 4.0;
            const int executionCount = 100;

            var target = new Timing.Threading.Provider();
            var delayInMs = 10.GetRandom(5);
            var delayTimespan = TimeSpan.FromMilliseconds(delayInMs);

            var results = new List<long>();

            for (int i = 0; i < executionCount; i++)
            {
                var timer = new System.Diagnostics.Stopwatch();
                timer.Start();
                target.Delay(delayTimespan);
                timer.Stop();
                results.Add(timer.ElapsedMilliseconds);
            }

            var actualDelayMs = results.Range();

            TestContext.WriteLine("Delay - Delay Ms: {0}  Range of Delays: {1}  Max allowed Range: {2}", delayInMs, actualDelayMs, maxDelayRange);
            Assert.IsTrue(actualDelayMs <= maxDelayRange);
        }
Esempio n. 27
0
        static void Run(string filename, bool verbose)
        {
            if (!File.Exists(filename))
            {
                Console.WriteLine("Cannot find file " + filename);
                return;
            }

            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            var opts = new Options();
            opts.ExecutionMode = ExecutionMode.Serial;
            ProtoCore.Core core = new Core(opts);
            core.Compilers.Add(ProtoCore.Language.Associative, new ProtoAssociative.Compiler(core));
            core.Compilers.Add(ProtoCore.Language.Imperative, new ProtoImperative.Compiler(core));
            core.Options.DumpByteCode = verbose;
            core.Options.Verbose = verbose;
            ProtoFFI.DLLFFIHandler.Register(ProtoFFI.FFILanguage.CSharp, new ProtoFFI.CSModuleHelper());

            ProtoScriptRunner runner = new ProtoScriptRunner();

            runner.LoadAndExecute(filename, core);
            long ms = sw.ElapsedMilliseconds;
            sw.Stop();
            Console.WriteLine(ms);
        }
Esempio n. 28
0
        static void Mul(InputData data, Port<int> resp)
         {
             int i, j;
             System.Diagnostics.Stopwatch sWatch = new System.Diagnostics.Stopwatch();
             sWatch.Start();


            for (i = data.start; i <= data.stop-1; i++)
             {
                 for (j = i+1; j <= data.stop; j++)
                 {
                      if (a[j] < a[i]) //сортировка пузырьком
                    {
                        var temp = a[i];
                        a[i] = a[j];
                        a[j] = temp;
                    }
                }
             }
            //внимательно присмотревшись к этой функции и к условиям, в которых она вызывается, можно сделать вывод
            //что она вернет массив, состоящий из двух сортированных половинок, но не сортированный целиком
            //так оно и есть, потому что параллельный пузырек - необычная задумка
            //в данной лабораторной работе эта проблема решается в делегате, описанном в приемнике, штатными средствами C#
             sWatch.Stop();
             resp.Post(1);
             Console.WriteLine("Поток № {0}: Параллельный алгоритм = {1} мс.", Thread.CurrentThread.ManagedThreadId, sWatch.ElapsedMilliseconds.ToString());
        }
Esempio n. 29
0
        public void PerfAtLeastOnceSend()
        {
            string testName = "PerfAtLeastOnceSend";
            Connection connection = new Connection(address);
            Session session = new Session(connection);
            this.sender = new SenderLink(session, "sender-" + testName, "q1");

            this.onOutcome = OnSendComplete;
            this.done = new ManualResetEvent(false);
            this.totalCount = 1000000;
            this.completedCount = 0;
            this.initialCount = 300;
            this.batchCount = 100;
            Trace.TraceLevel = TraceLevel.Information;

            var watch = new System.Diagnostics.Stopwatch();
            watch.Start();

            this.SendMessages(initialCount);

            this.done.WaitOne();
            watch.Stop();
            Trace.WriteLine(TraceLevel.Information, "total: {0}, time: {1}ms", this.totalCount, watch.ElapsedMilliseconds);

            connection.Close();
        }
 static void Main(string[] args) {
   var stopWatch = new System.Diagnostics.Stopwatch();
   stopWatch.Restart();
   run();
   stopWatch.Stop();
   Console.WriteLine(string.Format("Elapsed Time: {0:0.000} seconds", stopWatch.Elapsed.TotalSeconds));      
 }
Esempio n. 31
0
 void stop()
 {
     _sw?.Stop();
     foreach (var tcp in _tcps)
     {
         tcp?.stop();
     }
     btnStartStopr.Text = "Connect";
     nudRow.Enabled     = true;
     nudCol.Enabled     = true;
 }
Esempio n. 32
0
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            _Stopwatch?.Start();

            try
            {
                return(await next());
            }
            finally
            {
                _Stopwatch?.Stop();

                if (_Configuration.AllowUse)
                {
                    _RequestInformation.Elapsed = _Stopwatch !.ElapsedMilliseconds;

                    _RequestProcessor !.Process();
                }
            }
        }
Esempio n. 33
0
 void stop()
 {
     _sw?.Stop();
     _tcp?.stop();
     btnStartStopr.Text = "Start";
 }
Esempio n. 34
0
        public static List <List <int> > GetProdProvs(DateTime dateFrom, DateTime dateTo)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <List <List <int> > >(MethodBase.GetCurrentMethod(), dateFrom, dateTo));
            }
            Random rnd    = new Random();
            string rndStr = rnd.Next(1000000).ToString();
            string command;

#if DEBUG
            _elapsedTimeProdProvs = "";
            System.Diagnostics.Stopwatch stopWatch      = new System.Diagnostics.Stopwatch();
            System.Diagnostics.Stopwatch stopWatchTotal = new System.Diagnostics.Stopwatch();
            _elapsedTimeProdProvs = "Elapsed time for GetProdProvs:\r\n";
            stopWatch.Restart();
            stopWatchTotal.Restart();
#endif
            command = "DROP TABLE IF EXISTS tempdash" + rndStr + @";";
            Db.NonQ(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProdProvs += "DROP TABLE: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            //this table will contain approx 12x3xProv rows if there was production for each prov in each month.
            command = @"CREATE TABLE tempdash" + rndStr + @" (
				DatePeriod date NOT NULL,
				ProvNum bigint NOT NULL,
				production decimal NOT NULL
				) DEFAULT CHARSET=utf8"                ;
            Db.NonQ(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProdProvs += "CREATE TABLE: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            //procs. Inserts approx 12xProv rows
            command = @"INSERT INTO tempdash" + rndStr + @"
				SELECT procedurelog.ProcDate,procedurelog.ProvNum,
				SUM(procedurelog.ProcFee*(procedurelog.UnitQty+procedurelog.BaseUnits))-IFNULL(SUM(claimproc.WriteOff),0)
				FROM procedurelog USE INDEX(indexPNPD)
				LEFT JOIN claimproc ON procedurelog.ProcNum=claimproc.ProcNum
				AND claimproc.Status='7' /*only CapComplete writeoffs are subtracted here*/
				WHERE procedurelog.ProcStatus = '2'
				AND procedurelog.ProcDate >= "                 + POut.Date(dateFrom) + @"
				AND procedurelog.ProcDate <= "                 + POut.Date(dateTo) + @"
				GROUP BY procedurelog.ProvNum,MONTH(procedurelog.ProcDate)"                ;
            Db.NonQ(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProdProvs += "INSERT INTO: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif

            //todo 2 more tables


            //get all the data as 12xProv rows
            command = @"SELECT DatePeriod,ProvNum,SUM(production) prod
				FROM tempdash"                 + rndStr + @" 
				GROUP BY ProvNum,MONTH(DatePeriod)"                ;//this fails with date issue
            DataTable tableProd = Db.GetTable(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProdProvs += "tableProd: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            command = "DROP TABLE IF EXISTS tempdash" + rndStr + @";";
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProdProvs += "DROP TABLE: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            Db.NonQ(command);
            command = @"SELECT ProvNum
				FROM provider WHERE IsHidden=0
				ORDER BY ItemOrder"                ;
            DataTable tableProv = Db.GetTable(command);
#if DEBUG
            stopWatch.Stop();
            stopWatchTotal.Stop();
            _elapsedTimeProdProvs += "SELECT ProvNum FROM provider: " + stopWatch.Elapsed.ToString() + "\r\n";
            _elapsedTimeProdProvs += "Total: " + stopWatchTotal.Elapsed.ToString();
            if (_showElapsedTimesForDebug)
            {
                System.Windows.Forms.MessageBox.Show(_elapsedTimeProdProvs);
            }
#endif
            List <List <int> > retVal = new List <List <int> >();
            for (int p = 0; p < tableProv.Rows.Count; p++)      //loop through each provider
            {
                long       provNum = PIn.Long(tableProv.Rows[p]["ProvNum"].ToString());
                List <int> listInt = new List <int>();            //12 items
                for (int i = 0; i < 12; i++)
                {
                    decimal  prod       = 0;
                    DateTime datePeriod = dateFrom.AddMonths(i);                  //only the month and year are important
                    for (int j = 0; j < tableProd.Rows.Count; j++)
                    {
                        if (provNum == PIn.Long(tableProd.Rows[j]["ProvNum"].ToString()) &&
                            datePeriod.Month == PIn.Date(tableProd.Rows[j]["DatePeriod"].ToString()).Month &&
                            datePeriod.Year == PIn.Date(tableProd.Rows[j]["DatePeriod"].ToString()).Year)
                        {
                            prod = PIn.Decimal(tableProd.Rows[j]["prod"].ToString());
                            break;
                        }
                    }
                    listInt.Add((int)(prod));
                }
                retVal.Add(listInt);
            }
            return(retVal);
        }
Esempio n. 35
0
        public static void Main(string[] args)
        {
            //AutoFin->false
            ManualResetEvent terminateProgram = new ManualResetEvent(false);

            //Motor_Rady
            LcdConsole.WriteLine("***Motor_Rady***");
            Motor motorA = new Motor(MotorPort.OutA);
            Motor motorD = new Motor(MotorPort.OutD);

            motorA.Off();
            motorD.Off();
            motorA.ResetTacho();
            motorD.ResetTacho();
            //Vehicle_Rady
            Vehicle    vehicle = new Vehicle(MotorPort.OutA, MotorPort.OutD);
            WaitHandle waitHandle;

            vehicle.ReverseLeft  = false;
            vehicle.ReverseRight = false;
            int b = 0;

            //Sensor_Rady
            LcdConsole.WriteLine("***Sensor_Rady***");
            //Touch_Rady
            var touchSensor1 = new EV3TouchSensor(SensorPort.In1);
            var touchSensor2 = new EV3TouchSensor(SensorPort.In4);
            //UltraSonic_Rady
            var UltraSonicSensor = new EV3UltrasonicSensor(SensorPort.In3, UltraSonicMode.Centimeter);
            //Color_Rady
            EventWaitHandle stopped = new ManualResetEvent(false);

            ColorMode[] modes   = { ColorMode.Color, ColorMode.Reflection, ColorMode.Ambient, ColorMode.Blue };
            int         modeIdx = 0;
            var         sensor  = new EV3ColorSensor(SensorPort.In2, ColorMode.Reflection);


            //Conection
            LcdConsole.WriteLine("***Conect_Rady***");
            //Http
            Encoding enc   = Encoding.UTF8;
            string   input = "Detect";
            string   url   = "http://nursinghomeexplorer.azurewebsites.net/index.php";
            string   param = "";
            //
            Hashtable ht = new Hashtable();

            ht["langpair"] = "#ja";
            ht["hl"]       = "en";
            ht["text"]     = HttpUtility.UrlEncode(input, enc);
            foreach (string k in ht.Keys)
            {
                param += String.Format("{0}={1}&", k, ht[k]);
            }
            byte[] data = Encoding.ASCII.GetBytes(param);
            //
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

            req.Method        = "POST";
            req.ContentType   = "application/x-www-form-urlencoded";
            req.ContentLength = data.Length;
            LcdConsole.WriteLine("***Conected!***");

            //timer set
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            long a = 0;

            //buts
            ButtonEvents buts = new ButtonEvents();

            LcdConsole.WriteLine("Up read BrightLine");
            LcdConsole.WriteLine("Down read Floor");
            //LcdConsole.WriteLine ("Left Exit program");
            //LcdConsole.WriteLine ("Right Exit program");
            LcdConsole.WriteLine("Enter change color mode");
            LcdConsole.WriteLine("Esc. StartRun");

            buts.UpPressed += () =>
            {
                LcdConsole.WriteLine("Sensor value: " + sensor.ReadAsString());
            };
            buts.DownPressed += () =>
            {
                LcdConsole.WriteLine("Raw sensor value: " + sensor.ReadRaw());
            };
            buts.EnterPressed += () =>
            {
                modeIdx     = (modeIdx + 1) % modes.Length;
                sensor.Mode = modes[modeIdx];
                LcdConsole.WriteLine("Sensor mode is set to: " + modes[modeIdx]);
            };
            //Left_Finish
            buts.LeftPressed += () => {
                terminateProgram.Set();
            };

            //Escape_StartRun
            buts.EscapePressed += () =>
            {
                LcdConsole.WriteLine("***StartRun***");
                stopped.Set();
                //loop_run on the line
                while (true)
                {
                    //touchsensor2 Pressed
                    if (touchSensor2.IsPressed() == true)
                    {
                        //motors stop
                        motorA.Brake();
                        motorD.Brake();

                        LcdConsole.WriteLine("***Stop***");

                        //timer start
                        sw.Start();

                        //after 5sec
                        Thread.Sleep(5000);
                        a = sw.ElapsedMilliseconds;

                        LcdConsole.WriteLine("***Stop_5sec***");

                        if (a >= 5000)
                        {
                            //timer stop
                            a = 0;
                            sw.Stop();
                            sw.Reset();

                            if (touchSensor2.IsPressed() == true)
                            {
                                LcdConsole.WriteLine("***Stop_ISPressed2***");

                                //
                                Stream reqStream = req.GetRequestStream();
                                LcdConsole.WriteLine("***Stop_GetReqStream***");
                                reqStream.Write(data, 0, data.Length);
                                LcdConsole.WriteLine("***Stop_write***");
                                reqStream.Close();
                                LcdConsole.WriteLine("***Stop_reqStream.close***");

                                break;
                            }
                            if (touchSensor1.IsPressed() == true)
                            {
                                //
                                Stream reqStream = req.GetRequestStream();
                                reqStream.Write(data, 0, data.Length);
                                reqStream.Close();

                                break;
                            }
                        }
                        else
                        {
                            continue;
                        }
                    }

                    //touchsensor1 pressed
                    if (touchSensor1.IsPressed() == true)
                    {
                        motorA.Brake();
                        motorD.Brake();
                        LcdConsole.WriteLine("***Stop***");
                        //timer start
                        sw.Start();

                        //after 5sec
                        Thread.Sleep(5000);

                        a = sw.ElapsedMilliseconds;
                        if (a >= 5000)
                        {
                            //timer stop
                            a = 0;
                            sw.Stop();
                            sw.Reset();

                            if (touchSensor1.IsPressed() == true)
                            {
                                //
                                Stream reqStream = req.GetRequestStream();
                                reqStream.Write(data, 0, data.Length);
                                reqStream.Close();

                                break;
                            }
                            if (touchSensor2.IsPressed() == true)
                            {
                                //
                                Stream reqStream = req.GetRequestStream();
                                reqStream.Write(data, 0, data.Length);
                                reqStream.Close();

                                break;
                            }
                        }
                        else
                        {
                            continue;
                        }
                    }
                    //Ultrasonic on
                    if (UltraSonicSensor.Read() <= 30)
                    {
                        motorA.Brake();
                        motorD.Brake();
                        LcdConsole.WriteLine("***Stop***");
                        //timer start
                        sw.Start();

                        //after 5sec
                        Thread.Sleep(5000);

                        a = sw.ElapsedMilliseconds;

                        if (a >= 5000)
                        {
                            //timer stop
                            a = 0;
                            sw.Stop();
                            sw.Reset();

                            if (UltraSonicSensor.Read() <= 30)
                            {
                                //
                                Stream reqStream = req.GetRequestStream();
                                reqStream.Write(data, 0, data.Length);
                                reqStream.Close();

                                break;
                            }
                        }
                        else
                        {
                            continue;
                        }
                    }

                    b = sensor.Read();

                    if (b < 15)
                    {
                        vehicle.TurnRightForward(10, 100);
                    }
                    if (15 <= b && b < 60)
                    {
                        vehicle.TurnLeftForward(10, 60);
                    }

                    if (b >= 60)
                    {
                        waitHandle = vehicle.Forward(10, 0, true);
                    }
                }
            };
            terminateProgram.WaitOne();
            buts.LeftPressed += () => {
                terminateProgram.Set();
            };
        }
Esempio n. 36
0
        public static DataTable GetProvList(DateTime dt)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetTable(MethodBase.GetCurrentMethod(), dt));
            }
#if DEBUG
            _elapsedTimeProvList = "";
            System.Diagnostics.Stopwatch stopWatch      = new System.Diagnostics.Stopwatch();
            System.Diagnostics.Stopwatch stopWatchTotal = new System.Diagnostics.Stopwatch();
            _elapsedTimeProvList = "Elapsed time for GetProvList:\r\n";
            stopWatch.Restart();
            stopWatchTotal.Restart();
#endif
            Random rnd    = new Random();
            string rndStr = rnd.Next(1000000).ToString();
            string command;
            command = "DROP TABLE IF EXISTS tempdash" + rndStr + @";";
            Db.NonQ(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProvList += "DROP TABLE: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            command = @"CREATE TABLE tempdash" + rndStr + @" (
				ProvNum bigint NOT NULL PRIMARY KEY,
				production decimal NOT NULL,
				income decimal NOT NULL
				) DEFAULT CHARSET=utf8"                ;
            Db.NonQ(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProvList += "CREATE TABLE: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            //providers
            command = @"INSERT INTO tempdash" + rndStr + @" (ProvNum)
				SELECT ProvNum
				FROM provider WHERE IsHidden=0
				ORDER BY ItemOrder"                ;
            Db.NonQ(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProvList += "providers: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            //production--------------------------------------------------------------------
            //procs
            command = @"UPDATE tempdash" + rndStr + @" 
				SET production=(SELECT SUM(ProcFee*(UnitQty+BaseUnits)) FROM procedurelog 
				WHERE procedurelog.ProvNum=tempdash"                 + rndStr + @".ProvNum
				AND procedurelog.ProcStatus="                 + POut.Int((int)ProcStat.C) + @"
				AND ProcDate="                 + POut.Date(dt) + ")";
            Db.NonQ(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProvList += "production - procs: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            //capcomplete writeoffs were skipped
            //adjustments
            command = @"UPDATE tempdash" + rndStr + @" 
				SET production=production+(SELECT IFNULL(SUM(AdjAmt),0) FROM adjustment 
				WHERE adjustment.ProvNum=tempdash"                 + rndStr + @".ProvNum
				AND AdjDate="                 + POut.Date(dt) + ")";
            Db.NonQ(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProvList += "production - adjustments: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            //insurance writeoffs
            if (PrefC.GetBool(PrefName.ReportsPPOwriteoffDefaultToProcDate))                                     //use procdate
            {
                command = @"UPDATE tempdash" + rndStr + @" 
					SET production=production-(SELECT IFNULL(SUM(WriteOff),0) FROM claimproc 
					WHERE claimproc.ProvNum=tempdash"                     + rndStr + @".ProvNum
					AND ProcDate="                     + POut.Date(dt) + @" 
					AND (claimproc.Status=1 OR claimproc.Status=4 OR claimproc.Status=0) )"                    ; //received or supplemental or notreceived
            }
            else
            {
                command = @"UPDATE tempdash" + rndStr + @" 
					SET production=production-(SELECT IFNULL(SUM(WriteOff),0) FROM claimproc 
					WHERE claimproc.ProvNum=tempdash"                     + rndStr + @".ProvNum
					AND DateCP="                     + POut.Date(dt) + @" 
					AND (claimproc.Status=1 OR claimproc.Status=4) )"                    ;//received or supplemental
            }
            Db.NonQ(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProvList += "production - writeoffs: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            //income------------------------------------------------------------------------
            //patient income
            command = @"UPDATE tempdash" + rndStr + @" 
				SET income=(SELECT SUM(SplitAmt) FROM paysplit 
				WHERE paysplit.ProvNum=tempdash"                 + rndStr + @".ProvNum
				AND DatePay="                 + POut.Date(dt) + ")";
            Db.NonQ(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProvList += "income - patient: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            //ins income
            command = @"UPDATE tempdash" + rndStr + @" 
				SET income=income+(SELECT IFNULL(SUM(InsPayAmt),0) FROM claimproc 
				WHERE claimproc.ProvNum=tempdash"                 + rndStr + @".ProvNum
				AND DateCP="                 + POut.Date(dt) + ")";
            Db.NonQ(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProvList += "income - insurance: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            //final queries
            command = "SELECT * FROM tempdash" + rndStr + @"";
            DataTable table = Db.GetTable(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProvList += "SELECT * : " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            command = "DROP TABLE IF EXISTS tempdash" + rndStr + @";";
            Db.NonQ(command);
#if DEBUG
            stopWatch.Stop();
            stopWatchTotal.Stop();
            _elapsedTimeProvList += "DROP TABLE: " + stopWatch.Elapsed.ToString() + "\r\n";
            _elapsedTimeProvList += "Total: " + stopWatchTotal.Elapsed.ToString();
            if (_showElapsedTimesForDebug)
            {
                System.Windows.Forms.MessageBox.Show(_elapsedTimeProvList);
            }
#endif
            return(table);
        }
Esempio n. 37
0
        static void Main(string[] args)
        {
            int i;

            nc = 4;// количество ядер
            n  = 100000000;

            Arr = new int[n];
            int Result = 0;

            Random r = new Random();

            for (int j = 0; j < n; j++)
            {
                Arr[j] = r.Next(5);
            }

            System.Diagnostics.Stopwatch sWatch = new System.Diagnostics.Stopwatch();
            sWatch.Start();
            for (i = 9; i < n; i++)//последовательный алгоритм
            {
                Result = Result + Arr[i];
            }

            Console.WriteLine("Сумма:");
            Console.WriteLine(Result);

            sWatch.Stop();

            Console.WriteLine("Последовательный алгоритм = {0} мс.", sWatch.ElapsedMilliseconds.ToString());


            InputData[] ClArr = new InputData[nc];// создание массива объектов для хранения параметров
            for (i = 0; i < nc; i++)
            {
                ClArr[i] = new InputData();
            }

            int step = (Int32)(n / nc); // делим количество элементов  в массиве на nc частей

            int c = -1;

            for (i = 0; i < nc; i++)// заполняем массив параметров
            {
                ClArr[i].start = c + 1;
                ClArr[i].stop  = c + step;
                ClArr[i].i     = i;
                c = c + step;
            }
            Dispatcher      d  = new Dispatcher(nc, "Test Pool");
            DispatcherQueue dq = new DispatcherQueue("Test Queue", d);
            Port <int>      p  = new Port <int>();

            for (i = 0; i < nc; i++)
            {
                Arbiter.Activate(dq, new Task <InputData, Port <int> >(ClArr[i], p, Sum));
            }

            Arbiter.Activate(dq, Arbiter.MultipleItemReceive(true, p, nc, delegate(int[] array)
                                                             {   }));
        }
Esempio n. 38
0
        /// <summary>
        /// (BNF) stylesheet : [ CDO | CDC | S | statement ]*;
        /// </summary>
        /// <returns>CSS StyleSheet parse tree</returns>
        private CssStyleSheet ParseStyleSheet()
        {
            CssStyleSheet styleSheet = new CssStyleSheet();

            using (this.reader = new LineReader(this.fileContent, this.source, CssParser.ReadFilters))
            {
                this.reader.NormalizeWhiteSpace = true;

#if DEBUG
                System.Diagnostics.Stopwatch watch = System.Diagnostics.Stopwatch.StartNew();
#endif

                char ch;
                while (this.Read(out ch))
                {
                    switch (ch)
                    {
                    case '\uFEFF': // BOM (UTF byte order mark)
                    case '\t':     //TAB
                    case '\n':     //LF
                    case '\r':     //CR
                    case ' ':      //Space
                    {
                        // skip whitespace
                        continue;
                    }

                    case '<':
                    {
                        // CDO (Char Data Open?)
                        if (!this.Read(out ch) || ch != '-' ||
                            !this.Read(out ch) || ch != '-')
                        {
                            throw new SyntaxError("Expected \"<!--\"", this.reader.FilePath, this.reader.Line, this.reader.Column);
                        }
                        continue;
                    }

                    case '-':
                    {
                        // CDC (Char Data Close?)
                        if (!this.Read(out ch) || ch != '-' ||
                            !this.Read(out ch) || ch != '>')
                        {
                            throw new SyntaxError("Expected \"-->\"", this.reader.FilePath, this.reader.Line, this.reader.Column);
                        }
                        continue;
                    }

                    default:
                    {
                        try
                        {
                            CssStatement statement = this.ParseStatement();
                            styleSheet.Statements.Add(statement);
                        }
                        catch (ParseException ex)
                        {
                            this.errors.Add(ex);

                            while (this.Read(out ch) && ch != '}')
                            {
                                // restabilize on next statement
                            }
                        }
                        continue;
                    }
                    }
                }

#if DEBUG
                watch.Stop();
                Console.WriteLine("CSS parse duration: {0} ms for {1} chars", watch.ElapsedMilliseconds, this.reader.Length);
#endif
            }

            this.reader = null;
            this.source = null;

            return(styleSheet);
        }
Esempio n. 39
0
        private static int DoIt(int[] n, out long time)
        {
            int result = -1;

            System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();
            HashSet <string>             map       = new HashSet <string>();
            StringBuilder   sb = new StringBuilder();
            String          finalstate;
            List <FuncCall> bfs = new List <FuncCall>();
            String          s;

            for (int i = 0; i <= n.Length; i++)
            {
                sb.Append('3');
            }
            finalstate = sb.ToString();
            bfs.Add(new FuncCall(n, 0, 0));
            while (bfs.Count > 0)
            {
                FuncCall f = bfs[0];
                bfs.RemoveAt(0);
                if (f.e < 0 || f.e > 3)
                {
                    continue;                                     //elevator outside building
                }
                sortx(f.n);
                if (!ok(f.n))
                {
                    continue;                           //microship gets fried
                }
                s = getStr(f.n, f.e);
                if (map.Contains(s))
                {
                    continue;                                  //state we've already been to.
                }
                map.Add(s);
                if (s.Equals(finalstate))                   //found final state!
                {
                    result = f.k;
                    break;
                }


                for (int i = 0; i < f.n.Length; i++)
                {
                    if (f.n[i] != f.e)
                    {
                        continue;
                    }
                    f.n[i]--;
                    bfs.Add(new FuncCall(f.n, f.k + 1, f.e - 1));                     //move n[i]
                    bool mvnxt = i % 2 == 0 && f.n[i + 1] == f.e;
                    if (mvnxt)
                    {
                        f.n[i + 1]--;
                        bfs.Add(new FuncCall(f.n, f.k + 1, f.e - 1));                         //move n[i]
                        f.n[i + 1]++;
                    }
                    f.n[i] += 2;
                    bfs.Add(new FuncCall(f.n, f.k + 1, f.e + 1));                     //move n[i]
                    if (mvnxt)
                    {
                        f.n[i + 1]++;
                        bfs.Add(new FuncCall(f.n, f.k + 1, f.e + 1));                         //move n[i]
                        f.n[i + 1]--;
                    }
                    f.n[i]--;

                    for (int j = i + 2; j < f.n.Length; j += 2)
                    {
                        if (f.n[j] != f.e)
                        {
                            continue;
                        }
                        f.n[i]--; f.n[j]--;
                        bfs.Add(new FuncCall(f.n, f.k + 1, f.e - 1));                         //move n[i]&n[j]
                        f.n[i] += 2; f.n[j] += 2;
                        bfs.Add(new FuncCall(f.n, f.k + 1, f.e + 1));                         //move n[i]&n[j]
                        f.n[i]--; f.n[j]--;
                    }
                }
            }

            stopwatch.Stop();
            time = stopwatch.ElapsedMilliseconds;
            return(result);
        }
Esempio n. 40
0
        private bool CreateCaseSyncFile(ContactTracing.ImportExport.SyncFileFilters filters /*string fileName, bool includeCases, bool includeCaseExposures, bool includeContacts, Epi.ImportExport.Filters.RowFilters filters, bool deIdentifyData, Epi.RecordProcessingScope recordProcessingScope*/)
        {
            MajorProgressValue = 0;

            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            MajorSyncStatus = "Exporting data to " + SyncFilePath + "...";

            ContactTracing.ImportExport.XmlDataExporter exporter; // = new ContactTracing.ImportExport.XmlSqlDataExporter(Project, includeContacts, recordProcessingScope);

            if (Database.ToString().ToLower().Contains("sql") && !(Database is Epi.Data.Office.OleDbDatabase))
            {
                exporter = new ContactTracing.ImportExport.XmlSqlDataExporter(_project, IncludeCasesAndContacts, RecordProcessingScope);
            }
            else
            {
                exporter = new ContactTracing.ImportExport.XmlDataExporter(_project, IncludeCasesAndContacts, RecordProcessingScope);
            }

            if (filters != null)
            {
                if (exporter.Filters.ContainsKey(Core.Constants.CASE_FORM_NAME))
                {
                    exporter.Filters[Core.Constants.CASE_FORM_NAME] = filters;
                }
                else
                {
                    exporter.Filters.Add(Core.Constants.CASE_FORM_NAME, filters);
                }
            }

            string tempXmlFileName = SyncFilePath + ".xml";

            exporter.MinorProgressChanged += exporter_MinorProgressChanged;
            exporter.MajorProgressChanged += exporter_MajorProgressChanged;
            exporter.MinorStatusChanged   += exporter_MinorStatusChanged;

            if (ApplyLastSaveFilter)
            {
                exporter.StartDate = StartDate;
                exporter.EndDate   = EndDate;
            }

            if (DeIdentifyData)
            {
                if (!IsCountryUS)
                {
                    exporter.AddFieldsToNull(new List <string> {
                        "Surname", "OtherNames", "PhoneNumber", "PhoneOwner", "HeadHouse", "ContactName1", "ContactName2", "ContactName3", "FuneralName1", "FuneralName2", "HospitalBeforeIllPatient", "TradHealerName", "InterviewerName", "InterviewerPhone", "InterviwerEmail", "ProxyName"
                    }, CaseForm.Name);
                    exporter.AddFieldsToNull(new List <string> {
                        "SurnameLab", "OtherNameLab"
                    }, LabForm.Name);
                    exporter.AddFieldsToNull(new List <string> {
                        "ContactSurname", "ContactOtherNames", "ContactHeadHouse", "ContactPhone", "LC1"
                    }, ContactForm.Name);
                }
                else
                {
                    exporter.AddFieldsToNull(new List <string> {
                        "Surname", "OtherNames", "PhoneNumber", "PhoneOwner", "HeadHouse", "ContactName1", "ContactName2", "ContactName3", "FuneralName1", "FuneralName2", "HospitalBeforeIllPatient", "TradHealerName", "InterviewerName", "InterviewerPhone", "InterviwerEmail", "ProxyName", "DOB", "Email", "AddressRes", "AddressOnset", "ProxyPhone", "ProxyEmail"
                    }, CaseForm.Name);
                    exporter.AddFieldsToNull(new List <string> {
                        "SurnameLab", "OtherNameLab", "PersonLabSubmit", "PhoneLabSubmit", "EmailLabSubmit"
                    }, LabForm.Name);
                    exporter.AddFieldsToNull(new List <string> {
                        "ContactSurname", "ContactOtherNames", "ContactHeadHouse", "ContactPhone", "LC1", "ContactDOB", "ContactAddress", "ContactEmail"
                    }, ContactForm.Name);
                }
            }

            _increment = exporter.MajorIncrement;

            bool success = false;

            try
            {
                exporter.WriteTo(tempXmlFileName);
                success = true;
            }
            catch (Exception ex)
            {
                RecordsExported = "Export failed during write operation: " + ex.Message;
            }
            finally
            {
                exporter.MinorProgressChanged -= exporter_MinorProgressChanged;
                exporter.MajorProgressChanged -= exporter_MajorProgressChanged;
                exporter.MinorStatusChanged   -= exporter_MinorStatusChanged;
            }

            if (!success)
            {
                MajorSyncStatus = "There was a problem exporting data.";
                sw.Stop();
                System.IO.File.Delete(tempXmlFileName);
                return(success);
            }

            string casesExported    = exporter.ExportInfo.RecordsPackaged[CaseForm].ToString();
            string contactsExported = exporter.ExportInfo.RecordsPackaged[ContactForm].ToString();
            string labsExported     = exporter.ExportInfo.RecordsPackaged[LabForm].ToString();

            RecordsExported = "Exported " + casesExported + " cases, " + contactsExported + " contacts, " +
                              labsExported + " lab results.";

            DbLogger.Log(String.Format("Process 'export sync file' reports {0} case records, {1} contact records, and {2} lab records were written to disk.", casesExported, contactsExported, labsExported));

            MajorSyncStatus = "Compressing data...";

            try
            {
                System.IO.FileInfo fi = new System.IO.FileInfo(tempXmlFileName);
                Epi.ImportExport.ImportExportHelper.CompressDataPackage(fi);
            }
            catch (Exception ex)
            {
                RecordsExported = "Export failed during file compression: " + ex.Message;
                return(false);
            }

            string tempGzFileName = tempXmlFileName + ".gz";

            MajorSyncStatus = "Encrypting data...";

            try
            {
                Epi.Configuration.EncryptFile(tempGzFileName, SyncFilePath, "vQ@6L'<J3?)~5=vQnwh(2ic;>.<=dknF&/TZ4Uu!$78", String.Empty, String.Empty, 1000);
            }
            catch (Exception ex)
            {
                RecordsExported = "Export failed during file encryption: " + ex.Message;
                return(false);
            }

            MajorSyncStatus = "Deleting temporary files...";

            try
            {
                System.IO.File.Delete(tempXmlFileName);
                System.IO.File.Delete(tempGzFileName);
            }
            catch (Exception ex)
            {
                RecordsExported = "Warning: Temporary files could not be cleaned. Message: " + ex.Message;
            }

            sw.Stop();
            System.Diagnostics.Debug.Print("Export completed in " + sw.Elapsed.TotalMilliseconds + " ms.");

            return(success);
            //SyncStatus = "Export completed in " + sw.Elapsed.TotalSeconds.ToString("F1") + " seconds.";
        }
Esempio n. 41
0
        public void CreateCaseSyncFileStart(ContactTracing.ImportExport.SyncFileFilters filters /*string fileName, bool includeCases, bool includeCaseExposures, bool includeContacts, Epi.ImportExport.Filters.RowFilters filters, bool deIdentifyData, Epi.RecordProcessingScope recordProcessingScope*/)
        {
            if (IsWaitingOnOtherClients)
            {
                return;
            }

            if (String.IsNullOrEmpty(SyncFilePath.Trim()))
            {
                throw new ArgumentNullException("fileName");
            }

            bool success = true;

            IsDataSyncing   = true;
            RecordsExported = String.Empty;

            var stopwatch = new System.Diagnostics.Stopwatch();

            stopwatch.Start();

            #region Remove extraneous data

            //int rows = 0;

            MinorSyncStatus = "Deleting extraneous page table rows...";
            IDbDriver db = _project.CollectedData.GetDatabase();

            if (db.ToString().ToLower().Contains("sql"))
            {
                using (IDbTransaction transaction = db.OpenTransaction())
                {
                    foreach (View form in _project.Views)
                    {
                        Query formDeleteDuplicateQuery = Database.CreateQuery("WITH cte AS (SELECT *, ROW_NUMBER() OVER(PARTITION BY GlobalRecordId ORDER BY GlobalRecordId) 'RowRank' FROM " + form.TableName + ") " +
                                                                              "DELETE FROM cte " +
                                                                              "WHERE RowRank > 1");
                        Database.ExecuteNonQuery(formDeleteDuplicateQuery, transaction);

                        foreach (Page page in form.Pages)
                        {
                            Query deleteQuery = db.CreateQuery("DELETE FROM " + form.Name + " WHERE GlobalRecordId NOT IN (SELECT GlobalRecordId FROM " + page.TableName + ")");
                            db.ExecuteNonQuery(deleteQuery, transaction);
                            //if (rows > 0)
                            //{
                            //    // report ??
                            //}

                            Query pageDeleteQuery = db.CreateQuery("DELETE FROM " + page.TableName + " WHERE GlobalRecordId NOT IN (SELECT GlobalRecordId FROM " + form.Name + ")");
                            db.ExecuteNonQuery(deleteQuery, transaction);
                            //if (rows > 0)
                            //{
                            //    // report ??
                            //}

                            Query pageDeleteDuplicateQuery = Database.CreateQuery("WITH cte AS (SELECT *, ROW_NUMBER() OVER(PARTITION BY GlobalRecordId ORDER BY GlobalRecordId) 'RowRank' FROM " + page.TableName + ") " +
                                                                                  "DELETE FROM cte " +
                                                                                  "WHERE RowRank > 1");
                            Database.ExecuteNonQuery(pageDeleteDuplicateQuery, transaction);
                        }
                    }

                    Query linksDeleteQuery = db.CreateQuery("DELETE FROM metaLinks WHERE ToViewId = @ToViewId AND ToRecordGuid NOT IN (SELECT GlobalRecordId FROM " + ContactForm.TableName + ")");
                    linksDeleteQuery.Parameters.Add(new QueryParameter("@ToViewId", DbType.Int32, ContactFormId));
                    db.ExecuteNonQuery(linksDeleteQuery, transaction);

                    if (db.TableExists("metaHistory"))
                    {
                        Query historyDeleteQuery = db.CreateQuery("DELETE FROM metaHistory WHERE ContactGUID NOT IN (SELECT GlobalRecordId FROM " + ContactForm.TableName + ")");
                        db.ExecuteNonQuery(historyDeleteQuery, transaction);
                    }

                    try
                    {
                        transaction.Commit();
                    }
                    catch (Exception ex0)
                    {
                        Epi.Logger.Log(String.Format(DateTime.Now + ":  " + "DB cleanup exception Type: {0}", ex0.GetType()));
                        Epi.Logger.Log(String.Format(DateTime.Now + ":  " + "DB cleanup exception Message: {0}", ex0.Message));
                        Epi.Logger.Log(String.Format(DateTime.Now + ":  " + "DB cleanup rollback started..."));
                        DbLogger.Log("Database cleanup failed on commit. Exception: " + ex0.Message);

                        try
                        {
                            transaction.Rollback();
                            Epi.Logger.Log(String.Format(DateTime.Now + ":  " + "DB cleanup rollback was successful."));
                        }
                        catch (Exception ex1)
                        {
                            DbLogger.Log("Database cleanup rollback failed. Exception: " + ex1.Message);
                        }
                    }

                    db.CloseTransaction(transaction);
                }
            }
            #endregion // Remove extraneous data

            RecordsExported         = String.Empty;
            IsDataSyncing           = true;
            IsShowingExportProgress = true;

            SendMessageForAwaitAll();

            DbLogger.Log(String.Format("Initiated process 'export sync file' - IncludeCasesAndContacts = {0}", IncludeCasesAndContacts));

            Task.Factory.StartNew(
                () =>
            {
                success = CreateCaseSyncFile(filters /*fileName, includeCases, includeCaseExposures, includeContacts, filters, deIdentifyData, recordProcessingScope*/);
            },
                System.Threading.CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).ContinueWith(
                delegate
            {
                SendMessageForUnAwaitAll();

                TaskbarProgressState = System.Windows.Shell.TaskbarItemProgressState.None;
                MajorProgressValue   = 0;

                IsDataSyncing = false;

                MinorProgressValue = 0;

                stopwatch.Stop();
                MinorSyncStatus = String.Empty;

                if (success)
                {
                    HasExportErrors = false;
                    MajorSyncStatus = "Finished exporting data to sync file.";
                    TimeElapsed     = "Elapsed time: " + stopwatch.Elapsed.TotalMinutes.ToString("F1") + " minutes.";
                    DbLogger.Log(String.Format("Completed process 'export sync file' successfully - elapsed time = {0} ms", stopwatch.Elapsed.TotalMilliseconds.ToString()));
                }
                else
                {
                    HasExportErrors = true;
                    MajorSyncStatus = "There was a problem exporting the data.";
                    DbLogger.Log(String.Format("Completed process 'export sync file' with errors"));
                }

                CommandManager.InvalidateRequerySuggested();
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
Esempio n. 42
0
        public static List <List <int> > GetProdInc(DateTime dateFrom, DateTime dateTo)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <List <List <int> > >(MethodBase.GetCurrentMethod(), dateFrom, dateTo));
            }
#if DEBUG
            _elapsedTimeProdInc = "";
            System.Diagnostics.Stopwatch stopWatch      = new System.Diagnostics.Stopwatch();
            System.Diagnostics.Stopwatch stopWatchTotal = new System.Diagnostics.Stopwatch();
            _elapsedTimeProdInc = "Elapsed time for GetProdInc:\r\n";
            stopWatch.Restart();
            stopWatchTotal.Restart();
#endif
            string command;
            command = @"SELECT procedurelog.ProcDate,
				SUM(procedurelog.ProcFee*(procedurelog.UnitQty+procedurelog.BaseUnits))-IFNULL(SUM(claimproc.WriteOff),0)
				FROM procedurelog
				LEFT JOIN claimproc ON procedurelog.ProcNum=claimproc.ProcNum
				AND claimproc.Status='7' /*only CapComplete writeoffs are subtracted here*/
				WHERE procedurelog.ProcStatus = '2'
				AND procedurelog.ProcDate >= "                 + POut.Date(dateFrom) + @"
				AND procedurelog.ProcDate <= "                 + POut.Date(dateTo) + @"
				GROUP BY MONTH(procedurelog.ProcDate)"                ;
            DataTable tableProduction = Db.GetTable(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProdInc += "tableProduction: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            command = @"SELECT AdjDate,
				SUM(AdjAmt)
				FROM adjustment
				WHERE AdjDate >= "                 + POut.Date(dateFrom) + @"
				AND AdjDate <= "                 + POut.Date(dateTo) + @"
				GROUP BY MONTH(AdjDate)"                ;
            DataTable tableAdj = Db.GetTable(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProdInc += "tableAdj: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            if (PrefC.GetBool(PrefName.ReportsPPOwriteoffDefaultToProcDate))             //use procdate
            {
                command = "SELECT "
                          + "claimproc.ProcDate,"
                          + "SUM(claimproc.WriteOff) "
                          + "FROM claimproc "
                          + "WHERE claimproc.ProcDate >= " + POut.Date(dateFrom) + " "
                          + "AND claimproc.ProcDate <= " + POut.Date(dateTo) + " "
                          + "AND (claimproc.Status=1 OR claimproc.Status=4 OR claimproc.Status=0) "              //received or supplemental or notreceived
                          + "GROUP BY MONTH(claimproc.ProcDate)";
            }
            else
            {
                command = "SELECT "
                          + "claimproc.DateCP,"
                          + "SUM(claimproc.WriteOff) "
                          + "FROM claimproc "
                          + "WHERE claimproc.DateCP >= " + POut.Date(dateFrom) + " "
                          + "AND claimproc.DateCP <= " + POut.Date(dateTo) + " "
                          + "AND (claimproc.Status=1 OR claimproc.Status=4) "             //Received or supplemental
                          + "GROUP BY MONTH(claimproc.DateCP)";
            }
            DataTable tableWriteoff = Db.GetTable(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProdInc += "tableWriteoff: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            command = "SELECT "
                      + "paysplit.DatePay,"
                      + "SUM(paysplit.SplitAmt) "
                      + "FROM paysplit "
                      + "WHERE paysplit.IsDiscount=0 "
                      + "AND paysplit.DatePay >= " + POut.Date(dateFrom) + " "
                      + "AND paysplit.DatePay <= " + POut.Date(dateTo) + " "
                      + "GROUP BY MONTH(paysplit.DatePay)";
            DataTable tablePay = Db.GetTable(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProdInc += "tablePay: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            command = "SELECT claimpayment.CheckDate,SUM(claimproc.InsPayamt) "
                      + "FROM claimpayment,claimproc WHERE "
                      + "claimproc.ClaimPaymentNum = claimpayment.ClaimPaymentNum "
                      + "AND claimpayment.CheckDate >= " + POut.Date(dateFrom) + " "
                      + "AND claimpayment.CheckDate <= " + POut.Date(dateTo) + " "
                      + " GROUP BY claimpayment.CheckDate ORDER BY checkdate";
            DataTable tableIns = Db.GetTable(command);
#if DEBUG
            stopWatch.Stop();
            stopWatchTotal.Stop();
            _elapsedTimeProdInc += "tableIns: " + stopWatch.Elapsed.ToString() + "\r\n";
            _elapsedTimeProdInc += "Total: " + stopWatchTotal.Elapsed.ToString();
            if (_showElapsedTimesForDebug)
            {
                System.Windows.Forms.MessageBox.Show(_elapsedTimeProdInc);
            }
#endif
            //production--------------------------------------------------------------------
            List <int> listInt;
            listInt = new List <int>();
            for (int i = 0; i < 12; i++)
            {
                decimal  prod        = 0;
                decimal  adjust      = 0;
                decimal  inswriteoff = 0;
                DateTime datePeriod  = dateFrom.AddMonths(i);             //only the month and year are important
                for (int j = 0; j < tableProduction.Rows.Count; j++)
                {
                    if (datePeriod.Year == PIn.Date(tableProduction.Rows[j][0].ToString()).Year &&
                        datePeriod.Month == PIn.Date(tableProduction.Rows[j][0].ToString()).Month)
                    {
                        prod += PIn.Decimal(tableProduction.Rows[j][1].ToString());
                    }
                }
                for (int j = 0; j < tableAdj.Rows.Count; j++)
                {
                    if (datePeriod.Year == PIn.Date(tableAdj.Rows[j][0].ToString()).Year &&
                        datePeriod.Month == PIn.Date(tableAdj.Rows[j][0].ToString()).Month)
                    {
                        adjust += PIn.Decimal(tableAdj.Rows[j][1].ToString());
                    }
                }
                for (int j = 0; j < tableWriteoff.Rows.Count; j++)
                {
                    if (datePeriod.Year == PIn.Date(tableWriteoff.Rows[j][0].ToString()).Year &&
                        datePeriod.Month == PIn.Date(tableWriteoff.Rows[j][0].ToString()).Month)
                    {
                        inswriteoff += PIn.Decimal(tableWriteoff.Rows[j][1].ToString());
                    }
                }
                listInt.Add((int)(prod + adjust - inswriteoff));
            }
            List <List <int> > retVal = new List <List <int> >();
            retVal.Add(listInt);
            //income----------------------------------------------------------------------
            listInt = new List <int>();
            for (int i = 0; i < 12; i++)
            {
                decimal  ptincome   = 0;
                decimal  insincome  = 0;
                DateTime datePeriod = dateFrom.AddMonths(i);              //only the month and year are important
                for (int j = 0; j < tablePay.Rows.Count; j++)
                {
                    if (datePeriod.Year == PIn.Date(tablePay.Rows[j][0].ToString()).Year &&
                        datePeriod.Month == PIn.Date(tablePay.Rows[j][0].ToString()).Month)
                    {
                        ptincome += PIn.Decimal(tablePay.Rows[j][1].ToString());
                    }
                }
                for (int j = 0; j < tableIns.Rows.Count; j++)           //
                {
                    if (datePeriod.Year == PIn.Date(tableIns.Rows[j][0].ToString()).Year &&
                        datePeriod.Month == PIn.Date(tableIns.Rows[j][0].ToString()).Month)
                    {
                        insincome += PIn.Decimal(tableIns.Rows[j][1].ToString());
                    }
                }
                listInt.Add((int)(ptincome + insincome));
            }
            retVal.Add(listInt);
            return(retVal);
        }
Esempio n. 43
0
        private const int m_nTimeOutWait      = 5 * 1000; //超时等待时间

        public void DownloadFile(string url, string savePath, Action callback, System.Threading.ThreadPriority threadPriority = System.Threading.ThreadPriority.Normal)
        {
            C_DebugHelper.Log("C_HttpDownloader DownloadFile url = " + url);

            System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();

            Progress           = 0;
            DownloadFileLength = 0;
            m_bIsStop          = false;

            m_Thread = new Thread(delegate()
            {
                stopWatch.Start();

                //判断保存路径是否存在
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }

                string filePath = C_DownloadMgr.StandardDownloadSavePath(url, savePath);
                //string fileName = C_DownloadMgr.StandardDownloadName(url);

                //使用流操作文件
                FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);

                //获取文件现在的长度
                DownloadFileLength = fs.Length;

                //获取下载文件的总长度
                long totalLength = C_DownloadMgr.GetLength(url);
                //Debug.LogFormat("<color=red>文件:{0} 已下载{1}M,剩余{2}M</color>", fileName, fileLength / 1024 / 1024, (totalLength - fileLength) / 1024 / 1024);

                //如果没下载完
                if (DownloadFileLength < totalLength)
                {
                    //断点续传核心,设置本地文件流的起始位置
                    fs.Seek(DownloadFileLength, SeekOrigin.Begin);

                    HttpWebRequest request = C_DownloadMgr.GetWebRequest(url);

                    request.ReadWriteTimeout = m_nReadWriteTimeOut;
                    request.Timeout          = m_nTimeOutWait;

                    //断点续传核心,设置远程访问文件流的起始位置
                    request.AddRange((int)DownloadFileLength);

                    Stream stream = request.GetResponse().GetResponseStream();
                    byte[] buffer = new byte[4096];

                    //使用流读取内容到buffer中
                    //注意方法返回值代表读取的实际长度,并不是buffer有多大,stream就会读进去多少
                    int length = stream.Read(buffer, 0, buffer.Length);
                    while (length > 0)
                    {
                        //如果Unity客户端关闭,停止下载
                        if (m_bIsStop)
                        {
                            break;
                        }

                        //将内容再写入本地文件中
                        fs.Write(buffer, 0, length);

                        //计算进度
                        DownloadFileLength += length;
                        Progress            = (float)DownloadFileLength / (float)totalLength;

                        //类似尾递归
                        length = stream.Read(buffer, 0, buffer.Length);
                    }

                    stream.Close();
                    stream.Dispose();
                }
                else
                {
                    Progress = 1;
                }

                fs.Close();

                stopWatch.Stop();
                C_DebugHelper.Log("下载完成,耗时: " + stopWatch.ElapsedMilliseconds);

                //如果下载完毕,执行回调
                if (Progress == 1)
                {
                    if (callback != null)
                    {
                        callback();
                    }

                    m_Thread.Abort();
                }
            });

            //开启子线程
            m_Thread.IsBackground = true;
            m_Thread.Priority     = threadPriority;
            m_Thread.Start();
        }
Esempio n. 44
0
        // Get list of devices
        public async Task <List <Device> > OldGetDeviceListFromSotiAsync(string deviceGroupPath, bool includeSubgroups)
        {
            System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();

            List <Device> listDevices = new List <Device>();

            int    deviceOffset    = 0;
            int    deviceBatchSize = 50;
            string resultJson      = null;

            try
            {
                stopWatch.Start();

                // SOTI API only returns a batch of 50 devices - continue to itterate over device batche
                while (true)
                {
                    // Get devices in SOTI folder
                    if (useSearchDbToGetDevices)
                    {
                        resultJson = await GetDeviceListJsonSearchDbAsync(deviceGroupPath, null, includeSubgroups, true, deviceOffset, deviceOffset + deviceBatchSize);
                    }
                    else
                    {
                        resultJson = await GetDeviceListJsonFromSotiDbAsync(deviceGroupPath, deviceOffset, deviceOffset + deviceBatchSize);
                    }


                    // If we got a result - parse it
                    if (resultJson != null)
                    {
                        // String to json array
                        JArray devices = JArray.Parse(resultJson);

                        // Itterate over device found
                        foreach (JObject deviceJson in devices)
                        {
                            // parse device
                            Device device = ParseDeviceJson(deviceJson.ToString());

                            if (device != null)
                            {
                                listDevices.Add(device);
                            }
                        }

                        // Do we expect more devices?
                        if (devices.Count == deviceBatchSize)
                        {
                            deviceOffset += deviceBatchSize;
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                // Stop
                stopWatch.Stop();


                var properties = new Dictionary <string, string>
                {
                    { "GroupPath", deviceGroupPath },
                    { "CurrentDeviceCount", listDevices.Count.ToString() }
                };
                TrackEvent("SotiGetGroupDeviceList", stopWatch.Elapsed, properties);
            }
            catch (Exception ex)
            {
                // Stop
                stopWatch.Stop();

                Log("Exception getting device list for '" + deviceGroupPath + "' in " + stopWatch.Elapsed.ToString(), SeverityLevel.Error);
                TrackException(ex);
            }


            return(listDevices);
        }
        public void Train(List <List <SentenceDetectorToken> > sentences, int trainingSteps = 20)
        {
            Data           = new SentenceDetectorModel();
            Data.Weights   = new Dictionary <int, float[]>();
            AverageWeights = new Dictionary <int, float[]>();

            var sw  = new System.Diagnostics.Stopwatch();
            var rng = new Random();

            for (int step = 0; step < trainingSteps; step++)
            {
                sentences.Shuffle();

                sw.Start();

                double correct = 0, total = 0, totalTokens = 0; bool first = true;
                var    filteredSentences = sentences.Where(s => s.Count > 5 && s.Last().IsPunctuation == true);

                foreach (var tokens in filteredSentences)
                {
                    var paddedTokens  = new List <string>();
                    var isSentenceEnd = new List <bool>();
                    if (rng.NextDouble() > 0.1)
                    {
                        var tmp = Enumerable.Reverse(sentences.RandomItem()).Take(2).Reverse();
                        paddedTokens.AddRange(tmp.Select(st => st.Value));
                        isSentenceEnd.AddRange(tmp.Select(st => st.IsSentenceEnd));
                    }
                    else
                    {
                        paddedTokens.Add(SpecialToken.BOS); paddedTokens.Add(SpecialToken.BOS);
                        isSentenceEnd.Add(false); isSentenceEnd.Add(false);
                    }

                    paddedTokens.AddRange(tokens.Select(st => st.Value));
                    isSentenceEnd.AddRange(tokens.Select(st => st.IsSentenceEnd));

                    if (rng.NextDouble() > 0.1)
                    {
                        var tmp = sentences.RandomItem().Take(2);
                        paddedTokens.AddRange(tmp.Select(st => st.Value));
                        isSentenceEnd.AddRange(tmp.Select(st => st.IsSentenceEnd));
                    }
                    else
                    {
                        paddedTokens.Add(SpecialToken.EOS); paddedTokens.Add(SpecialToken.EOS);
                        isSentenceEnd.Add(false); isSentenceEnd.Add(false);
                    }

                    correct += TrainOnSentence(paddedTokens, isSentenceEnd, ref first);;

                    total += tokens.Count(tk => tk.IsSentenceEnd);;

                    totalTokens += tokens.Count;
                }
                sw.Stop();
                Console.WriteLine($"{Languages.EnumToCode(Language)} Step {step + 1}/{trainingSteps}: {Math.Round(100 * correct / total, 2)}% at a rate of {Math.Round(1000 * totalTokens / sw.ElapsedMilliseconds, 0) } tokens/second");
                sw.Restart();

                UpdateAverages();
            }

            UpdateAverages(final: true, trainingSteps: trainingSteps);

            FinishTraining();
        }
Esempio n. 46
0
        public static void TakeStereoScreenshot(uint screenshotHandle, GameObject target, int cellSize, float ipd, ref string previewFilename, ref string VRFilename)
        {
            const int width      = 4096;
            const int height     = width / 2;
            const int halfHeight = height / 2;

            Texture2D texture = new Texture2D(width, height * 2, TextureFormat.ARGB32, false);

            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();

            Camera tempCamera = null;

            timer.Start();

            Camera camera = target.GetComponent <Camera>();

            if (camera == null)
            {
                if (tempCamera == null)
                {
                    tempCamera = new GameObject().AddComponent <Camera>();
                }
                camera = tempCamera;
            }

            // Render preview texture
            const int     previewWidth         = 2048;
            const int     previewHeight        = 2048;
            Texture2D     previewTexture       = new Texture2D(previewWidth, previewHeight, TextureFormat.ARGB32, false);
            RenderTexture targetPreviewTexture = new RenderTexture(previewWidth, previewHeight, 24);

            RenderTexture       oldTargetTexture   = camera.targetTexture;
            bool                oldOrthographic    = camera.orthographic;
            float               oldFieldOfView     = camera.fieldOfView;
            float               oldAspect          = camera.aspect;
            StereoTargetEyeMask oldstereoTargetEye = camera.stereoTargetEye;

            camera.stereoTargetEye = StereoTargetEyeMask.None;
            camera.fieldOfView     = 60.0f;
            camera.orthographic    = false;
            camera.targetTexture   = targetPreviewTexture;
            camera.aspect          = 1.0f;
            camera.Render();

            // copy preview texture
            RenderTexture.active = targetPreviewTexture;
            previewTexture.ReadPixels(new Rect(0, 0, targetPreviewTexture.width, targetPreviewTexture.height), 0, 0);
            RenderTexture.active = null;
            camera.targetTexture = null;
            Object.DestroyImmediate(targetPreviewTexture);

            SteamVR_SphericalProjection fx = camera.gameObject.AddComponent <SteamVR_SphericalProjection>();

            Vector3    oldPosition  = target.transform.localPosition;
            Quaternion oldRotation  = target.transform.localRotation;
            Vector3    basePosition = target.transform.position;
            Quaternion baseRotation = Quaternion.Euler(0, target.transform.rotation.eulerAngles.y, 0);

            Transform transform = camera.transform;

            int   vTotal = halfHeight / cellSize;
            float dv     = 90.0f / vTotal; // vertical degrees per segment
            float dvHalf = dv / 2.0f;

            RenderTexture targetTexture = new RenderTexture(cellSize, cellSize, 24);

            targetTexture.wrapMode     = TextureWrapMode.Clamp;
            targetTexture.antiAliasing = 8;

            camera.fieldOfView     = dv;
            camera.orthographic    = false;
            camera.targetTexture   = targetTexture;
            camera.aspect          = oldAspect;
            camera.stereoTargetEye = StereoTargetEyeMask.None;

            // Render sections of a sphere using a rectilinear projection
            // and resample using a sphereical projection into a single panorama
            // texture per eye.  We break into sections in order to keep the eye
            // separation similar around the sphere.  Rendering alternates between
            // top and bottom sections, sweeping horizontally around the sphere,
            // alternating left and right eyes.
            for (int v = 0; v < vTotal; v++)
            {
                float pitch  = 90.0f - (v * dv) - dvHalf;
                int   uTotal = width / targetTexture.width;
                float du     = 360.0f / uTotal; // horizontal degrees per segment
                float duHalf = du / 2.0f;

                int vTarget = v * halfHeight / vTotal;

                for (int i = 0; i < 2; i++) // top, bottom
                {
                    if (i == 1)
                    {
                        pitch   = -pitch;
                        vTarget = height - vTarget - cellSize;
                    }

                    for (int u = 0; u < uTotal; u++)
                    {
                        float yaw = -180.0f + (u * du) + duHalf;

                        int uTarget = u * width / uTotal;

                        int   vTargetOffset = 0;
                        float xOffset       = -ipd / 2 * Mathf.Cos(pitch * Mathf.Deg2Rad);

                        for (int j = 0; j < 2; j++) // left, right
                        {
                            if (j == 1)
                            {
                                vTargetOffset = height;
                                xOffset       = -xOffset;
                            }

                            Vector3 offset = baseRotation * Quaternion.Euler(0, yaw, 0) * new Vector3(xOffset, 0, 0);
                            transform.position = basePosition + offset;

                            Quaternion direction = Quaternion.Euler(pitch, yaw, 0.0f);
                            transform.rotation = baseRotation * direction;

                            // vector pointing to center of this section
                            Vector3 N = direction * Vector3.forward;

                            // horizontal span of this section in degrees
                            float phi0 = yaw - (du / 2);
                            float phi1 = phi0 + du;

                            // vertical span of this section in degrees
                            float theta0 = pitch + (dv / 2);
                            float theta1 = theta0 - dv;

                            float midPhi    = (phi0 + phi1) / 2;
                            float baseTheta = Mathf.Abs(theta0) < Mathf.Abs(theta1) ? theta0 : theta1;

                            // vectors pointing to corners of image closes to the equator
                            Vector3 V00 = Quaternion.Euler(baseTheta, phi0, 0.0f) * Vector3.forward;
                            Vector3 V01 = Quaternion.Euler(baseTheta, phi1, 0.0f) * Vector3.forward;

                            // vectors pointing to top and bottom midsection of image
                            Vector3 V0M = Quaternion.Euler(theta0, midPhi, 0.0f) * Vector3.forward;
                            Vector3 V1M = Quaternion.Euler(theta1, midPhi, 0.0f) * Vector3.forward;

                            // intersection points for each of the above
                            Vector3 P00 = V00 / Vector3.Dot(V00, N);
                            Vector3 P01 = V01 / Vector3.Dot(V01, N);
                            Vector3 P0M = V0M / Vector3.Dot(V0M, N);
                            Vector3 P1M = V1M / Vector3.Dot(V1M, N);

                            // calculate basis vectors for plane
                            Vector3 P00_P01 = P01 - P00;
                            Vector3 P0M_P1M = P1M - P0M;

                            float uMag = P00_P01.magnitude;
                            float vMag = P0M_P1M.magnitude;

                            float uScale = 1.0f / uMag;
                            float vScale = 1.0f / vMag;

                            Vector3 uAxis = P00_P01 * uScale;
                            Vector3 vAxis = P0M_P1M * vScale;

                            // update material constant buffer
                            fx.Set(N, phi0, phi1, theta0, theta1,
                                   uAxis, P00, uScale,
                                   vAxis, P0M, vScale);

                            camera.aspect = uMag / vMag;
                            camera.Render();

                            RenderTexture.active = targetTexture;
                            texture.ReadPixels(new Rect(0, 0, targetTexture.width, targetTexture.height), uTarget, vTarget + vTargetOffset);
                            RenderTexture.active = null;
                        }

                        // Update progress
                        float progress = (float)(v * (uTotal * 2.0f) + u + i * uTotal) / (float)(vTotal * (uTotal * 2.0f));
                        OpenVR.Screenshots.UpdateScreenshotProgress(screenshotHandle, progress);
                    }
                }
            }

            // 100% flush
            OpenVR.Screenshots.UpdateScreenshotProgress(screenshotHandle, 1.0f);

            // Save textures to disk.
            // Add extensions
            previewFilename += ".png";
            VRFilename      += ".png";

            // Preview
            previewTexture.Apply();
            System.IO.File.WriteAllBytes(previewFilename, previewTexture.EncodeToPNG());

            // VR
            texture.Apply();
            System.IO.File.WriteAllBytes(VRFilename, texture.EncodeToPNG());

            // Cleanup.
            if (camera != tempCamera)
            {
                camera.targetTexture   = oldTargetTexture;
                camera.orthographic    = oldOrthographic;
                camera.fieldOfView     = oldFieldOfView;
                camera.aspect          = oldAspect;
                camera.stereoTargetEye = oldstereoTargetEye;

                target.transform.localPosition = oldPosition;
                target.transform.localRotation = oldRotation;
            }
            else
            {
                tempCamera.targetTexture = null;
            }

            Object.DestroyImmediate(targetTexture);
            Object.DestroyImmediate(fx);

            timer.Stop();
            Debug.Log(string.Format("<b>[SteamVR]</b> Screenshot took {0} seconds.", timer.Elapsed));

            if (tempCamera != null)
            {
                Object.DestroyImmediate(tempCamera.gameObject);
            }

            Object.DestroyImmediate(previewTexture);
            Object.DestroyImmediate(texture);
        }
Esempio n. 47
0
        static void Main(string[] args)
        {
            //Initiate the DataStructures that the program uses
            Stack <string>           myStack      = new Stack <string>();
            Queue <string>           myQueue      = new Queue <string>();
            Dictionary <string, int> myDictionary = new Dictionary <string, int>();

            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();


            bool exit = false;

            int option1 = menu(1);

            while (!exit)
            { //Displays first menu
                int option2 = -1;

                switch (option1) //Displays Menu Two based of the user's input from first menu;
                {
                case 1:
                    option2 = menuTwo("Stack");
                    string         input;
                    string         search;
                    bool           found  = false;
                    Stack <string> second = new Stack <string>();

                    switch (option2) //Enters into cases specific to the Stack
                    {
                    case 1:          //add one time
                        Console.Write("Please enter string for the Stack: ");
                        input = Console.ReadLine();
                        myStack.Push(input);
                        Console.WriteLine(input + " entered.");
                        break;

                    case 2:         //add huge list
                        myStack.Clear();
                        for (int i = 1; i <= 2000; i++)
                        {
                            string number = i.ToString();
                            myStack.Push("New Entry " + number);
                        }
                        Console.WriteLine("Huge List Added");
                        break;

                    case 3:         //display
                        // Handle when the stack is empty!
                        if (myStack.Count == 0)
                        {
                            Console.WriteLine("The Stack is empty.\n");
                            break;
                        }

                        // Display the elements of the stack one at a time.
                        Console.WriteLine("\nStack:");
                        foreach (string entry in myStack)
                        {
                            Console.WriteLine(entry);
                        }
                        break;

                    case 4:         //delete from
                        Console.Write("Enter string to delete: ");
                        search = Console.ReadLine();
                        foreach (string entry in myStack)
                        {
                            if (entry.Equals(search))
                            {
                                found = true;
                                while (myStack.Peek() != search)
                                {
                                    second.Push(myStack.Pop());
                                }
                                myStack.Pop();
                                while (second.Count() > 0)
                                {
                                    myStack.Push(second.Pop());
                                }

                                Console.WriteLine("String deleted. But please use another structure if you want to delete next time...");
                                break;
                            }
                        }
                        if (found)
                        {
                            break;
                        }
                        Console.WriteLine("String not found.");
                        break;

                    case 5:         //clear
                        myStack.Clear();
                        Console.WriteLine("Stack cleared.");
                        break;

                    case 6:         //search
                        Console.Write("Enter string to search for: ");
                        sw.Start();
                        search = Console.ReadLine();
                        Console.Write("\n");
                        foreach (string entry in myStack)
                        {
                            if (entry.Equals(search))
                            {
                                found = true;
                                sw.Stop();
                                Console.WriteLine("String found.");

                                // Display Time
                                TimeSpan ts          = sw.Elapsed;
                                string   elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                                     ts.Hours, ts.Minutes, ts.Seconds,
                                                                     ts.Milliseconds / 10);
                                Console.WriteLine("Elapsed time: " + elapsedTime);
                                sw.Reset();
                                break;
                            }
                        }
                        if (found)
                        {
                            break;
                        }
                        sw.Stop();
                        TimeSpan ts2 = sw.Elapsed;

                        // Display Time
                        string elapsedTime2 = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                            ts2.Hours, ts2.Minutes, ts2.Seconds,
                                                            ts2.Milliseconds / 10);
                        Console.WriteLine("Elapsed time: " + elapsedTime2);
                        sw.Reset();
                        Console.WriteLine("String not found.");
                        break;

                    case 7:         //return to main menu
                        option1 = menu(1);
                        break;
                    }
                    break;

                case 2:
                    option2 = menuTwo("Queue");

                    switch (option2) //Enters into cases specific to the Queue
                    {
                    case 1:          //add one time
                        Console.Write("\nEnter the item you would like to add to the Stack: ");
                        string singleItem = Console.ReadLine();
                        myQueue.Enqueue(singleItem);
                        break;

                    case 2:              //add huge list
                        myQueue.Clear(); //clear queue
                        for (int i = 1; i < 2001; i++)
                        {
                            myQueue.Enqueue("New Entry " + i);
                        }
                        Console.WriteLine("\nHuge list added.");
                        break;

                    case 3:                     //display
                        if (myQueue.Count != 0) //display contents of queue if it's not empty
                        {
                            Console.WriteLine("\nYour queue:");
                            foreach (string item in myQueue)
                            {
                                Console.WriteLine(item);
                            }
                        }
                        else
                        {
                            Console.WriteLine("\nThe queue is empty. Please fill to display results.");
                        }
                        break;

                    case 4:         //delete from
                        string         sDeleteItem;
                        bool           queueFound = false;
                        Queue <string> tempQueue  = new Queue <string>();
                        Console.Write("\nEnter the item you would like to delete: ");
                        sDeleteItem = Console.ReadLine();
                        while (myQueue.Count != 0)
                        {
                            //load up tempQueue with the contents of myQueue, other than the item to delete
                            if (myQueue.Peek() != sDeleteItem)
                            {
                                tempQueue.Enqueue(myQueue.Dequeue());
                            }
                            else
                            {
                                myQueue.Dequeue();
                                queueFound = true;
                            }
                        }
                        if (queueFound)
                        {
                            myQueue = tempQueue;        //set myQueue back equal to the tempQueue, deleting the item
                        }
                        else
                        {
                            Console.WriteLine("This item is not in the queue.");
                        }
                        break;

                    case 5:         //clear
                        if (myQueue.Count > 0)
                        {
                            myQueue.Clear();
                            Console.WriteLine("\nQueue has been cleared.");
                        }
                        else
                        {
                            Console.WriteLine("\nQueue is already empty.");
                        }
                        break;

                    case 6:         //search
                        bool   queueFound2 = false;
                        string sFindItem;
                        System.Diagnostics.Stopwatch sw2 = new System.Diagnostics.Stopwatch();
                        IEnumerator <string>         MyQueueEnumerator = myQueue.GetEnumerator();
                        Console.Write("\nEnter the item you would like to find: ");
                        sw2.Start();
                        sFindItem = Console.ReadLine();
                        while (!queueFound2 && MyQueueEnumerator.MoveNext())
                        {
                            if (sFindItem == MyQueueEnumerator.Current)
                            {
                                queueFound2 = true;
                            }
                        }
                        sw2.Stop();
                        if (queueFound2)
                        {
                            Console.WriteLine(sFindItem + " found.");
                        }
                        else
                        {
                            Console.WriteLine(sFindItem + " was not found.");
                        }
                        TimeSpan ts = sw2.Elapsed;
                        //set proper format for displaying the time
                        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                           ts.Hours, ts.Minutes, ts.Seconds,
                                                           ts.Milliseconds / 10);
                        Console.WriteLine("Elapsed time: " + elapsedTime);
                        sw2.Reset();
                        break;

                    case 7:         //return to main menu
                        option1 = menu(1);
                        break;
                    }
                    break;

                case 3:
                    option2 = menuTwo("Dictionary");

                    switch (option2) //Enters into cases specific to the Dictionary
                    {
                    case 1:          //add one time
                        Console.WriteLine("\nEnter the item you would like to add to the dictionary: ");
                        string singleItem = Console.ReadLine();
                        Console.WriteLine("\nEnter the the value for " + singleItem + ": ");
                        int iValue = Convert.ToInt32(Console.ReadLine());
                        myDictionary.Add(singleItem, iValue);
                        break;

                    case 2:                   //add huge list
                        myDictionary.Clear(); //clear dictionary
                        for (int i = 1; i < 2001; i++)
                        {
                            myDictionary.Add(("New Entry " + Convert.ToString(i)), i);
                        }
                        Console.WriteLine("\nHuge list added.");
                        break;

                    case 3:                          //display
                        if (myDictionary.Count != 0) //display contents of dictionary if it's not empty
                        {
                            Console.WriteLine("\nYour dictionary:");
                            foreach (KeyValuePair <string, int> entry in myDictionary)
                            {
                                Console.WriteLine(entry.Key + "\t" + entry.Value);
                            }
                        }
                        else
                        {
                            Console.WriteLine("\nThe dictionary is empty. Please fill to display results.");
                        }
                        break;

                    case 4:         //delete from
                        string sDeleteItem;
                        Console.Write("\nEnter the item you would like to delete: ");
                        sDeleteItem = Console.ReadLine();

                        //search dictionary to see if the item exists and delete item
                        if (myDictionary.ContainsKey(sDeleteItem))
                        {
                            myDictionary.Remove(sDeleteItem);
                            Console.WriteLine("\n" + sDeleteItem + " successfully deleted.");
                        }

                        else
                        {
                            Console.WriteLine("\nThe item you entered does not exist in the dictionary.");
                        }
                        break;

                    case 5:         //clear
                        myDictionary.Clear();
                        Console.WriteLine("\nDictionary cleared.");
                        break;

                    case 6:                                                                    //search
                        string sFindItem;
                        System.Diagnostics.Stopwatch sw2 = new System.Diagnostics.Stopwatch(); //create stopwatch
                        Console.Write("\nEnter the item you would like to find: ");
                        sw2.Start();
                        sFindItem = Console.ReadLine();

                        if (myDictionary.ContainsKey(sFindItem))
                        {
                            sw2.Stop();
                            Console.WriteLine(sFindItem + " found.");
                        }

                        else
                        {
                            sw2.Stop();
                            Console.WriteLine(sFindItem + " was not found.");
                        }

                        TimeSpan ts = sw2.Elapsed;
                        //set proper format for displaying the time
                        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                           ts.Hours, ts.Minutes, ts.Seconds,
                                                           ts.Milliseconds / 10);
                        Console.WriteLine("Elapsed time: " + elapsedTime);
                        sw2.Reset();
                        break;

                    case 7:         //return to main menu
                        Console.WriteLine();
                        option1 = menu(1);
                        break;
                    }
                    break;

                case 4:     // Exit
                    exit = true;
                    break;
                }
            }
        }
Esempio n. 48
0
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            DateTime dt    = DateTime.Now;
            DateTime begin = new DateTime(dt.Year, dt.Month, Convert.ToInt32(dt.Date.ToString("dd")), startHour, startMin - 5, 00);
            DateTime end   = new DateTime(dt.Year, dt.Month, Convert.ToInt32(dt.Date.ToString("dd")), endHour, endMin + 5, 00);
            bool     a     = dt.CompareTo(begin) >= 0 ? true : false;
            bool     b     = dt.CompareTo(end) <= 0 ? true : false;

            //台電金期貨指數即時報價
            if (timeRules.Contains(dt.ToString()) && a && b)
            {
                //計時開始
                System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                sw.Reset(); sw.Start();
                //AddText(MsgType.System, "開始時間:" + dt.ToString("yyyy/MM/dd HH:mm:ss.fff") + "\n");
                AddText(MsgType.System, "開始時間:" + dt.ToString("yyyy/MM/dd HH:mm:ss") + "\n");
                HtmlNodeCollection nodes = null;
                while (nodes == null)
                {
                    nodes = sp.PostTaiwanFutures();
                }

                foreach (HtmlNode node in nodes)
                {
                    HtmlNode tx1   = node.SelectSingleNode("//tr[3]//td[@class='rt r']");
                    HtmlNode txel1 = node.SelectSingleNode("//tr[19]//td[@class='rt r']");
                    HtmlNode txfi1 = node.SelectSingleNode("//tr[22]//td[@class='rt r']");

                    //AddText(MsgType.Error, "台指期:" + tx1.InnerText.Trim(',').Replace(",", "") + "\n"
                    //                      + "電子期:" + txel1.InnerText.Trim(',').Replace(",", "") + "\n"
                    //                      + "金融期:" + txfi1.InnerText.Trim(',').Replace(",", "") + "\n");
                    AddText(MsgType.Error, tx1.InnerText.Trim(',').Replace(",", "") + "\t"
                            + txel1.InnerText.Trim(',').Replace(",", "") + "\t"
                            + txfi1.InnerText.Trim(',').Replace(",", "") + "\n");
                    //複製到剪貼簿
                    Clipboard.SetData(DataFormats.Text, tx1.InnerText.Trim(',').Replace(",", "") + "\t"
                                      + txel1.InnerText.Trim(',').Replace(",", "") + "\t"
                                      + txfi1.InnerText.Trim(',').Replace(",", ""));

                    excel.FuturesWriteExcel(tx1.InnerText.Trim().Replace(",", ""),
                                            txel1.InnerText.Trim().Replace(",", ""),
                                            txfi1.InnerText.Trim().Replace(",", ""),
                                            dt.ToString("yyyy/MM/dd HH:mm"));
                }

                //計時結束
                sw.Stop();
                AddText(MsgType.System, "總耗時:" + sw.Elapsed.TotalSeconds.ToString() + " 秒\n");
                axWindowsMediaPlayer1.Ctlcontrols.play();
            }

            //國際期貨指數即時報價
            if (dt.ToString("mm") == "00" && dt.ToString("ss") == "00")
            {
                //計時開始
                System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                sw.Reset(); sw.Start();
                AddText(MsgType.System, "開始時間:" + dt.ToString("yyyy/MM/dd HH:mm:ss.fff") + "\n");

                htmldoc = null;
                List <string> header = new List <string>();
                List <string> point  = new List <string>();
                while (htmldoc == null)
                {
                    htmldoc = sp.Posthtmldoc();
                }
                for (int i = 0; i < panel_Item.Count; i++)
                {
                    _P = htmldoc.DocumentNode.SelectNodes("//span[@id='" + cb_ItemName[i].SelectedValue.ToString() + "_P']");
                    _T = htmldoc.DocumentNode.SelectNodes("//span[@id='" + cb_ItemName[i].SelectedValue.ToString() + "_T']");
                    foreach (HtmlNode node in _P)
                    {
                        header.Add(cb_ItemName[i].Text);
                        point.Add(node.InnerText.Trim());
                        AddText(MsgType.Error, cb_ItemName[i].Text + ":" + node.InnerText.Trim() + "    ");
                    }
                    foreach (HtmlNode node in _T)
                    {
                        AddText(MsgType.Error, "時間:" + node.InnerText.Trim() + "\n");
                    }
                }

                excel.FuturesWriteExcel(header, point, dt.ToString("yyyy-MM-dd HH:mm"));

                //計時結束
                sw.Stop();
                AddText(MsgType.System, "總耗時:" + sw.Elapsed.TotalSeconds.ToString() + " 秒\n");
            }
        }
Esempio n. 49
0
        /// <summary>
        /// Executes the specified pipelines and pipelines with <see cref="ExecutionPolicy.Always"/> policies.
        /// </summary>
        /// <param name="pipelines">
        /// The pipelines to execute or <c>null</c>/empty to only execute pipelines with the <see cref="ExecutionPolicy.Always"/> policy.
        /// </param>
        /// <param name="normalPipelines">
        /// <c>true</c> to run pipelines with the <see cref="ExecutionPolicy.Normal"/> policy in addition
        /// to the pipelines specified or <c>false</c> to only run the specified pipelines.
        /// </param>
        /// <param name="cancellationTokenSource">
        /// A cancellation token source that can be used to cancel the execution.
        /// </param>
        /// <returns>The output documents from each executed pipeline.</returns>
        public async Task <IPipelineOutputs> ExecuteAsync(string[] pipelines, bool normalPipelines, CancellationTokenSource cancellationTokenSource)
        {
            // Setup
            await default(SynchronizationContextRemover);
            CheckDisposed();
            Guid executionId = Guid.NewGuid();
            ConcurrentDictionary <string, PhaseResult[]> phaseResults =
                new ConcurrentDictionary <string, PhaseResult[]>(StringComparer.OrdinalIgnoreCase);
            PipelineOutputs outputs = new PipelineOutputs(phaseResults);

            // Create the pipeline phases (this also validates the pipeline graph)
            if (_phases == null)
            {
                _phases = GetPipelinePhases(_pipelines, _logger);
            }

            // Verify pipelines
            HashSet <string> executingPipelines = GetExecutingPipelines(pipelines, normalPipelines);

            if (executingPipelines.Count == 0)
            {
                _logger.LogWarning("No pipelines are configured or specified for execution.");
                return(outputs);
            }

            // Log
            _logger.LogInformation($"Executing {executingPipelines.Count} pipelines ({string.Join(", ", executingPipelines.OrderBy(x => x))})");
            _logger.LogDebug($"Execution ID {executionId}");
            System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();

            // Raise before event
            await Events.RaiseAsync(new BeforeEngineExecution(this, executionId));

            // Do a check for the same input/output path
            if (FileSystem.InputPaths.Any(x => x.Equals(FileSystem.OutputPath)))
            {
                _logger.LogWarning("The output path is also one of the input paths which can cause unexpected behavior and is usually not advised");
            }

            // Clean paths
            CleanTempPath();
            if (Settings.GetBool(Keys.CleanOutputPath))
            {
                CleanOutputPath();
            }

            // Get phase tasks
            Task[] phaseTasks = null;
            try
            {
                // Get and execute all phases
                phaseTasks = GetPhaseTasks(executionId, executingPipelines, phaseResults, cancellationTokenSource);
                await Task.WhenAll(phaseTasks);
            }
            catch (Exception ex)
            {
                if (!(ex is OperationCanceledException))
                {
                    _logger.LogCritical("Error during execution");
                }
                throw;
            }
            finally
            {
                stopwatch.Stop();
            }

            // Raise after event
            await Events.RaiseAsync(new AfterEngineExecution(this, executionId, outputs, stopwatch.ElapsedMilliseconds));

            // Log execution summary table
            _logger.LogInformation(
                "Execution summary: (number of output documents per pipeline and phase)"
                + Environment.NewLine
                + Environment.NewLine
                + phaseResults
                .OrderBy(x => x.Key)
                .ToStringTable(
                    new[]
            {
                "Pipeline",
                nameof(Phase.Input),
                nameof(Phase.Process),
                nameof(Phase.Transform),
                nameof(Phase.Output),
                "Total Time"
            },
                    x => x.Key,
                    x => GetPhaseResultTableString(x.Value[(int)Phase.Input]),
                    x => GetPhaseResultTableString(x.Value[(int)Phase.Process]),
                    x => GetPhaseResultTableString(x.Value[(int)Phase.Transform]),
                    x => GetPhaseResultTableString(x.Value[(int)Phase.Output]),
                    x =>
                    ((x.Value[(int)Phase.Input]?.ElapsedMilliseconds ?? 0)
                     + (x.Value[(int)Phase.Process]?.ElapsedMilliseconds ?? 0)
                     + (x.Value[(int)Phase.Transform]?.ElapsedMilliseconds ?? 0)
                     + (x.Value[(int)Phase.Output]?.ElapsedMilliseconds ?? 0)).ToString()
                    + " ms"));
Esempio n. 50
0
        /// <summary>
        /// http请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="method">POST,GET</param>
        /// <param name="headers">http的头部,直接拷贝谷歌请求的头部即可</param>
        /// <param name="content">content,每个key,value 都要UrlEncode才行</param>
        /// <param name="contentEncode">content的编码</param>
        /// <param name="proxyUrl">代理url</param>
        /// <returns></returns>
        public string http(string url, string method, string headers, string content, Encoding contentEncode, string proxyUrl)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Method = method;
            if (method.Equals("GET", StringComparison.InvariantCultureIgnoreCase))
            {
                request.MaximumAutomaticRedirections = 100;
                request.AllowAutoRedirect            = false;
            }

            fillHeaders(request, headers);
            fillProxy(request, proxyUrl);

            #region 添加Post 参数
            if (contentEncode == null)
            {
                contentEncode = Encoding.UTF8;
            }
            if (!string.IsNullOrWhiteSpace(content))
            {
                byte[] data = contentEncode.GetBytes(content);
                request.ContentLength = data.Length;
                using (Stream reqStream = request.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }
            }
            #endregion

            HttpWebResponse response        = null;
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            try
            {
                sw.Start();
                response = (HttpWebResponse)request.GetResponse();
                sw.Stop();
                AvgResponseMilliseconds = sw.ElapsedMilliseconds;
                CookieCollection cc           = new CookieCollection();
                string           cookieString = response.Headers[HttpResponseHeader.SetCookie];
                if (!string.IsNullOrWhiteSpace(cookieString))
                {
                    var spilit = cookieString.Split(';');
                    foreach (string item in spilit)
                    {
                        var kv = item.Split('=');
                        if (kv.Length == 2)
                        {
                            cc.Add(new Cookie(kv[0].Trim().ToString().Replace(",", "|*|"), kv[1].Trim()));
                        }
                    }
                }
                trackCookies(cc);
            }
            catch (Exception ex)
            {
                sw.Stop();
                AvgResponseMilliseconds = sw.ElapsedMilliseconds;
                return(ex.Message);
            }

            string result = getResponseBody(response);
            return(result);
        }
Esempio n. 51
0
        //bodyDataの入れ替え
        private void updateCheckData(int index)
        {
            Console.WriteLine("updateCheckData");

            CheckData checkData          = checkDatas[index];
            int       numberForArraySort = NUMBER_OF_FRAME - 1;

            //time
            long dt = GetUnixTime(DateTime.Now);

            //このindexのnowでーた取得
            Body   body     = bodies[index];
            double nowHeadX = Math.Round(body.Joints[JointType.Head].Position.X * 30, 0);
            double nowHeadY = Math.Round(body.Joints[JointType.Head].Position.Y * 30, 0);
            double nowHeadZ = Math.Round(body.Joints[JointType.Head].Position.Z * 30, 0);

            double nowMiddleX = Math.Round(body.Joints[JointType.SpineMid].Position.X * 30, 0);
            double nowMiddleY = Math.Round(body.Joints[JointType.SpineMid].Position.Y * 30, 0);
            double nowMiddleZ = Math.Round(body.Joints[JointType.SpineMid].Position.Z * 30, 0);



            //初期の時
            if (checkData == null)
            {
                checkData = new CheckData();

                if (index == 0)
                {
                    sw.Start();
                    Console.WriteLine("***?????? ストップウォッチ開始");
                }
            }

            //data代入
            double[] headXInfo = checkData.headXInfo;
            double[] headYInfo = checkData.headYInfo;
            double[] headZInfo = checkData.headZInfo;

            double[] middleXInfo = checkData.middleXInfo;
            double[] middleYInfo = checkData.middleYInfo;
            double[] middleZInfo = checkData.middleZInfo;


            long[] time = checkData.time;

            int length = headZInfo.Length;

            Console.WriteLine("***length:{0}", length);


            if (length < NUMBER_OF_FRAME)//配列埋まりきっていない時の処理-配列の長さを図ってその次のところに追加
            {
                Array.Resize(ref headXInfo, length + 1);
                Array.Resize(ref headYInfo, length + 1);
                Array.Resize(ref headZInfo, length + 1);
                Array.Resize(ref middleXInfo, length + 1);
                Array.Resize(ref middleYInfo, length + 1);
                Array.Resize(ref middleZInfo, length + 1);

                Array.Resize(ref time, length + 1);
                //nowDataを末尾に追加
                headXInfo[length] = nowHeadX;
                headYInfo[length] = nowHeadY;
                headZInfo[length] = nowHeadZ;

                middleXInfo[length] = nowMiddleX;
                middleYInfo[length] = nowMiddleY;
                middleZInfo[length] = nowMiddleZ;


                time[length] = dt;
            }
            else//配列が埋まりきっているとき-配列の中身入れ替え
            {
                //Info中身入れ替え
                for (int i = 0; i < numberForArraySort; ++i)
                {
                    headXInfo[i]   = headXInfo[i + 1];
                    headYInfo[i]   = headYInfo[i + 1];
                    headZInfo[i]   = headZInfo[i + 1];
                    middleXInfo[i] = middleXInfo[i + 1];
                    middleYInfo[i] = middleYInfo[i + 1];
                    middleZInfo[i] = middleZInfo[i + 1];
                    time[i]        = time[i + 1];
                }
                headXInfo[numberForArraySort]   = nowHeadX;//nowDataをいれる
                headYInfo[numberForArraySort]   = nowHeadY;
                headZInfo[numberForArraySort]   = nowHeadZ;
                middleXInfo[numberForArraySort] = nowMiddleX;//nowDataをいれる
                middleYInfo[numberForArraySort] = nowMiddleY;
                middleZInfo[numberForArraySort] = nowMiddleZ;
                time[numberForArraySort]        = dt;

                if (index == 0)
                {
                    sw.Stop();
                    Console.WriteLine("***?????? 時間:{0}", sw.Elapsed);
                }
            }


            foreach (int i in headZInfo)
            {
                // Console.WriteLine(i);
            }

            //データ保存
            checkData.middleXInfo = middleXInfo;
            checkData.middleYInfo = middleYInfo;
            checkData.middleZInfo = middleZInfo;

            checkData.headXInfo = headXInfo;
            checkData.headYInfo = headYInfo;
            checkData.headZInfo = headZInfo;
            checkData.time      = time;

            checkDatas[index] = checkData;
        }
Esempio n. 52
0
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            var IResourceServiceFactory = actionExecutedContext.ActionContext.ControllerContext.Configuration.DependencyResolver.GetService(typeof(IResourceServiceFactory)) as IResourceServiceFactory;
            var IUnitOfWork             = actionExecutedContext.ActionContext.ControllerContext.Configuration.DependencyResolver.GetService(typeof(IUnitOfWork)) as IUnitOfWork;
            var IRequestMetaFactory     = actionExecutedContext.ActionContext.ControllerContext.Configuration.DependencyResolver.GetService(typeof(IRequestMetaFactory)) as IRequestMetaFactory;
            var IResourceServices       = IResourceServiceFactory.Create <IResourceServices>();
            var ICommonFactory          = actionExecutedContext.ActionContext.ControllerContext.Configuration.DependencyResolver.GetService(typeof(ICommonFactory)) as ICommonFactory;
            var IPyroRequestUriFactory  = actionExecutedContext.ActionContext.ControllerContext.Configuration.DependencyResolver.GetService(typeof(IPyroRequestUriFactory)) as IPyroRequestUriFactory;
            var IGlobalProperties       = actionExecutedContext.ActionContext.ControllerContext.Configuration.DependencyResolver.GetService(typeof(IGlobalProperties)) as IGlobalProperties;
            var IResourceTriggerService = actionExecutedContext.ActionContext.ControllerContext.Configuration.DependencyResolver.GetService(typeof(IResourceTriggerService)) as IResourceTriggerService;
            var IPyroFhirResource       = actionExecutedContext.ActionContext.ControllerContext.Configuration.DependencyResolver.GetService(typeof(Common.PyroHealthFhirResource.IPyroFhirResource)) as Common.PyroHealthFhirResource.IPyroFhirResource;

            using (DbContextTransaction Transaction = IUnitOfWork.BeginTransaction())
            {
                try
                {
                    var PyroCodeSystem = IPyroFhirResource.CodeSystem.PyroFhirServerCodeSystem;

                    DateTime dtStart = (DateTime)actionExecutedContext.Request.Properties[DateTimeKey];
                    System.Diagnostics.Stopwatch stopwatch = (System.Diagnostics.Stopwatch)actionExecutedContext.Request.Properties[StopwatchKey];
                    stopwatch.Stop();
                    TimeSpan duration = stopwatch.Elapsed;

                    IPyroRequestUri DtoRequestUri = IPyroRequestUriFactory.CreateFhirRequestUri();
                    DtoRequestUri.FhirRequestUri.Parse(actionExecutedContext.Request.RequestUri.OriginalString);

                    // use owin context so we can self host (i.e. avoid System.Web.HttpContext.Current)
                    var owinContext = actionExecutedContext.Request.GetOwinContext();

                    string machineName       = System.Environment.MachineName;
                    string httpVerb          = actionExecutedContext.Request.Method.ToString();
                    string ipAddress         = owinContext.Request.RemoteIpAddress;
                    string controllerName    = actionExecutedContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerName;
                    string actionName        = actionExecutedContext.ActionContext.ActionDescriptor.ActionName;
                    bool   successfulRequest = (actionExecutedContext.Exception == null);
                    System.Web.Http.Routing.IHttpRouteData route = actionExecutedContext.ActionContext.ControllerContext.RouteData;

                    // Get the resource base
                    string baseUri = DtoRequestUri.FhirRequestUri.UriPrimaryServiceRoot.OriginalString;

                    // Create the Security Event Object
                    AuditEvent Audit = new AuditEvent();
                    Audit.Meta     = new Meta();
                    Audit.Meta.Tag = new List <Coding>()
                    {
                        PyroCodeSystem.GetCoding(Common.PyroHealthFhirResource.CodeSystems.PyroFhirServer.Codes.Protected)
                    };
                    if (actionExecutedContext.Request.Method == HttpMethod.Put)
                    {
                        Audit.Action = AuditEvent.AuditEventAction.U;
                    }
                    else if (actionExecutedContext.Request.Method == HttpMethod.Post)
                    {
                        Audit.Action = AuditEvent.AuditEventAction.C;
                    }
                    else if (actionExecutedContext.Request.Method == HttpMethod.Delete)
                    {
                        Audit.Action = AuditEvent.AuditEventAction.D;
                    }
                    else
                    {
                        Audit.Action = AuditEvent.AuditEventAction.R;
                    }

                    Audit.Recorded = DateTimeOffset.Now;

                    Audit.Outcome = AuditEvent.AuditEventOutcome.N0;
                    if (!successfulRequest)
                    {
                        // log error
                        if (actionExecutedContext.Exception is PyroException)
                        {
                            var fse = actionExecutedContext.Exception as PyroException;
                            if ((int)fse.HttpStatusCode >= 500)
                            {
                                Audit.Outcome = AuditEvent.AuditEventOutcome.N8;
                            }
                            else if ((int)fse.HttpStatusCode >= 400)
                            {
                                Audit.Outcome = AuditEvent.AuditEventOutcome.N4;
                            }
                        }
                        else
                        {
                            Audit.Outcome = AuditEvent.AuditEventOutcome.N8;
                        }
                    }

                    Audit.Type = new Coding()
                    {
                        System = "http://hl7.org/fhir/security-event-type", Code = "rest", Display = "Restful Operation"
                    };
                    Audit.Subtype = new List <Coding>();

                    if (actionExecutedContext.Request.Method == HttpMethod.Put)
                    {
                        Audit.Subtype.Add(new Coding()
                        {
                            System = "http://hl7.org/fhir/restful-interaction", Code = "update", Display = "update"
                        });
                    }
                    else if (actionExecutedContext.Request.Method == HttpMethod.Post)
                    {
                        Audit.Subtype.Add(new Coding()
                        {
                            System = "http://hl7.org/fhir/restful-interaction", Code = "create", Display = "create"
                        });
                    }
                    else if (actionExecutedContext.Request.Method == HttpMethod.Delete)
                    {
                        Audit.Subtype.Add(new Coding()
                        {
                            System = "http://hl7.org/fhir/restful-interaction", Code = "delete", Display = "delete"
                        });
                    }
                    else if (actionExecutedContext.Request.Method == HttpMethod.Options)
                    {
                        Audit.Subtype.Add(new Coding()
                        {
                            System = "http://hl7.org/fhir/restful-interaction", Code = "read", Display = "read"
                        });
                    }
                    else if (route.Values.ContainsKey("ResourceName") && route.Values.ContainsKey("id") && route.Values.ContainsKey("vid"))
                    {
                        Audit.Subtype.Add(new Coding()
                        {
                            System = "http://hl7.org/fhir/restful-interaction", Code = "vread", Display = "vread"
                        });
                    }
                    else if (route.Values.ContainsKey("ResourceName") && route.Values.ContainsKey("id"))
                    {
                        if (owinContext.Request.Uri.OriginalString.Contains("_history"))
                        {
                            Audit.Subtype.Add(new Coding()
                            {
                                System = "http://hl7.org/fhir/restful-interaction", Code = "history-instance", Display = "history-instance"
                            });
                        }
                        else
                        {
                            Audit.Subtype.Add(new Coding()
                            {
                                System = "http://hl7.org/fhir/restful-interaction", Code = "read", Display = "read"
                            });
                        }
                    }
                    else if (route.Values.ContainsKey("ResourceName"))
                    {
                        if (owinContext.Request.Uri.OriginalString.Contains("_history"))
                        {
                            Audit.Subtype.Add(new Coding()
                            {
                                System = "http://hl7.org/fhir/restful-interaction", Code = "history-type", Display = "history-type"
                            });
                        }
                        else
                        {
                            Audit.Subtype.Add(new Coding()
                            {
                                System = "http://hl7.org/fhir/restful-interaction", Code = "search-type", Display = "search-type"
                            });
                        }
                    }

                    Audit.Agent.Add(new AuditEvent.AgentComponent());
                    // se.Participant[0].UserId = "";
                    // se.Participant[0].AltId = owinContext.Authentication.;
                    if (owinContext.Authentication.User != null && owinContext.Authentication.User.Identity.IsAuthenticated)
                    {
                        Audit.Agent[0].Name = owinContext.Authentication.User.Identity.Name;

                        // read additional details from the identity claims
                        if (owinContext.Authentication.User.Identity is System.Security.Claims.ClaimsIdentity ci)
                        {
                            var claim = ci.Claims.Where(c => c.Type == "name").FirstOrDefault();
                            if (claim != null)
                            {
                                Audit.Agent[0].Name = claim.Value;
                            }
                            claim = ci.Claims.Where(c => c.Type == "sub").FirstOrDefault();
                            if (claim != null)
                            {
                                Audit.Agent[0].AltId = claim.Value;
                            }
                            if (ci.Claims.Any(c => c.Type == "author_only_access" && c.Value == "true"))
                            {
                                Audit.Agent[0].Role = new List <CodeableConcept>
                                {
                                    new CodeableConcept(null, "author_only_access")
                                };
                            }
                        }
                    }
                    Audit.Agent[0].Requestor = true;
                    Audit.Agent[0].Network   = new AuditEvent.NetworkComponent()
                    {
                        Address = ipAddress,
                        Type    = AuditEvent.AuditEventAgentNetworkType.N2
                    };

                    Audit.Source = new AuditEvent.SourceComponent
                    {
                        Site       = "Cloud",
                        Identifier = new Identifier(null, actionExecutedContext.Request.RequestUri.GetLeftPart(UriPartial.Authority))
                    };
                    Audit.Source.Type.Add(new Coding()
                    {
                        System = "http://hl7.org/fhir/ValueSet/audit-source-type", Code = "3", Display = "Web Server"
                    });

                    if (route.Values.ContainsKey("ResourceName") && route.Values.ContainsKey("id"))
                    {
                        string relativeUri = String.Format("{0}/{1}", route.Values["ResourceName"] as string, route.Values["id"] as string);
                        if (route.Values.ContainsKey("vid"))
                        {
                            relativeUri += "/_history/" + route.Values["vid"] as string;
                        }
                        Audit.Entity = new List <AuditEvent.EntityComponent>
                        {
                            new AuditEvent.EntityComponent()
                            {
                                Name      = actionExecutedContext.Request.RequestUri.ToString(),
                                Reference = new ResourceReference()
                                {
                                    Url = new Uri(relativeUri, UriKind.Relative)
                                },
                                Type = new Coding()
                                {
                                    System = "http://hl7.org/fhir/object-type", Code = "1", Display = "Person"
                                }
                            }
                        };
                        if (actionExecutedContext.Request.Properties.ContainsKey(Attributes.ActionLogAttribute.ResourceIdentityKey))
                        {
                            string reference = actionExecutedContext.Request.Properties[Attributes.ActionLogAttribute.ResourceIdentityKey] as string;
                            if (!string.IsNullOrEmpty(reference))
                            {
                                Audit.Entity[0].Reference.Reference = reference;
                            }
                        }
                    }
                    else
                    {
                        Audit.Entity = new List <AuditEvent.EntityComponent>
                        {
                            new AuditEvent.EntityComponent()
                            {
                                Name        = actionExecutedContext.Request.RequestUri.ToString(),
                                Description = baseUri == null ?
                                              owinContext.Request.Uri.OriginalString
                                : owinContext.Request.Uri.OriginalString.Replace(baseUri, ""),
                                Type = new Coding()
                                {
                                    System = "http://hl7.org/fhir/object-type", Code = "1", Display = "Person"
                                }
                            }
                        };

                        if (actionExecutedContext.Request.Properties.ContainsKey(Attributes.ActionLogAttribute.ResourceIdentityKey))
                        {
                            string reference = actionExecutedContext.Request.Properties[Attributes.ActionLogAttribute.ResourceIdentityKey] as string;
                            if (!string.IsNullOrEmpty(reference))
                            {
                                Audit.Entity[0].Reference = new ResourceReference()
                                {
                                    Reference = reference
                                }
                            }
                            ;
                        }
                    }


                    IHtmlGenerationSupport Narative = ICommonFactory.CreateFhirNarativeGenerationSupport();
                    Narative.NewValuePairList("Time", string.Format("{0} ({1:f3} sec)", dtStart, duration.TotalSeconds));
                    Narative.AppendValuePairList(actionExecutedContext.Request.Method.ToString(), string.Format("{0}", HttpUtility.HtmlEncode(baseUri == null ?
                                                                                                                                              owinContext.Request.Uri.OriginalString
                                  : owinContext.Request.Uri.OriginalString.Replace(baseUri, ""))));
                    Narative.AppendValuePairList("BaseUri", baseUri);
                    Narative.AppendValuePairList("From", ipAddress);
                    if (owinContext.Authentication.User != null && owinContext.Authentication.User.Identity.IsAuthenticated)
                    {
                        Narative.AppendValuePairList("User", owinContext.Authentication.User.ToString());
                    }
                    else
                    {
                        Narative.AppendValuePairList("User", "(anonymous)");
                    }

                    if (Audit.Outcome != AuditEvent.AuditEventOutcome.N0)
                    {
                        Audit.OutcomeDesc = actionExecutedContext.Exception.Message;
                        Narative.AppendValuePairList("Error", actionExecutedContext.Exception.Message);
                    }
                    Audit.Text = new Narrative
                    {
                        Div    = Narative.Generate(),
                        Status = Narrative.NarrativeStatus.Generated
                    };

                    // Add custom PyroHealth event data
                    Audit.AddExtension("http://pyrohealth.net/extention/AuditEvent/TimeTaken", new FhirDecimal((decimal)duration.TotalMilliseconds));

                    if (IGlobalProperties.FhirAuditEventLogRequestData)
                    {
                        var requestDataObj = new AuditEvent.EntityComponent
                        {
                            Identifier  = new Identifier(null, "RequestData"),
                            Name        = actionExecutedContext.Request.RequestUri.ToString(),
                            Description = "Orginial Request Data",
                            Type        = new Coding()
                            {
                                System = "http://hl7.org/fhir/object-type", Code = "4", Display = "RequestData"
                            },
                            Detail = new List <AuditEvent.DetailComponent>()
                        };
                        var DetailComponent = new AuditEvent.DetailComponent();
                        requestDataObj.Detail.Add(DetailComponent);
                        string RequestData = GetRequestData(actionExecutedContext);
                        if (!string.IsNullOrWhiteSpace(RequestData))
                        {
                            DetailComponent.Value = Encoding.UTF8.GetBytes(RequestData);
                            Audit.Entity.Add(requestDataObj);
                        }
                    }

                    if (IGlobalProperties.FhirAuditEventLogResponseData)
                    {
                        var responseDataObj = new AuditEvent.EntityComponent
                        {
                            Identifier  = new Identifier(null, "ResponseData"),
                            Name        = actionExecutedContext.Request.RequestUri.ToString(),
                            Description = "Orginial Response Data",
                            Type        = new Coding()
                            {
                                System = "http://hl7.org/fhir/object-type", Code = "4", Display = "ResponseData"
                            },
                            Detail = new List <AuditEvent.DetailComponent>()
                        };
                        var DetailComponent = new AuditEvent.DetailComponent();
                        responseDataObj.Detail.Add(DetailComponent);
                        string ResponseData = GetResponseData(actionExecutedContext);
                        if (!string.IsNullOrWhiteSpace(ResponseData))
                        {
                            DetailComponent.Value = Encoding.UTF8.GetBytes(ResponseData);
                            Audit.Entity.Add(responseDataObj);
                        }
                    }

                    //Will only log if Debug logging is enabled.
                    DebugLogRequestResource(actionExecutedContext);


                    //Commit to Database
                    Pyro.Common.RequestMetadata.IRequestMeta IRequestMeta = IRequestMetaFactory.CreateRequestMeta().Set($"{ResourceType.AuditEvent}");
                    IResourceTriggerService.TriggersActive = false;
                    IResourceServiceOutcome ResourceServiceOutcome = IResourceServices.Post(Audit, IRequestMeta);
                    IResourceTriggerService.TriggersActive = true;
                    //IResourceServiceOutcome ResourceServiceOutcome = IResourceServices.SetResource(Audit, DtoRequestUri, RestEnum.CrudOperationType.Create);
                    Transaction.Commit();
                }
                catch (Exception Exec)
                {
                    Logger.Log.Error(Exec, "ActionLogAttribute");
                    Transaction.Rollback();
                }

                base.OnActionExecuted(actionExecutedContext);
            }
        }
Esempio n. 53
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            context.Response.Cache.SetExpires(DateTime.Now.AddMinutes(0));
            context.Response.Cache.SetMaxAge(new TimeSpan(0));
            context.Response.AddHeader("Last-Modified", DateTime.Now.ToLongDateString());

            var handlerPair = Handlers.FirstOrDefault(pair => context.Request.Url.Segments.LastOrDefault()._f(_ => _.StartsWith(pair.Key + ".")));
            var handler     = handlerPair._f(_ => _.Value);

            if (handler == null)
            {
                context.Response.StatusCode = 404;
                return;
            }
            var handlerName = handlerPair.Key;

            if (context.Request.Url.AbsolutePath.EndsWith(".js"))
            {
                var prevCycle  = int.Parse(context.Request.QueryString["cycle"]);
                var updates    = Updates(context);
                var prevUpdate = updates.FirstOrDefault(_update => _update.Handler == handlerName && _update.Cycle == prevCycle);
                var prevPage   = prevUpdate != null ? prevUpdate.Page : null;
                var prevState  = prevUpdate._f(_ => _.State);

                var        jsonTexts     = context.Request.Form.GetValues("commands[]");
                JsonData[] json_commands = null;
                if (jsonTexts != null && jsonTexts.Length > 0)
                {
                    json_commands = jsonTexts.Select(text => new JsonData(JsonSerializer.Deserialize(new Newtonsoft.Json.JsonTextReader(new System.IO.StringReader(text))))).ToArray();
                }

                var watcher = new System.Diagnostics.Stopwatch();
                watcher.Start();
                HtmlResult <HElement> result = handler(prevState, json_commands, new HContext(handlerPair.Key, context));

                var update = PushUpdate(context, handlerName, result.Html, result.State);

                var page = result.Html;

                var isPartial = page.Name.LocalName != "html";

                var js_updates = HtmlJavaScriptSynchronizer.JsSync(new HElementProvider(), prevPage == null ? null : isPartial ? prevPage : prevPage.Element("body"), isPartial ? page : page.Element("body")).ToArray();
                var jupdate    = new Dictionary <string, object>()
                {
                    { "cycle", update.Cycle }, { "prev_cycle", prevCycle }, { "processed_commands", json_commands.Else_Empty().Length }, { "updates", js_updates }
                };

                if (context.Request.Url.AbsolutePath.EndsWith(".text.js"))
                {
                    context.Response.ContentType = "text/plain";
                }
                else
                {
                    context.Response.ContentType = "text/json";
                }

                JsonSerializer.Serialize(context.Response.Output, jupdate);
                watcher.Stop();
                update.Elapsed = watcher.Elapsed;
            }
            else
            {
                var lastState = Updates(context).LastOrDefault(_update => _update.Handler == handlerName)._f(_ => _.State);

                var result = handler(lastState, null, new HContext(handlerPair.Key, context));
                var page   = result.Html;
                if (!context.Request.Url.AbsolutePath.EndsWith(".raw.html"))
                {
                    var head = page.Element("head") ?? new HElement("head");

                    var update = PushUpdate(context, handlerName, new HElement("html", head, new HElement("body")), result.State);

                    var startHead = new HElement(head.Name,
                                                 head.Attributes,
                                                 head.Nodes,
                                                 SoftTech.Wui.HWebSynchronizeHandler.Scripts_Inline(handlerName, update.Cycle, refreshPeriod: result.RefreshPeriod ?? TimeSpan.FromSeconds(10))
                                                 );
                    page = new HElement("html", startHead, new HElement("body"));
                }

                context.Response.Write(page.ToString());
            }
        }
Esempio n. 54
0
        ///<summary>Returns all DashbaordAR(s) for the given time period. Caution, this will run aging and calculate a/r if a month within the given range is missing.
        ///This can take several seconds per month missing.</summary>
        public static List <DashboardAR> GetAR(DateTime dateFrom, DateTime dateTo, List <DashboardAR> listDashAR)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <List <DashboardAR> >(MethodBase.GetCurrentMethod(), dateFrom, dateTo, listDashAR));
            }
            //assumes that dateFrom is the first of the month.
            string             command;
            List <DashboardAR> listRet = new List <DashboardAR>();

#if DEBUG
            _elapsedTimeAR = "";
            System.Diagnostics.Stopwatch stopWatch      = new System.Diagnostics.Stopwatch();
            System.Diagnostics.Stopwatch stopWatchTotal = new System.Diagnostics.Stopwatch();
            _elapsedTimeAR = "Elapsed time for GetAR:\r\n";
            stopWatchTotal.Start();
#endif
            int months = 0;
            while (dateTo >= dateFrom.AddMonths(months))             //calculate the number of months between the two dates.
            {
                months++;
            }
            for (int i = 0; i < months; i++)
            {
                DateTime    dateLastOfMonth = dateFrom.AddMonths(i + 1).AddDays(-1);
                DashboardAR dash            = null;
                for (int d = 0; d < listDashAR.Count; d++)
                {
                    if (listDashAR[d].DateCalc != dateLastOfMonth)
                    {
                        continue;
                    }
                    dash = listDashAR[d];
                }
                if (dash != null)               //we found a DashboardAR object from the database for this month, so use it.
                {
                    listRet.Add(dash);
                    continue;
                }
#if DEBUG
                stopWatch.Restart();
#endif
                //run historical aging on all patients based on the date entered.
                command = "SELECT SUM(Bal_0_30+Bal_31_60+Bal_61_90+BalOver90),SUM(InsEst) "
                          + "FROM (" + Ledgers.GetAgingQueryString(dateLastOfMonth, isHistoric: true) + ") guarBals";
                DataTable table = ReportsComplex.RunFuncOnReportServer(() => Db.GetTable(command));
#if DEBUG
                stopWatch.Stop();
                _elapsedTimeAR += "Aging using Ledgers.GetHistoricAgingQueryString() #" + i + " : " + stopWatch.Elapsed.ToString() + "\r\n";
#endif
                dash          = new DashboardAR();
                dash.DateCalc = dateLastOfMonth;
                dash.BalTotal = PIn.Double(table.Rows[0][0].ToString());
                dash.InsEst   = PIn.Double(table.Rows[0][1].ToString());
                DashboardARs.Insert(dash);                                                   //save it to the db for later.
                if (!string.IsNullOrEmpty(PrefC.ReportingServer.Server))                     //only attempt to insert into the reporting server if the reporting server is set up.
                {
                    ReportsComplex.RunFuncOnReportServer(() => (DashboardARs.Insert(dash))); //save it to the db for later.
                }
                listRet.Add(dash);                                                           //and also use it now.
            }
#if DEBUG
            stopWatchTotal.Stop();
            _elapsedTimeAR += "Total: " + stopWatchTotal.Elapsed.ToString();
            if (_showElapsedTimesForDebug)
            {
                System.Windows.Forms.MessageBox.Show(_elapsedTimeAR);
            }
#endif
            return(listRet);
        }
Esempio n. 55
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="current"></param>
        /// <returns>m/s</returns>
        public static float GetAverageSpeed(this RailTrack current)
        {
#if DEBUG
            var watch           = System.Diagnostics.Stopwatch.StartNew();
            var watchGetTangent = new System.Diagnostics.Stopwatch();
#endif

            const float step     = 25f;
            float       trackPos = 0.0f;

            int num = -1;

            float speedSum = 0;

            float realSpeed = 0;

            float trackLength = (float)current.logicTrack.length;

            float lastAngle = 0;

            float curveTotalDistance = 0.0f;

            BezierPoint[] points = current.curve.GetAnchorPoints();

            BezierPoint p1 = points[0];
            BezierPoint p2 = points[1];
            float       curveBlockLength = BezierCurve.ApproximateLength(p1, p2, 10);
            int         curvePointIndex  = 1;

            if (current.curve.close)
            {
                Terminal.Log($"Closed curve not supported yet!");
            }

            while (trackPos < trackLength)
            {
                float localDistance = Mathf.InverseLerp(0.0f, trackLength, trackPos);

                while (trackPos > (curveTotalDistance + curveBlockLength))
                {
                    curveTotalDistance += curveBlockLength;
                    p1 = points[curvePointIndex];
                    p2 = points[curvePointIndex + 1];
                    curvePointIndex++;
                    curveBlockLength = BezierCurve.ApproximateLength(p1, p2, 10);
                }

#if DEBUG
                watchGetTangent.Start();
#endif
                float localCurveDistance = Mathf.InverseLerp(curveTotalDistance, curveTotalDistance + curveBlockLength, trackPos);

                //Vector3 tangent2 = current.curve.GetTangentAt(localDistance); // Slow as f*ck
                Vector3 tangent = current.curve.GetTangent(p1, p2, localCurveDistance);

                //Terminal.Log($"tan1 {tangent2} tan2 {tangent} local {localCurveDistance} total {curveTotalDistance} block {curveBlockLength} pos {trackPos}");

#if DEBUG
                watchGetTangent.Stop();
#endif
                float angle = Mathf.Atan2(tangent.z, tangent.x);

                if (num >= 0)
                {
                    float maxSpeed = AngleDiffToSpeed(Utils.GetAngleDifference(lastAngle, angle), step);

                    if (num == 0)
                    {
                        realSpeed = maxSpeed;
                    }
                    else
                    {
                        if (maxSpeed > realSpeed)
                        {
                            if (realSpeed < 1.0f)
                            {
                                realSpeed = 1.0f;
                            }

                            realSpeed += step / realSpeed;
                        }
                        else
                        {
                            realSpeed = maxSpeed;
                        }
                    }

                    speedSum += realSpeed;
                }

                num++;

                trackPos += step;
                lastAngle = angle;
            }

            if (num <= 0)
            {
                //if track segment is too short, take two end points
                Vector3 tangent1 = current.curve.GetTangentAt(0.0f);
                Vector3 tangent2 = current.curve.GetTangentAt(1.0f);

                float angle1 = Mathf.Atan2(tangent1.z, tangent1.x);
                float angle2 = Mathf.Atan2(tangent2.z, tangent2.x);

#if DEBUG2
                watch.Stop();
                //Terminal.Log($"num {num} {watch.ElapsedMilliseconds}ms");
#endif
                return(AngleDiffToSpeed(Utils.GetAngleDifference(angle1, angle2), trackLength));
            }
#if DEBUG2
            watch.Stop();
            if (num > 100)
            {
                Terminal.Log($"num {num} all {watch.ElapsedMilliseconds}ms tangent {watchGetTangent.ElapsedMilliseconds}");
            }
#endif
            return((speedSum / num) * 3.6f); // km/h -> m/s
        }
Esempio n. 56
0
        public void Stop(string vergelijkingnaam, string analyseapplicatie, string referentieapplicatie, string analysequery, string referentiequery, string analysegemeentecode, string referentiegemeentecode, long analysecount, long referencecount)
        {
            Output.Info("\t" + ((int)((100.0 / analysecount) * match)) + "% gelijk #" + match + " afwijkend #" + nomatch + " mist #" + missing + "(adding #" + ds.Tables["outputline"].Rows.Count + " outputlines )");

            // save the regels
            regeladapter.Update(ds, "outputline");

            // update the koprow
            koprow["referentieapplicatie"]   = referentieapplicatie;
            koprow["analyseapplicatie"]      = analyseapplicatie;
            koprow["referentiequery"]        = referentiequery;
            koprow["analysequery"]           = analysequery;
            koprow["referentiegemeentecode"] = referentiegemeentecode;
            koprow["analysegemeentecode"]    = analysegemeentecode;
            koprow["percentage"]             = (100.0 / analysecount) * match;
            koprow["referentieaantal"]       = referencecount;
            koprow["analyseaantal"]          = analysecount;
            koprow["gelijkaantal"]           = match;
            koprow["afwijkingaantal"]        = nomatch;
            koprow["nietgevondenaantal"]     = missing;
            //koprow["ongeldigaantal"] = invalid;

            // the code that you want to measure comes here
            watch.Stop();
            koprow["looptijd"] = watch.Elapsed.TotalSeconds;
            //ds.Tables["output"].Rows[0]. koprow
            //koprow.SetModified();
            kopadapter.Update(ds, "output");

            if (Properties.Settings.Default.influxdb_url != "")
            {
                // dimensions
                String ResultLine = "referentieapplicatie=" + (referentieapplicatie == null ? "GEEN" : referentieapplicatie.Replace(" ", "\\ ").Replace(",", "\\,").Replace("=", "\\=")) + ",";
                ResultLine += "analyseapplicatie=" + (analyseapplicatie == null ? "GEEN" : analyseapplicatie.Replace(" ", "\\ ").Replace(",", "\\,").Replace("=", "\\=")) + ",";
                ResultLine += "referentiegemeentecode=" + (referentiegemeentecode == null ? "GEEN" : referentiegemeentecode.Replace(" ", "\\ ").Replace(",", "\\,").Replace("=", "\\=")) + ",";
                ResultLine += "analysegemeentecode=" + (analysegemeentecode == null ? "GEEN" : analysegemeentecode.Replace(" ", "\\ ").Replace(",", "\\,").Replace("=", "\\=")) + " ";
                // values
                ResultLine += "referentieaantal=" + referencecount + ",";
                ResultLine += "analyseaantal=" + analysecount + ",";
                ResultLine += "gelijkaantal=" + match + ",";
                ResultLine += "afwijkingaantal=" + nomatch + ",";
                ResultLine += "nietgevondenaantal=" + missing + ",";
                //ResultLine += "ongeldigaantal=" + invalid + ",";
                ResultLine += "percentage=" + Math.Round((100.0 / analysecount) * match, 2);

                var postdata = "ispiegel,";
                postdata += "vergelijking=" + vergelijkingnaam.Replace(" ", "\\ ").Replace(",", "\\,").Replace("=", "\\=") + ",";
                postdata += ResultLine;
                var client = new ShootAndForgetWebClient();
                if (Properties.Settings.Default.influxdb_auth != "")
                {
                    // ik wil in één keer de boel versturen, stomme "client.Credentials = new NetworkCredential"!
                    string credentials = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(Properties.Settings.Default.influxdb_auth));
                    client.Headers[System.Net.HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentials);
                }
                client.Headers[System.Net.HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                Output.Info("\t>>> posting to: " + Properties.Settings.Default.influxdb_url + " the following data:" + postdata);
                try
                {
                    var response = client.UploadString(Properties.Settings.Default.influxdb_url, postdata);
                }
                catch (System.Net.WebException ex)
                {
                    Output.Warn("Sending the data to: " + Properties.Settings.Default.influxdb_url, ex);
                }
            }
        }
Esempio n. 57
0
        public static List <List <int> > GetNewPatients(DateTime dateFrom, DateTime dateTo)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <List <List <int> > >(MethodBase.GetCurrentMethod(), dateFrom, dateTo));
            }
            Random rnd    = new Random();
            string rndStr = rnd.Next(1000000).ToString();

#if DEBUG
            _elapsedTimeNewPatients = "";
            System.Diagnostics.Stopwatch stopWatch      = new System.Diagnostics.Stopwatch();
            System.Diagnostics.Stopwatch stopWatchTotal = new System.Diagnostics.Stopwatch();
            _elapsedTimeNewPatients = "Elapsed time for GetNewPatients:\r\n";
            stopWatch.Restart();
            stopWatchTotal.Restart();
#endif
            string command;
            command = "DROP TABLE IF EXISTS tempdash" + rndStr + @";";
            Db.NonQ(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeNewPatients += "DROP TABLE: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            command = @"CREATE TABLE tempdash" + rndStr + @" (
				PatNum bigint NOT NULL PRIMARY KEY,
				dateFirstProc datetime NOT NULL
				) DEFAULT CHARSET=utf8"                ;
            Db.NonQ(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeNewPatients += "CREATE TABLE: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            //table full of individual patients and their dateFirstProcs.
            command = @"INSERT INTO tempdash" + rndStr + @" 
				SELECT PatNum, MIN(ProcDate) dateFirstProc 
				FROM procedurelog USE INDEX(indexPatNum)
				WHERE ProcStatus=2 GROUP BY PatNum
				HAVING dateFirstProc >= "                 + POut.Date(dateFrom) + " "
                      + "AND dateFirstProc <= " + POut.Date(dateTo);
            Db.NonQ(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeNewPatients += "INSERT INTO: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            command = "SELECT dateFirstProc,COUNT(*) "
                      + "FROM tempdash" + rndStr + @" "
                      + "GROUP BY MONTH(dateFirstProc)";
            DataTable tableCounts = Db.GetTable(command);
#if DEBUG
            stopWatch.Stop();
            stopWatchTotal.Stop();
            _elapsedTimeNewPatients += "SELECT dateFirstProc,COUNT(*): " + stopWatch.Elapsed.ToString() + "\r\n";
            _elapsedTimeNewPatients += "Total: " + stopWatchTotal.Elapsed.ToString();
            if (_showElapsedTimesForDebug)
            {
                System.Windows.Forms.MessageBox.Show(_elapsedTimeNewPatients);
            }
#endif
            List <int> listInt = new List <int>();
            for (int i = 0; i < 12; i++)
            {
                int      ptcount    = 0;
                DateTime datePeriod = dateFrom.AddMonths(i);              //only the month and year are important
                for (int j = 0; j < tableCounts.Rows.Count; j++)
                {
                    if (datePeriod.Year == PIn.Date(tableCounts.Rows[j][0].ToString()).Year &&
                        datePeriod.Month == PIn.Date(tableCounts.Rows[j][0].ToString()).Month)
                    {
                        ptcount += PIn.Int(tableCounts.Rows[j][1].ToString());
                    }
                }
                listInt.Add(ptcount);
            }
            List <List <int> > retVal = new List <List <int> >();
            retVal.Add(listInt);
            return(retVal);
        }
Esempio n. 58
0
        static void Main(string[] args)
        {
            Console.WriteLine("Start Task13_TripleStore");
            // Создаем генератор триплетов теста фототека. Генерируем поток массивов трех строк. Входным параметром является количество персон
            Random rnd = new Random();
            Func <int, IEnumerable <string[]> > GenerateTriples = n =>
            {
                // n персон
                var persons = Enumerable.Range(0, n).SelectMany(i => new string[][]
                {
                    new string[] { "<p" + (n - i - 1) + ">", "<name>", "Pupkin_" + (n - i - 1) }, // имя
                    new string[] { "<p" + (n - i - 1) + ">", "<age>", "33" } // возраст
                });
                // 2*n фоток
                var photos = Enumerable.Range(0, 2 * n).SelectMany(i => new string[][]
                {
                    new string[] { "<ph" + (2 * n - i - 1) + ">", "<name>", "DSP_" + (2 * n - i - 1) }, // имя
                    new string[] { "<ph" + (2 * n - i - 1) + ">", "<age>", "33" } // возраст
                });
                // 6*n отражений
                var reflections = Enumerable.Range(0, 6 * n).SelectMany(i => new string[][]
                {
                    new string[] { "<re" + (6 * n - i - 1) + ">", "<reflected>", "<p" + rnd.Next(n) + ">" }, // отражаемое
                    new string[] { "<re" + (6 * n - i - 1) + ">", "<inphoto>", "<ph" + rnd.Next(2 * n) + ">" } // в документе
                });
                return(persons.Concat(photos).Concat(reflections));
            };

            PType tp_triple = new PTypeRecord(
                new NamedType("subject", new PType(PTypeEnumeration.sstring)),
                new NamedType("predicate", new PType(PTypeEnumeration.sstring)),
                new NamedType("object", new PType(PTypeEnumeration.sstring)));

            string      path    = "data";
            int         nom     = 0;
            TableSimple triples = new TableSimple(tp_triple, new int[] { 0, 2 }, () => File.Open(path + (nom++), FileMode.OpenOrCreate));


            int npersons = 400_000;

            bool toload = true;

            if (toload) // Загрузка данных
            {
                triples.Fill(GenerateTriples(npersons));
            }

            string sample = "<p" + (npersons * 2 / 3) + ">";

            var rfls = triples.GetAllByKey(2, sample).Where(r => (string)r[1] == "<reflected>");

            foreach (object[] r in rfls)
            {
                Console.WriteLine($"{r[0]} {r[1]} {r[2]}");
            }
            Console.WriteLine();

            var indocs = rfls.SelectMany(r => triples.GetAllByKey(0, r[0])).Where(t => (string)t[1] == "<inphoto>");

            foreach (object[] r in indocs)
            {
                Console.WriteLine($"{r[0]} {r[1]} {r[2]}");
            }
            Console.WriteLine();

            var phs = indocs.SelectMany(r => triples.GetAllByKey(0, r[2])).Where(t => (string)t[1] == "<name>");

            foreach (object[] r in phs)
            {
                Console.WriteLine($"{r[0]} {r[1]} {r[2]}");
            }
            Console.WriteLine();

            // Теперь цикл по образцам
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            int nsamples = 1000;

            sw.Start();
            int count = 0;

            for (int i = 0; i < nsamples; i++)
            {
                sample = "<p" + rnd.Next(npersons) + ">";
                var que = triples.GetAllByKey(2, sample).Where(r => (string)r[1] == "<reflected>")
                          .SelectMany(r => triples.GetAllByKey(0, r[0])).Where(t => (string)t[1] == "<inphoto>")
                          .SelectMany(r => triples.GetAllByKey(0, r[2])).Where(t => (string)t[1] == "<name>");
                //foreach (object[] r in que) Console.WriteLine($"{r[0]} {r[1]} {r[2]}");
                //Console.WriteLine();
                count += que.Count();
            }
            sw.Stop();
            Console.WriteLine($"count={count} duration={sw.ElapsedMilliseconds}");
        }
Esempio n. 59
0
        //Builds the actual asset bundle.  Only builds if files added & required information set in mod info fields
        bool BuildMod()
        {
            const string modBuilderLabel = "Mod Builder";

            if (!ModInfoReady)
            {
                Debug.LogWarning("Not ready to build, canceled.");
                return(false);
            }

            //get destination for mod
            modOutPutPath = (Directory.Exists(modOutPutPath) ? modOutPutPath : Application.dataPath);
            string modFilePath = EditorUtility.SaveFilePanel("Save", modOutPutPath, modInfo.ModTitle, "dfmod");

            if (!Directory.Exists(modOutPutPath) || string.IsNullOrEmpty(modFilePath))
            {
                Debug.LogWarning("Invalid build path");
                return(false);
            }
            else if (Assets == null || Assets.Count < 0)
            {
                Debug.LogWarning("No assets selected");
                return(false);
            }

            modOutPutPath = modFilePath.Substring(0, modFilePath.LastIndexOfAny(new char[] { '\\', '/' }) + 1);

            //refresh
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();

            string fileName = modFilePath.Substring(modFilePath.LastIndexOfAny(new char[] { '\\', '/' }) + 1);

            AddAssetToMod(GetAssetPathFromFilePath(currentFilePath));
            List <string> assets = Assets;

            if (precompiledMod)
            {
                string dataPath    = Application.dataPath;
                var    scriptPaths = new List <string>();
                var    otherAssets = new List <string>();

                foreach (string assetPath in assets)
                {
                    if (assetPath.EndsWith(".cs", StringComparison.Ordinal))
                    {
                        scriptPaths.Add(Path.Combine(dataPath, assetPath.Substring("Assets/".Length)));
                    }
                    else
                    {
                        otherAssets.Add(assetPath);
                    }
                }

                assets = otherAssets;

                if (scriptPaths.Count > 0)
                {
                    string assemblyPath = Path.Combine(GetTempModDirPath(), fileName.Replace("dfmod", "dll.bytes"));

                    if (!ModAssemblyBuilder.Compile(assemblyPath, scriptPaths.ToArray()))
                    {
                        return(false);
                    }

                    string outputAssetPath = assemblyPath.Substring(assemblyPath.LastIndexOf("Assets"));
                    AssetDatabase.ImportAsset(outputAssetPath);
                    assets.Add(outputAssetPath);
                }
            }

            AssetBundleBuild[] buildMap = new AssetBundleBuild[1];
            buildMap[0].assetBundleName    = fileName;
            buildMap[0].assetBundleVariant = "";       //TODO

            var tempAssetPaths = new List <string>(assets);

#if LOG_BUILD_TIME
            var stopWatch = new System.Diagnostics.Stopwatch();
            stopWatch.Start();
#endif

            AssetDatabase.StartAssetEditing();

            try
            {
                for (int i = 0; i < tempAssetPaths.Count; i++)
                {
                    string filePath = tempAssetPaths[i];

                    EditorUtility.DisplayProgressBar(modBuilderLabel, filePath, (float)i / tempAssetPaths.Count);

                    if (!File.Exists(filePath))
                    {
                        Debug.LogError("Asset not found: " + filePath);
                        return(false);
                    }

                    if (filePath.EndsWith(".cs", StringComparison.Ordinal))
                    {
                        // Create a copy of C# script as a .txt text asset
                        string assetPath = CopyAsset <TextAsset>(filePath, ".txt");
                        if (assetPath == null)
                        {
                            return(false);
                        }

                        tempAssetPaths[i] = assetPath;
                    }
                    else if (filePath.EndsWith(".prefab", StringComparison.Ordinal))
                    {
                        // Serialize custom components
                        // Will create a prefab copy without custom components if needed
                        var prefabCopy = CheckForImportedComponents(filePath);
                        if (prefabCopy.HasValue)
                        {
                            tempAssetPaths[i] = prefabCopy.Value.prefabPath;
                            tempAssetPaths.Add(prefabCopy.Value.dataPath);
                        }
                    }
                }
            }
            finally
            {
                EditorUtility.ClearProgressBar();
                AssetDatabase.StopAssetEditing();
            }

#if LOG_BUILD_TIME
            stopWatch.Stop();
            Debug.Log($"Mod Builder: elapsed {stopWatch.ElapsedMilliseconds} milliseconds to prepare assets.");
#endif

            buildMap[0].assetNames = tempAssetPaths.ToArray();

            //build for every target in buildTarget array
            for (int i = 0; i < buildTargets.Length; i++)
            {
                if (EditorUtility.DisplayCancelableProgressBar(modBuilderLabel, $"Building for {buildTargets[i]}.", (float)i / buildTargets.Length))
                {
                    return(false);
                }

                if (buildTargetsToggles[i] == false)
                {
                    continue;
                }

                string fullPath = Path.Combine(modOutPutPath, buildTargets[i].ToString());
                Directory.CreateDirectory(fullPath);
                BuildPipeline.BuildAssetBundles(fullPath, buildMap, ToBuildAssetBundleOptions(compressionOption), buildTargets[i]);
            }

            EditorUtility.ClearProgressBar();
            return(true);
        }
Esempio n. 60
0
 //[OneTimeUnityTearDown]は無い
 public void OneTimeTearDownTest()
 {
     Debug.Log($"OneTimeTearDownTest t={sw.ElapsedMilliseconds}");
     sw.Stop();
 }