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");
        }
        /// <summary>
        /// Tests for Vektor class
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnVector_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();
            txtVector.Text = "Starting test suite for the Vektor class.\r\n\r\n";

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

            // Go over all defined operations and input combinations
            foreach (Vektor vector in vectors)
            {
                foreach (Vektor secondVector in vectors)
                {
                    txtVector.Text += vector + " + " + secondVector + " = " + (vector + secondVector) + "\r\n";
                    txtVector.Text += vector + " - " + secondVector + " = " + (vector - secondVector) + "\r\n";
                    txtVector.Text += vector + " == " + secondVector + " ... " + (vector == secondVector) + "\r\n";
                    txtVector.Text += vector + vector + " (length " + (vector == null ? 0 : vector.Length()) + ") > " + secondVector + " (length " + (secondVector == null ? 0 : secondVector.Length()) + ")" + " ... " + (vector > secondVector) + "\r\n";
                    txtVector.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;
            txtVector.Text += "\r\nTest suite finished, time elapsed: " + elapsed + "ms.";
        }
Exemple #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();
        }
Exemple #4
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();
                }
            );
        }
        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.");
        }
Exemple #6
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);
        }
        static void Main(string[] args)
        {

            TwitchPlays.ChannelName = "fluzzarn";
            TwitchPlays.NickName = "Fluzzarn";
            TwitchPlays.Password = Password.OAuthPWord;
            TwitchPlays.ServerAddress = "irc.twitch.tv";

            TwitchPlays.Connect();
            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
            timer.Start();

            kappa k = printKapps;
            TwitchPlays.AddCommandToFunction("Kappa",printKapps);
            TwitchPlays.AddCommandToFunction("exit", quit);
            TwitchPlays.AddCommandToFunction("quit", quit);
            while(true)
            {
                if(timer.ElapsedMilliseconds > 5000)
                {

                    string command = TwitchPlays.GetMostCommonCommand();
                    int amount = TwitchPlays.GetFrequencyOfCommand(command);
                    Console.WriteLine("Most common input was: " + command + " with " + amount + " instances");
                    TwitchPlays.ExecuteCommand(command);
                    TwitchPlays.ClearCommands();
                    timer.Reset();
                    timer.Start();
                }


            }
        }
        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);
        }
Exemple #9
0
        static void Main()
        {
            Scene scene = new Scene();
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();
            GameTime time = new GameTime();
            MessagePump.Run(scene.GraphicsEngine.Form, () =>
            {
                watch.Reset();
                watch.Start();

                int frameTime = 1;
                if (time.LastFrameElapsedTime.TotalMilliseconds < frameTime)
                    System.Threading.Thread.Sleep((int)(frameTime - time.LastFrameElapsedTime.TotalMilliseconds));
                scene.Update(time);
                scene.Draw();

                watch.Stop();
                time.LastFrameElapsedTime = watch.Elapsed;
                time.TotalGameTime = time.TotalGameTime + watch.Elapsed;

            });
            scene.Dispose();

            // TODO ce soir
            // frustrum culling pour la planète.
            // backface culling pour le ground.
            //
        }
Exemple #10
0
        public static void Main(string[] args)
        {
            Director.Initialize ();
            Director.Instance.GL.Context.SetClearColor(255,255,255,0);

            walker = new Walker("run.png", "run.xml");

            var scene = new Scene();
            scene.Camera.SetViewFromViewport();
            SpriteTile sprite = walker.Get("walkLeft00");

            sprite.Position = scene.Camera.CalcBounds().Center;
            sprite.CenterSprite();
            sprite.Scale = new Vector2(1,1);
            scene.AddChild(sprite);

            Director.Instance.RunWithScene(scene, true);

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

            int spriteOffset = 0;
            timer.Start();
            bool walkLeft = true;
            while(true) {
                if(timer.ElapsedMilliseconds > 25f) {
                    string spriteName;
                    if(walkLeft) {
                        spriteName = "walkLeft";
                        sprite.Position = new Vector2(sprite.Position.X - 10, sprite.Position.Y);
                    } else {
                        spriteName = "walkRight";
                        sprite.Position = new Vector2(sprite.Position.X + 10, sprite.Position.Y);
                    }
                    if(sprite.Position.X < 0) {
                        walkLeft = false;
                    }
                    if(sprite.Position.X > Director.Instance.GL.Context.GetViewport().Width) {
                        walkLeft = true;
                    }
                    spriteName += spriteOffset.ToString("00");

                    sprite.TileIndex2D = walker.Get(spriteName).TileIndex2D;

                    if(spriteOffset >= 8) {
                        spriteOffset = 0;
                    } else {
                        spriteOffset ++;
                    }

                    timer.Reset();
                    timer.Start();
                }

                Director.Instance.Update();
                Director.Instance.Render();
                Director.Instance.GL.Context.SwapBuffers();
                Director.Instance.PostSwap();
            }
        }
		private long Time(Action toDo, int repetitions)
		{
			var stopwatch = new System.Diagnostics.Stopwatch();
			stopwatch.Start();
			{
				stopwatch.Start();
				for (int i = 0; i < repetitions; i ++)
				{
					toDo();
				}
			}
			stopwatch.Stop();
			return stopwatch.ElapsedTicks;
		}
        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");

        }
Exemple #13
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
 }
        public void CountWords()
        {
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();
            if (!string.IsNullOrWhiteSpace(this.Text))
            {
                var allWords = this.Text.Split(new string[] { SPACE, NEW_LINE, TAB, CARRIEGE_RETURN, DOT, SEMI_COLON, COLON, TWO_POINT }, StringSplitOptions.RemoveEmptyEntries);
                if (!this.DetailedStats)
                {
                    this.NumberOfWords = allWords.LongLength;
                }
                else
                {
                    for (long cursor = 0; cursor < allWords.LongLength; ++cursor)
                    {
                        if (!string.IsNullOrWhiteSpace(allWords[cursor]))
                        {
                            ++this.NumberOfWords;
                            if (!this.Stats.ContainsKey(allWords[cursor]))
                            {
                                this.Stats[allWords[cursor]] = 1;

                            }
                            else
                            {
                                ++this.Stats[allWords[cursor]];
                            }
                        }
                    }
                }
            }
            watch.Stop();
            this.CountTime = watch.ElapsedMilliseconds;
        }
 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";
     }
 }
Exemple #16
0
        public int MINIMAX_DECISION(Game game)
        {
            _stopwatch = new System.Diagnostics.Stopwatch();
            _stopwatch.Start();

            int maxValue = int.MinValue;
            List<int> colOptions = new List<int>();

            List<int> actions = ACTIONS(game);
            int iterationCounter = 0;
            foreach (int column in actions)
            {
                iterationCounter++;
                int v = MIN_VALUE(RESULT(game, column, _max), 1);

                if (v > maxValue)
                {
                    maxValue = v;
                    colOptions.Clear();
                    colOptions.Add(column);
                }
                else if (v == maxValue)
                {
                    colOptions.Add(column);
                }

                if (_stopwatch.Elapsed.Seconds > (game.TimeLimitSeconds - 1)) break;
            }

            int c = colOptions[_rnd.Next(colOptions.Count)];
            Console.WriteLine("Column selection: {0} / Elapsed: {1} / Total Actions: {2} / Actions Evaluated: {3}", c, _stopwatch.Elapsed, actions.Count, iterationCounter);
            return c;
        }
Exemple #17
0
        static void Main(string[] args)
        {
            var stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();

            Action<CancellationToken> longRunning = async (token) =>
            {
                for (int i = 0; i < 100; i++)
                {
                    Console.WriteLine("{0} {1}", i, stopwatch.Elapsed.TotalMilliseconds); 
                    await Task.Delay(new Random().Next(3, 100));
                    if (token.IsCancellationRequested)
                        break;
                }
            };

            // start with cancel option
            var source = new CancellationTokenSource();
            longRunning.Invoke(source.Token);

            // wait for a second 
            Thread.Sleep(1000);

            // top processing
            source.Cancel();

            Console.Read();
        }
Exemple #18
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);
        }
Exemple #19
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();
        }
		//[TestMethod]
		public void Performance()
		{
			var sw = new System.Diagnostics.Stopwatch();
			sw.Start();
			for (var i = 0; i < 200; i++) this.DefinedIPlugin();
			Assert.IsTrue(sw.ElapsedMilliseconds < 2000);
		}
Exemple #21
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();
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ExecutionContext"/> class.
 /// </summary>
 public ExecutionContext()
 {
     #if STOPWATCH
     _stopwatch = new System.Diagnostics.Stopwatch();
     _stopwatch.Start();
     #endif
 }
Exemple #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++;
            }
        }
        public MainWindow()
        {
            InitializeComponent();
             double ticks = 0L;
             System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

             int frameCount = 0;

             //There is a textbox "txtTicks" which accept a millisecond value
             //And a button "btn", by clicking the button the dispatchertimer &
             //stopwatcher are started.
             _timer.Tick += (sender, e) =>
             {
            frameCount++;
            //System.Diagnostics.Debug.WriteLine(watch.ElapsedMilliseconds);
            if (watch.ElapsedMilliseconds > 1000)
            {
               _timer.Stop();
               watch.Reset();
               MessageBox.Show(string.Format("Already 1 second! FrameCount: {0}", frameCount));
               frameCount = 0;
            }
             };

             this.btn.Click += (sender, e) =>
             {
            double.TryParse(this.txtTicks.Text, out ticks);
            if (ticks != 0.0)
            {
               _timer.Interval = TimeSpan.FromMilliseconds(ticks);
            }
            _timer.Start();
            watch.Start();
             };
        }
Exemple #25
0
		private static void InvokeBatch(IRemoteServ1 service)
		{
			try
			{
				service.DoSomethingWrong();
				Assert.Fail("Expecting exception here");
			}
			catch (Exception ex)
			{
				Assert.AreEqual("Remote server or invoker threw Exception with message simple message", ex.Message);
			}

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

			// 1000
			for (var i = 0; i < 100; i++)
			{
				if (i % 1000 == 0)
				{
					var collCount0 = GC.CollectionCount(0);
					var collCount1 = GC.CollectionCount(1);
					var collCount2 = GC.CollectionCount(2);

					Console.WriteLine("Collections on Gen 0 {0}, Gen 1 {1}, Gen 2 {2} ", collCount0, collCount1, collCount2);
				}

				// Console.WriteLine("new batch ");

				service.NoParamsOrReturn();
				service.JustParams("1");
				Assert.IsTrue(service.JustReturn().Equals("abc"));
				service.ParamsWithStruct(new MyCustomStruct() { Name = "1", Age = 30 });
				service.ParamsWithCustomType1(new Impl1() { });
				service.ParamsWithCustomType2(new Contract1Impl() { Name = "2", Age = 31 });
				service.ParamsAndReturn(Guid.NewGuid(), "", 1, DateTime.Now, 102.2m, FileAccess.ReadWrite, 1, 2, 3.0f, 4.0);
				service.WithInheritanceParam(new Derived1() { Something = 10, DerivedProp1 = 20 });

				var b = service.WithInheritanceRet();
				Assert.IsNotNull(b);
				Assert.IsInstanceOf(typeof(Derived2), b);
				Assert.AreEqual(10, (b as Derived2).Something);
				Assert.AreEqual("test", (b as Derived2).DerivedProp2);

				var enu = service.UsingEnumerators();
				Assert.IsNotNull(enu);
				Assert.AreEqual(2, enu.Count());

				var array = service.UsingArray();
				Assert.IsNotNull(array);
				Assert.AreEqual(2, array.Length);

				service.ReturningNull1();
				service.ReturningNull2();
			}

			watch.Stop();

			Console.WriteLine("took " + watch.ElapsedMilliseconds);
		}
        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;
        }
 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 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));
        }
Exemple #29
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());
		    }
		}
Exemple #30
0
		static Block ()
		{
#if !MF_FRAMEWORK_VERSION_V4_3
			sw = new System.Diagnostics.Stopwatch ();
			sw.Start ();
#endif
		}
        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();
                }
            }
        }
Exemple #32
0
        public static void Main(string[] args)
        {
            var util      = new Util();
            var stopWatch = new System.Diagnostics.Stopwatch();

            var fileStopWords = "stopwords.txt";

            //var fileText = "sample_text2.txt";

            stopWatch.Start();
            var stopWords = File.ReadAllLines(fileStopWords).Select(x => x.ToLower());

            Console.WriteLine($"stopWords: {stopWords.Count()} \t {stopWatch.ElapsedMilliseconds} ms");
            stopWatch.Restart();

            //var text = File.ReadAllText(fileText)?.ToLower();
            var text = util.GetHTTPText("https://pt.wikipedia.org/wiki/Pok%C3%A9mon_GO", "//div[@id='bodyContent']").Result.ToLower();

            Console.WriteLine($"ReadAllText \t {stopWatch.ElapsedMilliseconds} ms");
            stopWatch.Restart();

            text = text.Replace('\n', ' ');
            text = text.Replace('\t', ' ');

            Console.WriteLine($"Replace \t {stopWatch.ElapsedMilliseconds} ms");
            stopWatch.Restart();

            var tokenA = util.TokenizerA(text);

            Console.WriteLine($"tokenA {tokenA.Count()} \t {stopWatch.ElapsedMilliseconds} ms");
            stopWatch.Restart();

            var tokenB = util.TokenizerB(text);

            Console.WriteLine($"tokenB {tokenB.Count()} \t {stopWatch.ElapsedMilliseconds} ms");
            stopWatch.Restart();


            var words = text.Split(' ');

            Console.WriteLine($"Split \t {stopWatch.ElapsedMilliseconds} ms");
            stopWatch.Restart();

            Console.WriteLine($"words: {words.Length}");

//            var cw = new Regex("[a-zA-Z0-1]");

            Console.WriteLine();

            var stemmer = new PortugueseStemmer();
            var cWords  = tokenB
                          .Where(x => x.Length > 2 && stopWords.All(y => y.Trim() != x.Trim()))
                          .Select(x => stemmer.WordStemming(x))
                          .GroupBy(x => x).ToList();

            Console.WriteLine($"Select, Where n GroupBy \t {stopWatch.ElapsedMilliseconds} ms");
            stopWatch.Restart();

            Console.WriteLine($"cWords: {cWords.Count()}");

            Console.WriteLine($"Count \t {stopWatch.ElapsedMilliseconds} ms");
            stopWatch.Restart();

            foreach (var word in cWords.OrderByDescending(x => x.Count()).Take(15))
            {
                Console.WriteLine($"{word.Key}: {word.Count()}");
            }
        }
Exemple #33
0
 //constructor that takes int size as an argument and passes that int to the base constructor
 internal GameService(int size) : base(size: size)
 {
     assignLive();
     assignNumbers();
     time.Start();
 }
Exemple #34
0
        private async Task UpdateRankingAsync(CancellationToken cancellationToken)
        {
            var roundIds = new HashSet <long>();

            if (TournamentId == null && RoundId == null)
            {
                _logger.LogError($"Both {nameof(TournamentId)} and {nameof(RoundId)} are null. Cannot update ranking.");
                return;
            }

            if (TenantContext == null)
            {
                _logger.LogError($"{nameof(TenantContext)} is null. Cannot update ranking.");
                return;
            }
#if DEBUG
            var stopWatch = new System.Diagnostics.Stopwatch();
            stopWatch.Start();
#endif
            try
            {
                var matchesPlayed = await TenantContext.DbContext.AppDb.MatchRepository.GetMatchesCompleteAsync(
                    new PredicateExpression(TournamentId != null
                        ? MatchCompleteRawFields.TournamentId == TournamentId
                        : MatchCompleteRawFields.RoundId == RoundId), cancellationToken);

                var matchesToPlay = await TenantContext.DbContext.AppDb.MatchRepository.GetMatchesToPlayAsync(
                    new PredicateExpression(TournamentId != null
                        ? MatchToPlayRawFields.TournamentId == TournamentId
                        : MatchToPlayRawFields.RoundId == RoundId), cancellationToken);

                // Get round id and date of creation for the ranking entry
                var rankingCreatedOnTable = await TenantContext.DbContext.AppDb.RankingRepository.GetRoundRanksCreatedOn(
                    new PredicateExpression(TournamentId != null
                        ? RankingFields.TournamentId == TournamentId
                        : RankingFields.RoundId == RoundId), cancellationToken);

                #region * Identify rounds for which the ranking table must be updated *

                matchesPlayed.ForEach(m =>
                {
                    // Was the match updated after the ranking entry was created?
                    if (EnforceUpdate || rankingCreatedOnTable.Exists(rt => rt.RoundId == m.RoundId && rt.CreatedOn < m.ModifiedOn))
                    {
                        roundIds.Add(m.RoundId);
                    }
                });
                // matches to play is required for generation of ranking chart files (remaining match days)
                matchesToPlay.ForEach(m =>
                {
                    // Was the match updated after the ranking entry was created?
                    if (EnforceUpdate || rankingCreatedOnTable.Exists(rt => rt.RoundId == m.RoundId && rt.CreatedOn < m.ModifiedOn))
                    {
                        roundIds.Add(m.RoundId);
                    }
                });

                // No rounds which require an update
                if (!roundIds.Any())
                {
                    return;
                }

                #endregion

                var teamsInRound =
                    await TenantContext.DbContext.AppDb.TeamInRoundRepository.GetTeamInRoundAsync(
                        new PredicateExpression(TeamInRoundFields.RoundId.In(roundIds)), cancellationToken);

                foreach (var roundId in roundIds)
                {
                    /***** Ranking table update *****/

                    // rules can be different for every round
                    var matchRule =
                        await TenantContext.DbContext.AppDb.RoundRepository.GetMatchRuleAsync(roundId, cancellationToken);

                    // filter matches to only contain a single round
                    var ranking = new Ranking(matchesPlayed.Where(mp => mp.RoundId == roundId),
                                              matchesToPlay.Where(mtp => mtp.RoundId == roundId), (RankComparerEnum)matchRule.RankComparer);
                    // Update the ranking table
                    await TenantContext.DbContext.AppDb.RankingRepository.SaveAsync(ranking.GetList(out var lastUpdated),
                                                                                    roundId, cancellationToken);

                    /***** Chart file generation *****/

                    // without played matches, no chart can be generated
                    if (ranking.MatchesPlayed.Count == 0)
                    {
                        break;
                    }

                    var chart = new RankingChart(ranking,
                                                 teamsInRound.Select(tir => (tir.TeamId, tir.TeamNameForRound)).ToList(),
                                                 new RankingChart.ChartSettings
                    {
                        Title = null, XTitle = "MD", YTitle = "R", Width = 700, Height = 400,
                        GraphBackgroundColorArgb = "#FFEFFFEF", PlotAreaBackgroundColorArgb = "#FFFFFFFF",
                        FontName = "Arial, Helvetica, sans-serif", ShowLegend = false
                    })
                    {
                        UseMatchDayMarker = true
                    };

                    await using var chartStream = chart.GetPng();
                    await using var fileStream  = File.Create(Path.Combine(_webHostEnvironment.WebRootPath, RankingImageFolder,
                                                                           string.Format(RankingChartFilenameTemplate, TenantContext.Identifier, roundId,
                                                                                         DateTime.UtcNow.Ticks)));
                    chartStream.Seek(0, SeekOrigin.Begin);
                    await chartStream.CopyToAsync(fileStream, cancellationToken);
                }
            }
            catch (Exception e)
            {
                _logger.LogCritical(e, "Could not update ranking table and/or chart files");
            }

            DeleteObsoleteChartImageFiles(roundIds);
#if DEBUG
            stopWatch.Stop();
            _logger.LogInformation("{0} completed in {1}ms", nameof(RankingUpdateTask), stopWatch.ElapsedMilliseconds);
#endif
        }
        void Prepare()
        {
#if UNITY_EDITOR
            mPerfWatch.Reset();
            mPerfWatch.Start();
#endif
            if (Spline && StartMesh && ExtrusionParameter > 0)
            {
                StartMeshInfo = new MeshInfo(StartMesh, true, false);
                if (EndMesh)
                {
                    EndMeshInfo = new MeshInfo(EndMesh, false, true);
                }
                else
                {
                    EndMeshInfo = new MeshInfo(StartMesh, false, true);
                }



                // Calculate Steps
                float tf = FromTF;
                mSegmentInfo.Clear();
                FromTF = Mathf.Clamp01(FromTF);
                ToTF   = Mathf.Max(FromTF, Mathf.Clamp01(ToTF));
                Vector3 scale;
                if (FromTF != ToTF)
                {
                    switch (Extrusion)
                    {
                    case MeshExtrusion.FixedF:
                        while (tf < ToTF)
                        {
                            scale = getScale(tf);
                            mSegmentInfo.Add(new CurvyMeshSegmentInfo(this, tf, scale));
                            tf += ExtrusionParameter;
                        }
                        break;

                    case MeshExtrusion.FixedDistance:
                        float d = Spline.TFToDistance(FromTF);
                        tf = Spline.DistanceToTF(d);
                        while (tf < ToTF)
                        {
                            scale = getScale(tf);
                            mSegmentInfo.Add(new CurvyMeshSegmentInfo(this, tf, d, scale));
                            d += ExtrusionParameter;
                            tf = Spline.DistanceToTF(d);
                        }
                        break;

                    case MeshExtrusion.Adaptive:
                        while (tf < ToTF)
                        {
                            scale = getScale(tf);
                            mSegmentInfo.Add(new CurvyMeshSegmentInfo(this, tf, scale));
                            int dir = 1;
                            Spline.MoveByAngle(ref tf, ref dir, ExtrusionParameter, CurvyClamping.Clamp, 0.005f);
                        }

                        break;
                    }
                    if (!Mathf.Approximately(tf, ToTF))
                    {
                        tf = ToTF;
                    }
                    scale = getScale(tf);
                    mSegmentInfo.Add(new CurvyMeshSegmentInfo(this, tf, scale));
                }
            }
#if UNITY_EDITOR
            mPerfWatch.Stop();
            DebugPerfPrepare = mPerfWatch.ElapsedTicks / (double)System.TimeSpan.TicksPerMillisecond;
            mPerfWatch.Reset();
#endif
        }
Exemple #36
0
        private void btnExecute_Click(object sender, EventArgs e)
        {
            try
            {
                //Update vars with input text
                m_qry = scintQry.Text;

                //Create the query object
                qry = cv.createIEssOpMdxQuery();

                //TODO: Any other query properties that should be added here?
                if (Properties.Settings.Default.NameAlias == "NAME")
                {
                    qry.setQuery(false, m_qry, false, IEssOpMdxQuery.EEssMemberIdentifierType.NAME);
                }
                else
                {
                    qry.setQuery(false, m_qry, false, IEssOpMdxQuery.EEssMemberIdentifierType.ALIAS);
                }

                //Execute the query
                System.Diagnostics.Stopwatch qryTime = new System.Diagnostics.Stopwatch();
                qryTime.Start();
                cv.performOperation(qry);
                qryTime.Stop();

                //Update the status bar with run stats
                String   elapsed = null;
                TimeSpan ts      = qryTime.Elapsed;
                if (ts.Minutes > 0)
                {
                    elapsed = String.Format("Executed in: {0}:{1}.{2} minutes", ts.Minutes, ts.Seconds, ts.Milliseconds);
                }
                else
                {
                    elapsed = String.Format("Executed in: {0}.{1} seconds", ts.Seconds, ts.Milliseconds);
                }
                tsslExecTime.Text = elapsed;
                this.execState    = ExecutionState.QueryHasBeenExecuted;

                //Update the query history
                DataRow dr = this.dtQueryHistory.NewRow();
                dr["QueryText"]   = m_qry;
                dr["ElapsedTime"] = elapsed;
                dr["ExecutedBy"]  = this.essUser;
                dr["Timestamp"]   = DateTime.Now;
                this.dtQueryHistory.Rows.Add(dr);

                //Retrieve and parse the multi-dimensional data set
                IEssMdDataSet ds = cv.getMdDataSet();
                DataTable     dt = ParseMdDataSet(ds);

                //Bind the parsed data (DataTable obj) to the grid
                dgvResults.DataSource = dt;

                //Set the grid style
                DataGridViewCellStyle style = new DataGridViewCellStyle();
                style.BackColor = Color.Black;
                style.ForeColor = Color.White;
                style.Font      = new Font("Microsoft Sans Serif", 9, FontStyle.Bold);
                for (int i = 0; i < colHeaderRows; i++)
                {
                    dgvResults.Rows[i].DefaultCellStyle = style;
                }
                for (int i = 0; i < rowHeaderCols; i++)
                {
                    dgvResults.Columns[i].DefaultCellStyle = style;
                }
                dgvResults.AutoResizeColumns();
            }
            catch (Exception ex)
            {
                MessageBox.Show(String.Format("Error executing query: {0}", ex.Message), "Query Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemple #37
0
        public void ExecuteScript(string filePath)
        {
            CurrentStatus = EngineStatus.Running;
            FileName      = filePath;

            try
            {
                engineLogger.Information("Script Path: " + filePath);

                //create stopwatch for metrics tracking
                sw = new System.Diagnostics.Stopwatch();
                sw.Start();

                //log starting
                ReportProgress("Bot Engine Started: " + DateTime.Now.ToString());

                //parse file or streamed XML from tasktServer
                ReportProgress("Deserializing File");
                var automationScript = Core.Script.Script.DeserializeFile(filePath);

                //track variables and app instances
                ReportProgress("Creating Variable List");
                VariableList = automationScript.Variables;
                ReportProgress("Creating App Instance Tracking List");

                //create app instances and merge in global instances
                this.AppInstances = new Dictionary <string, object>();
                var GlobalInstances = GlobalAppInstances.GetInstances();
                foreach (var instance in GlobalInstances)
                {
                    this.AppInstances.Add(instance.Key, instance.Value);
                }


                //execute commands
                foreach (var executionCommand in automationScript.Commands)
                {
                    if (IsCancellationPending)
                    {
                        ReportProgress("Cancelling Script");
                        ScriptFinished(ScriptFinishedEventArgs.ScriptFinishedResult.Cancelled);
                        return;
                    }

                    ExecuteCommand(executionCommand);
                }

                if (IsCancellationPending)
                {
                    //mark cancelled - handles when cancelling and user defines 1 parent command or else it will show successful
                    ScriptFinished(ScriptFinishedEventArgs.ScriptFinishedResult.Cancelled);
                }
                else
                {
                    //mark finished
                    ScriptFinished(ScriptFinishedEventArgs.ScriptFinishedResult.Successful);
                }
            }
            catch (Exception ex)
            {
                ScriptFinished(ScriptFinishedEventArgs.ScriptFinishedResult.Error, ex.ToString());
            }
        }
Exemple #38
0
 public StopwatchScope()
 {
     m_sw = new System.Diagnostics.Stopwatch();
     m_sw.Start();
 }
Exemple #39
0
        private void ParseMouseUp(InputEventArgs e)
        {
            try
            {
                // if(string.IsNullOrEmpty(Thread.CurrentThread.Name)) Thread.CurrentThread.Name = "IE.Plugin.OnMouseUP";
                Log.Debug(string.Format("IE.Recording::OnMouseUp::begin"));
                var re = new RecordEvent
                {
                    Button = e.Button
                }; var a = new GetElement {
                    DisplayName = (e.Element.Name).Replace(Environment.NewLine, "").Trim()
                };

                var p = System.Diagnostics.Process.GetProcessById(e.Element.ProcessId);
                if (p.ProcessName != "iexplore" && p.ProcessName != "iexplore.exe")
                {
                    return;
                }

                var browser     = new Browser();
                var htmlelement = browser.ElementFromPoint(e.X, e.Y);
                if (htmlelement == null)
                {
                    return;
                }

                var sw = new System.Diagnostics.Stopwatch();
                sw.Start();
                IESelector sel = null;
                // sel = new IESelector(e.Element.rawElement, null, true);
                GenericTools.RunUI(() =>
                {
                    sel = new IESelector(browser, htmlelement, null, false, e.X, e.Y);
                });
                if (sel == null)
                {
                    return;
                }
                if (sel.Count < 2)
                {
                    return;
                }
                a.Selector   = sel.ToString();
                a.Image      = sel.Last().Element.ImageString();
                re.UIElement = e.Element;
                re.Element   = new IEElement(browser, htmlelement);
                re.Selector  = sel;
                re.X         = e.X;
                re.Y         = e.Y;

                Log.Debug(e.Element.SupportInput + " / " + e.Element.ControlType);
                re.a = new GetElementResult(a);
                //if (htmlelement.tagName.ToLower() == "input" && htmlelement.tagName.ToLower() == "select")
                if (htmlelement.tagName.ToLower() == "input")
                {
                    MSHTML.IHTMLInputElement inputelement = (MSHTML.IHTMLInputElement)htmlelement;
                    re.SupportInput = (inputelement.type.ToLower() == "text" || inputelement.type.ToLower() == "password");
                }
                re.SupportSelect = false;
                Log.Debug(string.Format("IE.Recording::OnMouseUp::end {0:mm\\:ss\\.fff}", sw.Elapsed));
                OnUserAction?.Invoke(this, re);
            }
            catch (Exception ex)
            {
                Log.Error(ex.ToString());
            }
        }
Exemple #40
0
        // Alpha beta searching with transposition table
        private double AlphaBeta(int[,] board, int color, int depth = 0, double alpha = double.NegativeInfinity, double beta = double.PositiveInfinity)
        {
            nodeCount += 1;

            evaluator.SetBoard(board);

            // Return evaluation value if reaching depth = depthMax or terminal node
            if (depth >= currentDepthMax)
            {
                return(evaluator.Evaluate(selfColor));
            }


            // Return evaluation when game ends
            List <Pos> newOptions    = evaluator.Availables(color);
            List <Pos> oppNewOptions = evaluator.Availables(StoneColor.OppColor(color));

            if (newOptions.Count == 0 && oppNewOptions.Count == 0)
            {
                int selfStones = evaluator.CountStones(selfColor);
                int oppStones  = evaluator.CountStones(StoneColor.OppColor(selfColor));
                if (selfStones > oppStones)
                {
                    return(double.PositiveInfinity);
                }
                else if (selfStones < oppStones)
                {
                    return(double.NegativeInfinity);
                }
                else
                {
                    return(evaluator.Evaluate(selfColor));
                }
            }


            // When only the opponent can put stone, go to next depth
            if (newOptions.Count == 0)
            {
                depth     += 1;
                color      = StoneColor.OppColor(color);
                newOptions = oppNewOptions;
            }


            // Expand board and store the all child boards in children list
            // Associate the child and the action of that time
            List <int[, ]>            children         = new List <int[, ]>();
            Dictionary <int[, ], Pos> actionChildTable = new Dictionary <int[, ], Pos>();

            foreach (Pos action in newOptions)
            {
                Board childBoard = new Board();
                childBoard.SetBoard(board);
                childBoard.UpdateBoard(action, color);
                children.Add(childBoard.GetBoard());
                actionChildTable.Add(childBoard.GetBoard(), action);
            }


            // Sort children in order of the score
            // In descending order when self turn and in ascending order when opponent turn
            st.Start();
            if (depth <= 3)
            {
                children = OrderBoards(children, color);
            }
            st.Stop();


            // Alpha beta searching
            if (color == selfColor)
            {
                // In self turn, search max value of children

                double score = double.NegativeInfinity;

                foreach (int[,] child in children)
                {
                    // Check if the child is stored in transposition table and the node type is EXACT
                    // If it does, set the value for the score
                    // If not, start alpha-beta-searching in next depth and store the score

                    string childHash = BoardToHash(child);

                    if (transpositionTable.ContainsKey(childHash) && transpositionTable[childHash].Depth >= currentDepthMax && transpositionTable[childHash].NodeType == "EXACT")
                    {
                        transpositionCutCount += 1;
                        score = transpositionTable[childHash].Score;
                    }
                    else
                    {
                        score = AlphaBeta(child, StoneColor.OppColor(color), depth + 1, alpha, beta);
                        transpositionTable[childHash] = new TranspositionTableEntry(child, currentDepthMax, score);
                    }


                    if (score > alpha)
                    {
                        alpha = score;

                        // Get best action
                        if (depth == 0)
                        {
                            foreach (KeyValuePair <int[, ], Pos> kvp in actionChildTable)
                            {
                                if (kvp.Key.Cast <int>().SequenceEqual(child.Cast <int>()))
                                {
                                    bestAction = kvp.Value;
                                }
                            }
                        }
                    }

                    // Beta cut
                    if (alpha >= beta)
                    {
                        betaCutCount += 1;
                        break;
                    }
                }
                return(alpha);
            }
            else
            {
                // If the opponent turn, search minimum value of children

                double score = double.PositiveInfinity;

                foreach (int[,] child in children)
                {
                    string childHash = BoardToHash(child);

                    if (transpositionTable.ContainsKey(childHash) && transpositionTable[childHash].Depth >= currentDepthMax && transpositionTable[childHash].NodeType == "EXACT")
                    {
                        transpositionCutCount += 1;
                        score = transpositionTable[childHash].Score;
                    }
                    else
                    {
                        score = AlphaBeta(child, StoneColor.OppColor(color), depth + 1, alpha, beta);
                        transpositionTable[childHash] = new TranspositionTableEntry(child, currentDepthMax, score);
                    }

                    beta = Math.Min(beta, score);

                    // Alpha cut
                    if (beta <= alpha)
                    {
                        alphaCutCount += 1;
                        break;
                    }
                }
                return(beta);
            }
        }
Exemple #41
0
        public override void Run()
        {
            #region Create renderers

            // Note: the renderers take care of creating their own
            // device resources and listen for DeviceManager.OnInitialize

            #region Initialize MeshRenderer instances
            List <I3Dobject> meshes = new List <I3Dobject>();

            // Create and initialize the mesh renderer
            var loadedMesh = Common.Mesh.LoadFromFile("Projet.cmo");
            List <MeshRenderer> tempMeshes = new List <MeshRenderer>();
            tempMeshes.AddRange((from mesh in loadedMesh
                                 select ToDispose(new MeshRenderer(mesh))));

            var         spheres = new List <SphereRenderer>();
            SkyBox      skyBox  = null;
            ObjRenderer venus;

            ShadowMap shadowMap = null;

            // We will support a cubemap for each mesh that contains "reflector" in its name
            List <DynamicCubeMap> envMaps = new List <DynamicCubeMap>();

            // We will rotate any meshes that contains "rotate" in its name
            List <MeshRenderer> rotateMeshes = new List <MeshRenderer>();

            // We will generate meshRows * meshColumns of any mesh that contains "replicate" in its name
            int meshRows    = 10;
            int meshColumns = 10;

            // Define an action to initialize our meshes so that we can
            // dynamically change the number of reflective surfaces and
            // replicated meshes
            Action createMeshes = () =>
            {
                if (shadowMap)
                {
                    shadowMap.Dispose();
                }

                shadowMap = ToDispose(new ShadowMap((uint)this.Viewport.Width, (uint)this.Viewport.Height));
                shadowMap.Initialize(this);
                // Clear context states, ensures we don't have
                // any of the resources we are going to release
                // assigned to the pipeline.
                DeviceManager.Direct3DContext.ClearState();
                if (contextList != null)
                {
                    foreach (var context in contextList)
                    {
                        context.ClearState();
                    }
                }

                // Remove meshes
                foreach (var mesh in meshes)
                {
                    mesh.Dispose();
                }
                meshes.Clear();

                // Remove environment maps
                foreach (var envMap in envMaps)
                {
                    envMap.Dispose();
                }
                envMaps.Clear();

                // Add skybox to make it render first
                if (skyBox != null)
                {
                    skyBox.Dispose();
                }
                skyBox = ToDispose(new SkyBox());
                skyBox.PerObjectBuffer = perObjectBuffer;
                meshes.Add(skyBox);


                venus       = ToDispose(new ObjRenderer("Models/venus-low.obj"));
                venus.World = Matrix.Scaling(0.15f);

                meshes.Add(venus);
                //meshes.Add(robot);

                spheres.ForEach(s =>
                {
                    s.Dispose();
                    s = null;
                });
                spheres.Clear();
                var colors = new[] { Color.Red, Color.Green, Color.Blue };
                for (int i = 1; i <= 5; i++)
                {
                    var s = ToDispose(new SphereRenderer(colors[i % colors.Length]));
                    s.Initialize(this);
                    //s.World = Matrix.Translation((float)(i * 1.5 / 2 * Math.Pow(-1, i)), 1f, 1f);
                    var pos = new Vector3((float)(-5f + i * (s.MeshExtent.Radius * 3)), 1f, (float)(1.5 / 2 * Math.Pow(-1, i)));
                    s.World    = Matrix.Translation(pos);
                    s.Position = pos;
                    spheres.Add(s);
                }

                #region Create replicated meshes
                // Add the same mesh multiple times, separate by the combined extent
                var replicatedMeshes = (from mesh in loadedMesh
                                        where (mesh.Name ?? "").ToLower().Contains("replicate")
                                        select mesh).ToArray();
                if (replicatedMeshes.Length > 0)
                {
                    var minExtent = (from mesh in replicatedMeshes
                                     orderby new { mesh.Extent.Min.X, mesh.Extent.Min.Z }
                                     select mesh.Extent).First();
                    var maxExtent = (from mesh in replicatedMeshes
                                     orderby new { mesh.Extent.Max.X, mesh.Extent.Max.Z } descending
                                     select mesh.Extent).First();
                    var extentDiff = (maxExtent.Max - minExtent.Min);

                    for (int x = -(meshColumns / 2); x < (meshColumns / 2); x++)
                    {
                        for (int z = -(meshRows / 2); z < (meshRows / 2); z++)
                        {
                            var meshGroup = (from mesh in replicatedMeshes
                                             where (mesh.Name ?? "").ToLower().Contains("replicate")
                                             select ToDispose(new MeshRenderer(mesh))).ToList();

                            // Reposition based on width/depth of combined extent
                            foreach (var m in meshGroup)
                            {
                                m.World.TranslationVector = new Vector3(m.Mesh.Extent.Center.X + extentDiff.X * x, m.Mesh.Extent.Min.Y, m.Mesh.Extent.Center.Z + extentDiff.Z * z);
                            }

                            //meshes.AddRange(meshGroup.Select(m=> m as I3Dobject));
                        }
                    }
                }
                #endregion

                #region Create reflective meshes
                // Create reflections where necessary and add rotation meshes
                int reflectorCount = 0;
                meshes.ForEach(m =>
                {
                    var name = (m.Mesh.Name ?? "").ToLower();
                    if (name.Contains("reflector") && reflectorCount < maxReflectors)
                    {
                        reflectorCount++;
                        var envMap       = ToDispose(new DynamicCubeMap(1024));
                        envMap.Reflector = (RendererBase)m;
                        envMap.Initialize(this);
                        m.EnvironmentMap = envMap;
                        envMaps.Add(envMap);
                    }
                    if (name.Contains("rotate"))
                    {
                        rotateMeshes.Add((MeshRenderer)m);
                    }

                    m.Initialize(this);
                });
                spheres.ForEach(s =>
                {
                    var envMap       = ToDispose(new DynamicCubeMap(1024));
                    envMap.Reflector = s;
                    envMap.Initialize(this);
                    s.EnvironmentMap = envMap;
                    envMaps.Add(envMap);
                });


                var venusEnv = ToDispose(new DynamicCubeMap(1024));
                venusEnv.Reflector = venus;
                venusEnv.Initialize(this);
                venus.EnvironmentMap = venusEnv;

                envMaps.AddRange(new[] { venusEnv /*, robotEnv*/ });
                #endregion

                // Initialize each mesh
                // meshes.ForEach(m => m.Initialize(this));
                meshes.AddRange(spheres.Select(s => s as I3Dobject));
                //spheres.ForEach(s => s.Initialize(this));
            };
            createMeshes();

            // Set the first animation as the current animation and start clock
            meshes.ForEach(m =>
            {
                if (m.Mesh != null)
                {
                    if (m.Mesh.Animations != null && m.Mesh.Animations.Any())
                    {
                        m.CurrentAnimation = m.Mesh.Animations.First().Value;
                    }
                    m.Clock.Start();
                }
            });

            // Create the overall mesh World matrix
            var meshWorld = Matrix.Identity;

            #endregion


            // Create an axis-grid renderer
            var axisGrid = ToDispose(new AxisGridRenderer());
            axisGrid.Initialize(this);

            // Create and initialize a Direct2D FPS text renderer
            var fps = ToDispose(new Common.FpsRenderer("Calibri", Color.CornflowerBlue, new Point(8, 8), 16));
            fps.Initialize(this);

            // Create and initialize a general purpose Direct2D text renderer
            // This will display some instructions and the current view and rotation offsets
            var textRenderer = ToDispose(new Common.TextRenderer("Calibri", Color.CornflowerBlue, new Point(8, 40), 12));
            textRenderer.Initialize(this);

            #endregion
            base.SizeChanged(true);

            // Initialize the world matrix
            var worldMatrix = Matrix.Identity;

            // Set the camera position
            cameraPosition = new Vector3(0, 1, 2);
            cameraTarget   = Vector3.Zero;  // Looking at the origin 0,0,0
            cameraUp       = Vector3.UnitY; // Y+ is Up

            // Prepare matrices
            // Create the view matrix from our camera position, look target and up direction
            viewMatrix = Matrix.LookAtRH(cameraPosition, cameraTarget, cameraUp);
            viewMatrix.TranslationVector += new Vector3(0, -0.98f, 0);

            // Create the projection matrix
            /* FoV 60degrees = Pi/3 radians */
            // Aspect ratio (based on window size), Near clip, Far clip
            projectionMatrix = Matrix.PerspectiveFovRH((float)Math.PI / 3f, Width / (float)Height, 0.1f, 100f);



            // Maintain the correct aspect ratio on resize
            Window.Resize += (s, e) =>
            {
                projectionMatrix = Matrix.PerspectiveFovRH((float)Math.PI / 3f, Width / (float)Height, 0.1f, 100f);
            };

            #region Rotation and window event handlers

            // Create a rotation vector to keep track of the rotation
            // around each of the axes
            var rotation = new Vector3(0.0f, 0.0f, 0.0f);

            // We will call this action to update text
            // for the text renderer
            Action updateText = () =>
            {
                textRenderer.Text =
                    String.Format(
                        "\nPause rotation: P"
                        + "\nLighting mode: {0} (Shift-Up/Down)"
                        + "\n"
                        ,
                        threadCount);
            };

            Dictionary <Keys, bool> keyToggles = new Dictionary <Keys, bool>();
            keyToggles[Keys.Z] = false;
            keyToggles[Keys.F] = false;

            // Support keyboard/mouse input to rotate or move camera view
            var moveFactor = 0.02f; // how much to change on each keypress
            var shiftKey   = false;
            var ctrlKey    = false;
            var background = Color.Black;
            Window.KeyDown += (s, e) =>
            {
                var context = DeviceManager.Direct3DContext;

                shiftKey = e.Shift;
                ctrlKey  = e.Control;

                switch (e.KeyCode)
                {
                // WASD -> pans view
                case Keys.A:
                    viewMatrix.TranslationVector += new Vector3(moveFactor * 2, 0f, 0f);
                    break;

                case Keys.D:
                    viewMatrix.TranslationVector -= new Vector3(moveFactor * 2, 0f, 0f);
                    break;

                case Keys.S:
                    if (shiftKey)
                    {
                        viewMatrix.TranslationVector += new Vector3(0f, moveFactor * 2, 0f);
                    }
                    else
                    {
                        viewMatrix.TranslationVector -= new Vector3(0f, 0f, 1) * moveFactor * 2;
                    }
                    break;

                case Keys.W:
                    if (shiftKey)
                    {
                        viewMatrix.TranslationVector -= new Vector3(0f, moveFactor * 2, 0f);
                    }
                    else
                    {
                        viewMatrix.TranslationVector += new Vector3(0f, 0f, 1) * moveFactor * 2;
                    }
                    break;

                // Up/Down and Left/Right - rotates around X / Y respectively
                // (Mouse wheel rotates around Z)
                //case Keys.Down:
                //    worldMatrix *= Matrix.RotationX(moveFactor);
                //    rotation += new Vector3(moveFactor, 0f, 0f);
                //    break;
                //case Keys.Up:
                //    worldMatrix *= Matrix.RotationX(-moveFactor);
                //    rotation -= new Vector3(moveFactor, 0f, 0f);
                //    break;
                //case Keys.Left:
                //    worldMatrix *= Matrix.RotationY(moveFactor);
                //    rotation += new Vector3(0f, moveFactor, 0f);
                //    break;
                //case Keys.Right:
                //    worldMatrix *= Matrix.RotationY(-moveFactor);
                //    rotation -= new Vector3(0f, moveFactor, 0f);
                //    break;
                case Keys.T:
                    fps.Show          = !fps.Show;
                    textRenderer.Show = !textRenderer.Show;
                    break;

                //case Keys.B:
                //    if (background == Color.White)
                //    {
                //        background = new Color(30, 30, 34);
                //    }
                //    else
                //    {
                //        background = Color.White;
                //    }
                //    break;
                case Keys.G:
                    axisGrid.Show = !axisGrid.Show;
                    break;

                case Keys.P:
                    break;

                case Keys.X:
                    // To test for correct resource recreation
                    // Simulate device reset or lost.
                    System.Diagnostics.Debug.WriteLine(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects());
                    DeviceManager.Initialize(DeviceManager.Dpi);
                    System.Diagnostics.Debug.WriteLine(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects());
                    break;

                case Keys.F:
                    keyToggles[Keys.F] = !keyToggles[Keys.F];
                    RasterizerStateDescription rasterDesc;
                    if (context.Rasterizer.State != null)
                    {
                        rasterDesc = context.Rasterizer.State.Description;
                    }
                    else
                    {
                        rasterDesc = new RasterizerStateDescription()
                        {
                            CullMode = CullMode.Back,
                            FillMode = FillMode.Solid
                        }
                    };
                    if (keyToggles[Keys.F])
                    {
                        rasterDesc.FillMode = FillMode.Wireframe;
                        rasterizerState     = ToDispose(new RasterizerState(context.Device, rasterDesc));
                    }
                    else
                    {
                        rasterDesc.FillMode = FillMode.Solid;
                        rasterizerState     = ToDispose(new RasterizerState(context.Device, rasterDesc));
                    }
                    break;

                case Keys.L: normalLighting = 0; break;

                case Keys.M: normalLighting = 1; break;

                case Keys.C: specularEnviron = specularEnviron == 0 ? 1u : 0; break;

                case Keys.B: specularLocal = specularLocal == 0 ? 1u : 0; break;
                }

                updateText();
            };
            Window.KeyUp += (s, e) =>
            {
                // Clear the shift/ctrl keys so they aren't sticky
                if (e.KeyCode == Keys.ShiftKey)
                {
                    shiftKey = false;
                }
                if (e.KeyCode == Keys.ControlKey)
                {
                    ctrlKey = false;
                }
            };
            Window.MouseWheel += (s, e) =>
            {
                if (shiftKey)
                {
                    // Zoom in/out
                    viewMatrix.TranslationVector += new Vector3(0f, 0f, (e.Delta / 120f) * moveFactor * 2);
                }
                else
                {
                    // rotate around Z-axis
                    viewMatrix *= Matrix.RotationZ((e.Delta / 120f) * moveFactor);
                    rotation   += new Vector3(0f, 0f, (e.Delta / 120f) * moveFactor);
                }
                updateText();
            };

            var lastX = 0;
            var lastY = 0;

            Window.MouseDown += (s, e) =>
            {
                if (e.Button == MouseButtons.Left)
                {
                    lastX = e.X;
                    lastY = e.Y;
                }
            };

            Window.MouseMove += (s, e) =>
            {
                if (e.Button == MouseButtons.Left)
                {
                    var yRotate = lastX - e.X;
                    var xRotate = lastY - e.Y;
                    lastY = e.Y;
                    lastX = e.X;

                    // Mouse move changes
                    viewMatrix *= Matrix.RotationX(-xRotate * moveFactor);
                    viewMatrix *= Matrix.RotationY(-yRotate * moveFactor);

                    updateText();
                }
            };

            // Display instructions with initial values
            updateText();

            #endregion

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

            // Setup the deferred contexts
            SetupContextList();

            #region Render loop

            // Whether or not to reinitialize meshes
            bool initializeMesh = false;

            // Define additional key handlers for controlling the
            // number of threads, reflectors, and replicated meshes
            #region Dynamic Cube map and threading KeyDown handlers
            Window.KeyDown += (s, e) =>
            {
                switch (e.KeyCode)
                {
                case Keys.Up:
                    if (shiftKey)
                    {
                        maxReflectors++;
                    }
                    else
                    {
                        meshRows += 2;
                    }
                    initializeMesh = true;
                    break;

                case Keys.Down:
                    if (shiftKey)
                    {
                        maxReflectors = Math.Max(0, maxReflectors - 1);
                    }
                    else
                    {
                        meshRows = Math.Max(2, meshRows - 2);
                    }
                    initializeMesh = true;
                    break;

                case Keys.Right:
                    meshColumns   += 2;
                    initializeMesh = true;
                    break;

                case Keys.Left:
                    meshColumns    = Math.Max(2, meshColumns - 2);
                    initializeMesh = true;
                    break;

                case Keys.Add:
                    if (shiftKey)
                    {
                        additionalCPULoad += 100;
                    }
                    else
                    {
                        threadCount++;
                    }
                    break;

                case Keys.Subtract:
                    if (shiftKey)
                    {
                        additionalCPULoad = Math.Max(0, additionalCPULoad - 100);
                    }
                    else
                    {
                        threadCount = Math.Max(1, threadCount - 1);
                    }
                    break;

                case Keys.G:
                    buildCubeMapGeometryInstancing = !buildCubeMapGeometryInstancing;
                    break;

                default:
                    break;
                }
                updateText();
            };
            #endregion

            #region Render mesh group
            // Action for rendering a group of meshes for a
            // context (based on number of available contexts)
            Action <int, DeviceContext, Matrix, Matrix> renderMeshGroup = (contextIndex, renderContext, view, projection) =>
            {
                var viewProjection = view * projection;


                // Determine the meshes to render for this context
                int batchSize  = (int)Math.Floor((double)meshes.Count / contextList.Length);
                int startIndex = batchSize * contextIndex;
                int endIndex   = Math.Min(startIndex + batchSize, meshes.Count - 1);
                // If this is the last context include whatever remains to be
                // rendered due to the rounding above.
                if (contextIndex == contextList.Length - 1)
                {
                    endIndex = meshes.Count - 1;
                }

                // Loop over the meshes for this context and render them
                var perObject = new ConstantBuffers.PerObject();
                for (var i = startIndex; i <= endIndex; i++)
                {
                    // Retrieve current mesh
                    var m = meshes[i];

                    perObject.World = m.World * worldMatrix;
                    // Update perObject constant buffer
                    perObject.WorldInverseTranspose = Matrix.Transpose(Matrix.Invert(perObject.World));
                    perObject.WorldViewProjection   = perObject.World * viewProjection;
                    perObject.Transpose();
                    renderContext.UpdateSubresource(ref perObject, perObjectBuffer);

                    // Provide the material and armature constant buffer to the mesh renderer
                    m.PerArmatureBuffer = perArmatureBuffer;
                    m.PerMaterialBuffer = perMaterialBuffer;

                    m.PerObjectBuffer = perObjectBuffer;

                    // Render the mesh using the provided DeviceContext
                    m.Render(renderContext);
                }
            };

            #endregion

            #region Render scene
            Vector3 lightDirection;
            // Action for rendering the entire scene
            Action <DeviceContext, Matrix, Matrix, RenderTargetView, DepthStencilView, DynamicCubeMap> renderScene = (context, view, projection, rtv, dsv, envMap) =>
            {
                // We must initialize the context every time we render
                // the scene as we are changing the state depending on
                // whether we are rendering the envmaps or final scene
                InitializeContext(context, false);

                // We always need the immediate context
                // Note: the passed in context will normally be the immediate context
                // however it is possible to run this method threaded also.
                var immediateContext = this.DeviceManager.Direct3DDevice.ImmediateContext;

                // Clear depth stencil view
                context.ClearDepthStencilView(dsv, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0);
                // Clear render target view
                if (rtv != null)
                {
                    context.ClearRenderTargetView(rtv, background);
                }

                // Create viewProjection matrix
                var viewProjection = Matrix.Multiply(view, projection);

                // Extract camera position from view
                var camPosition = Matrix.Transpose(Matrix.Invert(view)).Column4;
                cameraPosition = new Vector3(camPosition.X, camPosition.Y, camPosition.Z);

                // Update scene variable properties
                Scene.Model          = worldMatrix;
                Scene.View           = view;
                Scene.ViewProjection = viewProjection;
                Scene.Projection     = projection;
                Scene.CameraPosition = cameraPosition;
                Scene.Time           = clock.ElapsedMilliseconds;

                // Setup the per frame constant buffer
                var perFrame = new ConstantBuffers.PerFrame();
                perFrame.Light.Color = new Color(0.9f, 0.9f, 0.9f, 1.0f);
                var lightDir = Vector3.Transform(new Vector3(-1f, -1f, -1f), worldMatrix);
                perFrame.Light.Direction = new Vector3(lightDir.X, lightDir.Y, lightDir.Z);
                perFrame.CameraPosition  = cameraPosition;
                perFrame.NormalLighting  = normalLighting;
                //perFrame.SpecularEnviron = specularEnviron;
                //perFrame.SpecularLocal = specularLocal;

                context.UpdateSubresource(ref perFrame, perFrameBuffer);
                lightDirection = new Vector3(lightDir.X, lightDir.Y, lightDir.Z);
                // Render each object

                // Prepare the default per material constant buffer
                var perMaterial = new ConstantBuffers.PerMaterial();
                perMaterial.Ambient       = new Color4(0.2f);
                perMaterial.Diffuse       = Color.White;
                perMaterial.Emissive      = new Color4(0);
                perMaterial.Specular      = Color.White;
                perMaterial.SpecularPower = 20f;
                context.UpdateSubresource(ref perMaterial, perMaterialBuffer);

                context.PixelShader.SetShaderResource(2, textureCube);

                // ----------Render meshes------------

                if (contextList.Length == 1)
                {
                    // If there is only one context available there is no need to
                    // generate command lists and execute them so just render the
                    // mesh directly on the current context (which may or may
                    // not be an immediate context depending on the caller).
                    renderMeshGroup(0, context, view, projection);
                }
                else
                {
                    // There are multiple contexts therefore
                    // we are using deferred contexts. Prepare a
                    // separate thread for each available context
                    // and render a group of meshes on each.
                    Task[]        renderTasks = new Task[contextList.Length];
                    CommandList[] commands    = new CommandList[contextList.Length];
                    var           viewports   = context.Rasterizer.GetViewports();

                    for (var i = 0; i < contextList.Length; i++)
                    {
                        // Must store the iteration value in another variable
                        // or each task action will use the last iteration value.
                        var contextIndex = i;

                        // Create task to run on new thread from ThreadPool
                        renderTasks[i] = Task.Run(() =>
                        {
                            // Retrieve context for this thread
                            var renderContext = contextList[contextIndex];
                            // Initialize the context state
                            InitializeContext(renderContext, false);

                            // Set the render targets and viewport
                            renderContext.OutputMerger.SetRenderTargets(dsv, rtv);
                            renderContext.Rasterizer.SetViewports(viewports);

                            // If we are rendering for a cubemap we must set the
                            // per environment map buffer.
                            if (envMap != null)
                            {
                                renderContext.GeometryShader.SetConstantBuffer(4, envMap.PerEnvMapBuffer);
                            }

                            // Render logic
                            renderMeshGroup(contextIndex, renderContext, view, projection);

                            // Create the command list
                            if (renderContext.TypeInfo == DeviceContextType.Deferred)
                            {
                                commands[contextIndex] = renderContext.FinishCommandList(false);
                            }
                        });
                    }
                    // Wait for all the tasks to complete
                    Task.WaitAll(renderTasks);

                    // Replay the command lists on the immediate context
                    for (var i = 0; i < contextList.Length; i++)
                    {
                        if (contextList[i].TypeInfo == DeviceContextType.Deferred && commands[i] != null)
                        {
                            immediateContext.ExecuteCommandList(commands[i], false);
                            // Clean up command list
                            commands[i].Dispose();
                            commands[i] = null;
                        }
                    }
                }
            };

            #endregion

            long frameCount      = 0;
            int  lastThreadCount = threadCount;

            // Create and run the render loop
            RenderLoop.Run(Window, () =>
            {
                // Allow dynamic changes to number of reflectors and replications
                if (initializeMesh)
                {
                    initializeMesh = false;
                    createMeshes();
                }

                // Allow dynamic chnages to the number of threads to use
                if (lastThreadCount != threadCount)
                {
                    SetupContextList();
                    lastThreadCount = threadCount;
                }

                // Start of frame:
                frameCount++;

                // Retrieve immediate context
                var context = DeviceManager.Direct3DContext;

                if (frameCount % 3 == 1) // to update cubemap once every third frame
                {
                    #region Update environment maps

                    // Update each of the cubemaps
                    if (buildCubeMapGeometryInstancing)
                    {
                        activeVertexShader   = envMapVSShader;
                        activeGeometryShader = envMapGSShader;
                        activePixelShader    = envMapPSShader;
                    }
                    else
                    {
                        //activeVertexShader = vertexShader;
                        //activeGeometryShader = null;
                        //activePixelShader = blinnPhongShader;
                    }

                    // Render the scene from the perspective of each of the environment maps
                    SkyBox.EnableSkyBoxState = (specularEnviron == 1u);
                    foreach (var envMap in envMaps)
                    {
                        var mesh = envMap.Reflector as I3Dobject;
                        if (mesh != null)
                        {
                            // Calculate view point for reflector
                            var meshCenter = Vector3.Transform(mesh.MeshExtent.Center, mesh.World * worldMatrix);
                            envMap.SetViewPoint(new Vector3(meshCenter.X, meshCenter.Y, meshCenter.Z));
                            if (buildCubeMapGeometryInstancing)
                            {
                                // Render cubemap in single full render pass using
                                // geometry shader instancing.
                                envMap.UpdateSinglePass(context, renderScene);
                            }
                        }
                    }

                    //activeVertexShader = shadowVSShader;
                    //activeGeometryShader = null;
                    //activePixelShader = null;

                    //InitializeContext(context, false);

                    //var lightDir = Vector3.Transform(new Vector3(-1f, -1f, -1f), worldMatrix);
                    //shadowMap.SetLightDirection(new Vector3(lightDir.X, lightDir.Y, lightDir.Z));
                    //shadowMap.Update(context, renderScene);
                    #endregion
                }

                #region Render final scene
                // Reset the vertex, geometry and pixel shader
                activeVertexShader   = vertexShader;
                activeGeometryShader = null;
                activePixelShader    = blinnPhongShader;
                // Initialize context (also resetting the render targets)
                InitializeContext(context, true);

                // Render the final scene
                SkyBox.EnableSkyBoxState = true;
                renderScene(context, viewMatrix, projectionMatrix, RenderTargetView, DepthStencilView, null);
                #endregion

                // Render FPS
                fps.Render();

                // Render instructions + position changes
                textRenderer.Render();

                // Present the frame
                Present();
            });
            #endregion
        }
Exemple #42
0
 public void StartTime()
 {
     stopwatch.Start();
 }
Exemple #43
0
        static Dictionary <string, long> laptimes;       // holds lap counters, defined by string IDs

        private static void CreateStopWatch()
        {
            stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();
            laptimes = new Dictionary <string, long>();
        }
        public List <ImportResult> Import(List <ImportDecision <LocalBook> > decisions, bool replaceExisting, DownloadClientItem downloadClientItem = null, ImportMode importMode = ImportMode.Auto)
        {
            var importResults         = new List <ImportResult>();
            var allImportedTrackFiles = new List <BookFile>();
            var allOldTrackFiles      = new List <BookFile>();
            var addedAuthors          = new List <Author>();
            var addedBooks            = new List <Book>();

            var bookDecisions = decisions.Where(e => e.Item.Book != null && e.Approved)
                                .GroupBy(e => e.Item.Book.ForeignBookId).ToList();

            var iDecision = 1;

            foreach (var bookDecision in bookDecisions)
            {
                _logger.ProgressInfo($"Importing book {iDecision++}/{bookDecisions.Count} {bookDecision.First().Item.Book}");

                var decisionList = bookDecision.ToList();

                var author = EnsureAuthorAdded(decisionList, addedAuthors);

                if (author == null)
                {
                    // failed to add the author, carry on with next book
                    continue;
                }

                var book = EnsureBookAdded(decisionList, addedBooks);

                if (book == null)
                {
                    // failed to add the book, carry on with next one
                    continue;
                }

                var edition = EnsureEditionAdded(decisionList);

                if (edition == null)
                {
                    // failed to add the edition, carry on with next one
                    continue;
                }

                // if (replaceExisting)
                // {
                //     RemoveExistingTrackFiles(author, book);
                // }

                // make sure part numbers are populated for audio books
                // If all audio files and all part numbers are zero, set them by filename order
                if (decisionList.All(b => MediaFileExtensions.AudioExtensions.Contains(Path.GetExtension(b.Item.Path)) && b.Item.Part == 0))
                {
                    var part = 1;
                    foreach (var d in decisionList.OrderBy(x => PadNumbers.Replace(x.Item.Path)))
                    {
                        d.Item.Part = part++;
                    }
                }

                // set the correct release to be monitored before importing the new files
                var newRelease = bookDecision.First().Item.Edition;
                _logger.Debug("Updating release to {0}", newRelease);
                book.Editions = _editionService.SetMonitored(newRelease);

                // Publish book edited event.
                // Deliberatly don't put in the old book since we don't want to trigger an AuthorScan.
                _eventAggregator.PublishEvent(new BookEditedEvent(book, book));
            }

            var qualifiedImports = decisions.Where(c => c.Approved)
                                   .GroupBy(c => c.Item.Author.Id, (i, s) => s
                                            .OrderByDescending(c => c.Item.Quality, new QualityModelComparer(s.First().Item.Author.QualityProfile))
                                            .ThenByDescending(c => c.Item.Size))
                                   .SelectMany(c => c)
                                   .ToList();

            _logger.ProgressInfo($"Importing {qualifiedImports.Count} files");
            _logger.Debug($"Importing {qualifiedImports.Count} files. replaceExisting: {replaceExisting}");

            var filesToAdd          = new List <BookFile>(qualifiedImports.Count);
            var trackImportedEvents = new List <TrackImportedEvent>(qualifiedImports.Count);

            foreach (var importDecision in qualifiedImports)
            {
                var localTrack = importDecision.Item;
                var oldFiles   = new List <BookFile>();

                try
                {
                    //check if already imported
                    if (importResults.Where(r => r.ImportDecision.Item.Book.Id == localTrack.Book.Id).Any(r => r.ImportDecision.Item.Part == localTrack.Part))
                    {
                        importResults.Add(new ImportResult(importDecision, "Book has already been imported"));
                        continue;
                    }

                    localTrack.Book.Author = localTrack.Author;

                    var bookFile = new BookFile
                    {
                        Path         = localTrack.Path.CleanFilePath(),
                        CalibreId    = localTrack.CalibreId,
                        Part         = localTrack.Part,
                        PartCount    = localTrack.PartCount,
                        Size         = localTrack.Size,
                        Modified     = localTrack.Modified,
                        DateAdded    = DateTime.UtcNow,
                        ReleaseGroup = localTrack.ReleaseGroup,
                        Quality      = localTrack.Quality,
                        MediaInfo    = localTrack.FileTrackInfo.MediaInfo,
                        EditionId    = localTrack.Edition.Id,
                        Author       = localTrack.Author,
                        Edition      = localTrack.Edition
                    };

                    bool copyOnly;
                    switch (importMode)
                    {
                    default:
                    case ImportMode.Auto:
                        copyOnly = downloadClientItem != null && !downloadClientItem.CanMoveFiles;
                        break;

                    case ImportMode.Move:
                        copyOnly = false;
                        break;

                    case ImportMode.Copy:
                        copyOnly = true;
                        break;
                    }

                    if (!localTrack.ExistingFile)
                    {
                        bookFile.SceneName = GetSceneReleaseName(downloadClientItem);

                        var moveResult = _bookFileUpgrader.UpgradeBookFile(bookFile, localTrack, copyOnly);
                        oldFiles = moveResult.OldFiles;
                    }
                    else
                    {
                        // Delete existing files from the DB mapped to this path
                        var previousFile = _mediaFileService.GetFileWithPath(bookFile.Path);

                        if (previousFile != null)
                        {
                            _mediaFileService.Delete(previousFile, DeleteMediaFileReason.ManualOverride);

                            if (bookFile.CalibreId == 0 && previousFile.CalibreId != 0)
                            {
                                bookFile.CalibreId = previousFile.CalibreId;
                            }
                        }

                        _metadataTagService.WriteTags(bookFile, false);
                    }

                    filesToAdd.Add(bookFile);
                    importResults.Add(new ImportResult(importDecision));

                    if (!localTrack.ExistingFile)
                    {
                        _extraService.ImportTrack(localTrack, bookFile, copyOnly);
                    }

                    allImportedTrackFiles.Add(bookFile);
                    allOldTrackFiles.AddRange(oldFiles);

                    // create all the import events here, but we can't publish until the trackfiles have been
                    // inserted and ids created
                    trackImportedEvents.Add(new TrackImportedEvent(localTrack, bookFile, oldFiles, !localTrack.ExistingFile, downloadClientItem));
                }
                catch (RootFolderNotFoundException e)
                {
                    _logger.Warn(e, "Couldn't import book " + localTrack);
                    _eventAggregator.PublishEvent(new TrackImportFailedEvent(e, localTrack, !localTrack.ExistingFile, downloadClientItem));

                    importResults.Add(new ImportResult(importDecision, "Failed to import book, root folder missing."));
                }
                catch (DestinationAlreadyExistsException e)
                {
                    _logger.Warn(e, "Couldn't import book " + localTrack);
                    importResults.Add(new ImportResult(importDecision, "Failed to import book, destination already exists."));
                }
                catch (UnauthorizedAccessException e)
                {
                    _logger.Warn(e, "Couldn't import book " + localTrack);
                    _eventAggregator.PublishEvent(new TrackImportFailedEvent(e, localTrack, !localTrack.ExistingFile, downloadClientItem));

                    importResults.Add(new ImportResult(importDecision, "Failed to import book, permissions error"));
                }
                catch (CalibreException e)
                {
                    _logger.Warn(e, "Couldn't import book " + localTrack);

                    importResults.Add(new ImportResult(importDecision, "Failed to import book, error communicating with Calibre.  Check log for details."));
                }
                catch (Exception e)
                {
                    _logger.Warn(e, "Couldn't import book " + localTrack);
                    importResults.Add(new ImportResult(importDecision, "Failed to import book."));
                }
            }

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

            watch.Start();
            _mediaFileService.AddMany(filesToAdd);
            _logger.Debug($"Inserted new trackfiles in {watch.ElapsedMilliseconds}ms");

            // now that trackfiles have been inserted and ids generated, publish the import events
            foreach (var trackImportedEvent in trackImportedEvents)
            {
                _eventAggregator.PublishEvent(trackImportedEvent);
            }

            var bookImports = importResults.Where(e => e.ImportDecision.Item.Book != null)
                              .GroupBy(e => e.ImportDecision.Item.Book.Id).ToList();

            foreach (var bookImport in bookImports)
            {
                var book    = bookImport.First().ImportDecision.Item.Book;
                var edition = book.Editions.Value.Single(x => x.Monitored);
                var author  = bookImport.First().ImportDecision.Item.Author;

                if (bookImport.Where(e => e.Errors.Count == 0).ToList().Count > 0 && author != null && book != null)
                {
                    _eventAggregator.PublishEvent(new BookImportedEvent(
                                                      author,
                                                      book,
                                                      allImportedTrackFiles.Where(s => s.EditionId == edition.Id).ToList(),
                                                      allOldTrackFiles.Where(s => s.EditionId == edition.Id).ToList(),
                                                      replaceExisting,
                                                      downloadClientItem));
                }
            }

            //Adding all the rejected decisions
            importResults.AddRange(decisions.Where(c => !c.Approved)
                                   .Select(d => new ImportResult(d, d.Rejections.Select(r => r.Reason).ToArray())));

            // Refresh any authors we added
            if (addedAuthors.Any())
            {
                _commandQueueManager.Push(new BulkRefreshAuthorCommand(addedAuthors.Select(x => x.Id).ToList(), true));
            }

            var addedAuthorMetadataIds = addedAuthors.Select(x => x.AuthorMetadataId).ToHashSet();
            var booksToRefresh         = addedBooks.Where(x => !addedAuthorMetadataIds.Contains(x.AuthorMetadataId)).ToList();

            if (booksToRefresh.Any())
            {
                _logger.Debug($"Refreshing info for {booksToRefresh.Count} new books");
                _commandQueueManager.Push(new BulkRefreshBookCommand(booksToRefresh.Select(x => x.Id).ToList()));
            }

            return(importResults);
        }
            private IEnumerator PopulateListRoutine()
            {
                while (true)
                {
                    if (this.IsPopulated)
                    {
                        yield return(null);

                        continue;
                    }

                    HashSet <UnityEngine.Object> seenObjects = new HashSet <UnityEngine.Object>();
                    this.toggleableAssets.Clear();
                    this.toggleableAssetLookup.Clear();

                    IEnumerable <AssetUtilities.AssetSearchResult> allAssets;
#pragma warning disable CS0618 // Type or member is obsolete
                    if (this.PrettyPath == null)
                    {
                        allAssets = AssetUtilities.GetAllAssetsOfTypeWithProgress(typeof(TElement), null);
                    }
                    else
                    {
                        allAssets = AssetUtilities.GetAllAssetsOfTypeWithProgress(typeof(TElement), "Assets/" + this.PrettyPath.TrimStart('/'));
                    }
#pragma warning restore CS0618 // Type or member is obsolete

                    int[] layers = this.LayerNames != null?this.LayerNames.Select(l => LayerMask.NameToLayer(l)).ToArray() : null;

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

                    foreach (var p in allAssets)
                    {
                        if (sw.Elapsed.TotalMilliseconds > this.MaxSearchDurationPrFrameInMS)
                        {
                            this.NumberOfResultsToSearch = p.NumberOfResults;
                            this.CurrentSearchingIndex   = p.CurrentIndex;

                            GUIHelper.RequestRepaint();
                            //this.SetToggleValues(startIndex);

                            yield return(null);

                            sw.Reset();
                            sw.Start();
                        }

                        var asset = p.Asset;

                        if (asset != null && seenObjects.Add(asset))
                        {
                            var go = asset as Component != null ? (asset as Component).gameObject : asset as GameObject == null ? null : asset as GameObject;

                            var assetName = go == null ? asset.name : go.name;

                            if (this.AssetNamePrefix != null && assetName.StartsWith(this.AssetNamePrefix, StringComparison.InvariantCultureIgnoreCase) == false)
                            {
                                continue;
                            }

                            if (this.AssetsFolderLocation != null)
                            {
                                var path = new DirectoryInfo(Path.GetDirectoryName(Application.dataPath + "/" + AssetDatabase.GetAssetPath(asset)));
                                if (this.AssetsFolderLocation.HasSubDirectory(path) == false)
                                {
                                    continue;
                                }
                            }

                            if (this.LayerNames != null && go == null || this.Tags != null && go == null)
                            {
                                continue;
                            }

                            if (go != null && this.Tags != null && !this.Tags.Contains(go.tag))
                            {
                                continue;
                            }

                            if (go != null && this.LayerNames != null && !layers.Contains(go.layer))
                            {
                                continue;
                            }

                            if (this.toggleableAssetLookup.ContainsKey(asset as TElement))
                            {
                                continue;
                            }

                            if (
                                this.StaticCustomIncludeMethod != null && !this.StaticCustomIncludeMethod(asset as TElement) ||
                                this.InstanceCustomIncludeMethod != null && !this.InstanceCustomIncludeMethod(this.Property.ParentValues[0], asset as TElement))
                            {
                                continue;
                            }

                            var toggleable = new ToggleableAsset(asset as TElement, this.AutoPopulate);

                            this.toggleableAssets.Add(toggleable);
                            this.toggleableAssetLookup.Add(asset as TElement, toggleable);
                        }
                    }

                    this.SetToggleValues();

                    this.IsPopulated = true;
                    GUIHelper.RequestRepaint();
                    yield return(null);
                }
            }
Exemple #46
0
 /// <summary>
 ///     Starts, or resumes, measuring elapsed time for an interval.
 /// </summary>
 public void Start()
 {
     _stopwatch.Start();
 }
Exemple #47
0
        public IElement LaunchBySelector(Selector selector, bool CheckRunning, TimeSpan timeout)
        {
            if (selector == null || selector.Count == 0)
            {
                return(null);
            }
            var f = selector.First();
            var p = f.Properties.Where(x => x.Name == "url").FirstOrDefault();

            if (p == null)
            {
                return(null);
            }
            var url = p.Value;

            if (string.IsNullOrEmpty(url))
            {
                return(null);
            }
            GenericTools.RunUI(() =>
            {
                var browser = Browser.GetBrowser(true, url);
                var doc     = browser.Document;
                if (url != doc.url)
                {
                    doc.url = url;
                }
                browser.Show();
                var sw = new System.Diagnostics.Stopwatch();
                sw.Start();
                while (sw.Elapsed < timeout)
                {
                    try
                    {
                        Log.Debug("pending complete, readyState: " + doc.readyState);
                        Thread.Sleep(100);
                        if (doc.readyState != "complete" && doc.readyState != "interactive")
                        {
                            break;
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            });

            var wbs = new SHDocVw.ShellWindows().Cast <SHDocVw.WebBrowser>().ToList();

            foreach (var w in wbs)
            {
                try
                {
                    var doc = (w.Document as MSHTML.HTMLDocument);
                    if (doc != null)
                    {
                        var wBrowser   = w as SHDocVw.WebBrowser;
                        var automation = Interfaces.AutomationUtil.getAutomation();
                        var _ele       = automation.FromHandle(new IntPtr(wBrowser.HWND));
                        if (_ele != null)
                        {
                            var ui     = new UIElement(_ele);
                            var window = ui.GetWindow();
                            if (window != null)
                            {
                                return(new UIElement(window));
                            }
                        }
                    }
                }
                catch (Exception)
                {
                }
            }
            return(null);
        }
        void OnAudioFilterRead(float[] data, int channels)
        {
                        #if UNITY_EDITOR
            if (!runEffect)
            {
                return;
            }
            stopwatch.Reset();
            stopwatch.Start();
                        #endif
            if (Filter == FilterState.Bypass)
            {
                return;
            }

            double[] input = new double[channels];
            for (var i = 0; i < data.Length; i = i + channels)
            {
                for (var c = 0; c < channels; c++)
                {
                    input[c]  = Math.Abs(data[i + c]) > 10e-8 ? data[i + c] : 0;
                    output[c] = 0;


                    for (var x = 0; x < passes; x++)
                    {
                        high[c] = input[c] - low[c] - damp * band[c];
                        band[c] = freq * high[c] + band[c] - ((0.1f - Drive) + 0.001f) * Math.Pow(band[c], 3);
                        low[c]  = freq * band[c] + low[c];
                    }

                    switch (Filter)
                    {
                    case FilterState.LowShelf:
                    case FilterState.LowPass:
                        output[c] = low[c];
                        break;

                    case FilterState.HighShelf:
                    case FilterState.HighPass:
                        output[c] = high[c];
                        break;

                    case FilterState.BandAdd:
                    case FilterState.BandPass:
                        output[c] = band[c];
                        break;
                    }

                    if (Filter == FilterState.HighShelf || Filter == FilterState.LowShelf || Filter == FilterState.BandAdd)
                    {
                        data[i + c] += (float)output[c] * AdditiveGain;
                    }
                    else
                    {
                        data[i + c] = (float)output[c];
                    }
                }
            }
                        #if UNITY_EDITOR
            stopwatch.Stop();
            runTime = Mathf.Round((float)stopwatch.Elapsed.TotalMilliseconds * 100) / 100;        // stopwatch.ElapsedMilliseconds;
                        #endif
        }
Exemple #49
0
        /// <summary>
        /// Downloads the speificed file to the specified location.
        /// </summary>
        /// <remarks>
        /// This method starts the download and returns.
        ///
        /// If the given <paramref name="p_strSavePath"/> already exists, an attempt will be made to
        /// resume the download. If the pre-existing file is not a partial download, or the download
        /// cannot be resumed, the file will be overwritten.
        /// </remarks>
        /// <param name="p_uriURL">The URL list of the file to download.</param>
        /// <param name="p_dicCookies">A list of cookies that should be sent in the request to download the file.</param>
        /// <param name="p_strSavePath">The path to which to save the file.
        /// If <paramref name="p_booUseDefaultFileName"/> is <c>false</c>, this value should be a complete
        /// path, including filename. If <paramref name="p_booUseDefaultFileName"/> is <c>true</c>,
        /// this value should be the directory in which to save the file.</param>
        /// <param name="p_booUseDefaultFileName">Whether to use the file name suggested by the server.</param>
        public void DownloadAsync(List <Uri> p_uriURL, Dictionary <string, string> p_dicCookies, string p_strSavePath, bool p_booUseDefaultFileName)
        {
            System.Diagnostics.Stopwatch swRetry = new System.Diagnostics.Stopwatch();
            int retries = 1;
            int i       = 0;
            Uri uriURL  = p_uriURL[i];

            ItemProgress = i;
            Status       = TaskStatus.Running;

            while ((retries <= m_intRetries) || (Status != TaskStatus.Paused) || (Status != TaskStatus.Queued))
            {
                if ((Status == TaskStatus.Paused) || (Status == TaskStatus.Queued))
                {
                    break;
                }
                else if (Status == TaskStatus.Retrying)
                {
                    Status = TaskStatus.Running;
                }

                m_fdrDownloader = new FileDownloader(uriURL, p_dicCookies, p_strSavePath, p_booUseDefaultFileName, m_intMaxConnections, m_intMinBlockSize, m_strUserAgent);
                m_steState      = new State(true, uriURL, p_dicCookies, p_strSavePath, p_booUseDefaultFileName);
                m_fdrDownloader.DownloadComplete += new EventHandler <CompletedDownloadEventArgs>(Downloader_DownloadComplete);
                ShowItemProgress        = false;
                OverallProgressMaximum  = (Int64)(m_fdrDownloader.FileSize / 1024);
                OverallProgressMinimum  = 0;
                OverallProgressStepSize = 1;
                OverallProgress         = (Int64)m_fdrDownloader.DownloadedByteCount;

                if (Status == TaskStatus.Cancelling)
                {
                    retries = m_intRetries;
                }
                else if (Status == TaskStatus.Paused)
                {
                    break;
                }

                if (!m_fdrDownloader.FileExists)
                {
                    if (m_fdrDownloader.FileNotFound)
                    {
                        swRetry.Start();
                        retries        = 1;
                        OverallMessage = String.Format("File not found on this server, retrying.. ({0}/{1})", retries, m_intRetries);
                        Status         = TaskStatus.Retrying;

                        if (i++ == p_uriURL.Count)
                        {
                            Status = TaskStatus.Error;
                            OnTaskEnded(String.Format("File does not exist: {0}", uriURL.ToString()), null);
                            return;
                        }

                        ItemProgress = i;
                        uriURL       = p_uriURL[i];

                        while ((swRetry.ElapsedMilliseconds < m_intRetryInterval) && swRetry.IsRunning)
                        {
                            if ((Status == TaskStatus.Cancelling) || (Status == TaskStatus.Paused) || (Status == TaskStatus.Queued))
                            {
                                break;
                            }
                        }

                        swRetry.Stop();
                        swRetry.Reset();
                    }
                    else if (m_fdrDownloader.ErrorCode == "666")
                    {
                        ErrorCode = m_fdrDownloader.ErrorCode;
                        ErrorInfo = m_fdrDownloader.ErrorInfo;
                        Status    = TaskStatus.Error;
                        OnTaskEnded(m_fdrDownloader.ErrorInfo, null);
                        return;
                    }
                    else if (++retries <= m_intRetries)
                    {
                        swRetry.Start();
                        OverallMessage = String.Format("Server busy or unavailable, retrying.. ({0}/{1})", retries, m_intRetries);
                        Status         = TaskStatus.Retrying;

                        if ((retries == m_intRetries) && (++i < p_uriURL.Count))
                        {
                            ItemProgress = i;
                            retries      = 1;
                            uriURL       = p_uriURL[i];
                        }

                        while ((swRetry.ElapsedMilliseconds < m_intRetryInterval) && swRetry.IsRunning)
                        {
                            if ((Status == TaskStatus.Cancelling) || (Status == TaskStatus.Paused) || (Status == TaskStatus.Queued))
                            {
                                break;
                            }
                        }

                        swRetry.Stop();
                        swRetry.Reset();
                    }
                    else
                    {
                        Status = TaskStatus.Error;
                        OnTaskEnded(String.Format("Error trying to get the file: {0}", uriURL.ToString()), null);
                        return;
                    }
                }
                else
                {
                    break;
                }
            }

            if (ModRepository.IsOffline)
            {
                this.Pause();
            }
            else if (Status == TaskStatus.Running)
            {
                m_fdrDownloader.StartDownload();
                m_tmrUpdater.Start();
            }
        }
Exemple #50
0
        public ChokePoints GetChokePoints(Point2D start, Point2D end, int frame)
        {
            var stopwatch = new System.Diagnostics.Stopwatch();

            stopwatch.Start();

            var chokePoints = new ChokePoints();

            chokePoints.Good = GeHighGroundChokePoints(start, end, frame);
            chokePoints.Bad  = GeHighGroundChokePoints(end, start, frame);

            //var path = PathFinder.GetGroundPath(start.X, start.Y, end.X, end.Y, frame);
            //float maxDistance = 1000;
            //var currentX = start.X;
            //var currentY = start.Y;
            //bool done = false;
            //while (!done)
            //{
            //    var goodChokePoint = ChokePointService.FindHighGroundChokePoint(path, maxDistance);
            //    var goodLength = maxDistance;
            //    if (goodChokePoint != null)
            //    {
            //        goodLength = PathFinder.GetGroundPath(currentX, currentY, goodChokePoint.X, goodChokePoint.Y, frame).Count;
            //    }

            //    var neutralChokePoint = ChokePointService.FindFlatChokePoint(path, maxDistance);
            //    var neutralLength = maxDistance;
            //    if (neutralChokePoint != null)
            //    {
            //        neutralLength = PathFinder.GetGroundPath(currentX, currentY, neutralChokePoint.X, neutralChokePoint.Y, frame).Count;
            //    }

            //    var badChokePoint = ChokePointService.FindLowGroundChokePoint(path, maxDistance);
            //    var badLength = maxDistance;
            //    if (badChokePoint != null)
            //    {
            //        badLength = PathFinder.GetGroundPath(currentX, currentY, badChokePoint.X, badChokePoint.Y, frame).Count;
            //    }

            //    if (goodLength < maxDistance && goodLength < neutralLength && goodLength < badLength)
            //    {
            //        currentX = goodChokePoint.X;
            //        currentY = goodChokePoint.Y;
            //        var entireChoke = ChokePointService.GetEntireChokePoint(goodChokePoint);
            //        var center = new Vector2(entireChoke.Sum(p => p.X) / entireChoke.Count(), entireChoke.Sum(p => p.Y) / entireChoke.Count());
            //        chokePoints.Good.Add(new ChokePoint { Center = center, Points = entireChoke });
            //    }
            //    else if (neutralLength < maxDistance && neutralLength < goodLength && neutralLength < badLength)
            //    {
            //        currentX = neutralChokePoint.X;
            //        currentY = neutralChokePoint.Y;
            //        var entireChoke = ChokePointService.GetEntireChokePoint(neutralChokePoint);
            //        var center = new Vector2(entireChoke.Sum(p => p.X) / entireChoke.Count(), entireChoke.Sum(p => p.Y) / entireChoke.Count());
            //        chokePoints.Neutral.Add(new ChokePoint { Center = center, Points = entireChoke });
            //    }
            //    else if (badLength < maxDistance && badLength < neutralLength && badLength < goodLength)
            //    {
            //        currentX = badChokePoint.X;
            //        currentY = badChokePoint.Y;
            //        var entireChoke = ChokePointService.GetEntireChokePoint(badChokePoint);
            //        var center = new Vector2(entireChoke.Sum(p => p.X) / entireChoke.Count(), entireChoke.Sum(p => p.Y) / entireChoke.Count());
            //        chokePoints.Bad.Add(new ChokePoint { Center = center, Points = entireChoke });
            //    }
            //    else
            //    {
            //        done = true;
            //    }

            //    path = PathFinder.GetGroundPath(currentX, currentY, end.X, end.Y, frame);
            //    if (path.Count > 10)
            //    {
            //        path = path.Skip(10).ToList();
            //    }
            //    else
            //    {
            //        done = true;
            //    }
            //}

            stopwatch.Stop();
            System.Console.WriteLine($"Generated Chokepoints in {stopwatch.ElapsedMilliseconds} ms");

            return(chokePoints);
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            //跳过匿名访问
            bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ||
                                     filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);

            if (skipAuthorization)
            {
                return;
            }

            if (filterContext.HttpContext.Session["AdminCredential"] == null)
            {
                if (!ApplicationContext.AppSetting.IS_NeedLogin)
                {
                    filterContext.HttpContext.Session["AdminCredential"] = new AdminCredential()
                    {
                        Name = "开发帐号",
                        ID   = 999,
                    };
                    return;
                }
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.Result = new JsonResult
                    {
                        Data                = new { Message = "登陆超时,请刷新页面重新登陆", Success = false },
                        ContentType         = null,
                        ContentEncoding     = null,
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                }
                else
                {
                    if (!string.IsNullOrEmpty(filterContext.HttpContext.Request.FilePath))
                    {
                        var returnUrl = HttpUtility.UrlEncode(filterContext.HttpContext.Request.Url.AbsoluteUri);
                        filterContext.Result = new RedirectResult("/Login/Index?returnUrl=" + returnUrl);
                    }
                    else
                    {
                        filterContext.Result = new RedirectResult("/Login/");
                    }
                }
            }
            else
            {
                var controllerName = (filterContext.RouteData.Values["controller"]).ToString().ToLower();
                var actionName     = (filterContext.RouteData.Values["action"]).ToString().ToLower();

                var LoginUser = (AdminCredential)filterContext.HttpContext.Session["AdminCredential"];
                if (LoginUser.ID == 999)
                {
                    return;
                }
                string menuid     = filterContext.HttpContext.Request.QueryString["menuid"];
                bool   ispageauth = false;
                var    mid        = Convert.ToInt32(menuid);
                string CacheKey   = controllerName + actionName + mid;
                ispageauth = (bool)CacheHelper.Single.Get(CacheKey, 0, () =>
                {
                    if (OperationConfigService.Instance.ValidControllerNameEqMenuID(mid, controllerName, actionName, out mid))
                    {
                        var menulist = OperationConfigService.Instance.GetAccessMenus(LoginUser.Roles).Data;
                        foreach (var menu in menulist)
                        {
                            if ((menu.ChildMenuList != null && menu.ChildMenuList.Any(e => e.ID == mid)) || menu.ID == mid)
                            {
                                ispageauth = true;
                            }
                        }
                        if (mid == -1)
                        {
                            ispageauth = true;
                        }
                    }
                    return(ispageauth);
                });
                if (!ispageauth)
                {
                    filterContext.Result = new RedirectResult("/PageAuth.html");
                }
            }
            sw.Stop();
            ApplicationContext.Log.Debug("PageAuthAttribute", sw.ElapsedMilliseconds.ToString());
        }
Exemple #52
0
 public void OnMouseDown(int tileX, int tileY)
 {
     clickStopwatch.Reset();
     clickStopwatch.Start();
     tileDownPoint = new Point(tileX, tileY);
 }
Exemple #53
0
        public static IEElement[] GetElementsWithuiSelector(IESelector selector, IElement fromElement = null, int maxresults = 1)
        {
            IEElement iefromElement = fromElement as IEElement;
            Browser   browser;

            if (iefromElement != null)
            {
                browser = iefromElement.Browser;
            }
            else
            {
                browser = Browser.GetBrowser();
            }
            if (browser == null)
            {
                Log.Warning("Failed locating an Internet Explore instance");
                return(new IEElement[] { });
            }

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

            sw.Start();

            IEElement _fromElement = fromElement as IEElement;
            var       selectors    = selector.Where(x => x.Enabled == true && x.Selector == null).ToList();

            var current = new List <IEElement>();

            IEElement[] result = null;

            int startIndex = 1;

            if (iefromElement != null)
            {
                startIndex = 0;
                current.Add(iefromElement);
            }
            else
            {
                MSHTML.IHTMLElement startfrom = null;
                startfrom = browser.Document.documentElement;
                current.Add(new IEElement(browser, startfrom));
            }
            for (var i = startIndex; i < selectors.Count; i++)
            {
                var s        = new IESelectorItem(selectors[i]);
                var elements = new List <IEElement>();
                elements.AddRange(current);
                current.Clear();
                int failcounter = 0;
                do
                {
                    foreach (var _element in elements)
                    {
                        MSHTML.IHTMLElement[] matches;
                        if (frameTags.Contains(_element.TagName.ToUpper()))
                        {
                            if (s.tagName.ToUpper() == "HTML")
                            {
                                i++; s = new IESelectorItem(selectors[i]);
                            }
                            var _f = _element.RawElement as MSHTML.HTMLFrameElement;
                            MSHTML.DispHTMLDocument doc = (MSHTML.DispHTMLDocument)((SHDocVw.IWebBrowser2)_f).Document;
                            var _doc = doc.documentElement as MSHTML.IHTMLElement;
                            matches = ((IESelectorItem)s).matches(_doc);

                            browser.elementx     += _f.offsetLeft;
                            browser.elementy     += _f.offsetTop;
                            browser.frameoffsetx += _f.offsetLeft;
                            browser.frameoffsety += _f.offsetTop;
                        }
                        else
                        {
                            matches = ((IESelectorItem)s).matches(_element.RawElement);
                        }
                        var uimatches = new List <IEElement>();
                        foreach (var m in matches)
                        {
                            var ui = new IEElement(browser, m);
                            uimatches.Add(ui);
                        }
                        current.AddRange(uimatches.ToArray());
                        Log.Selector("add " + uimatches.Count + " matches to current");
                    }
                    if (current.Count == 0)
                    {
                        ++failcounter;
                        string message = string.Format("Failer # " + failcounter + " finding any hits for selector # " + i + " {0:mm\\:ss\\.fff}", sw.Elapsed) + "\n";
                        message += "lookin for \n" + s.ToString() + "\n";
                        foreach (var _element in elements)
                        {
                            MSHTML.IHTMLElementCollection children = (MSHTML.IHTMLElementCollection)_element.RawElement.children;
                            foreach (MSHTML.IHTMLElement elementNode in children)
                            {
                                var ui = new IEElement(browser, elementNode);
                                message += ui.ToString() + "\n";
                            }
                            var matches = ((IESelectorItem)s).matches(_element.RawElement);
                        }
                        Log.Selector(message);
                    }
                    else
                    {
                        Log.Selector(string.Format("Found " + current.Count + " hits for selector # " + i + " {0:mm\\:ss\\.fff}", sw.Elapsed));
                    }
                } while (failcounter < 2 && current.Count == 0);

                if (i == (selectors.Count - 1))
                {
                    result = current.ToArray();
                }
                if (current.Count == 0 && Config.local.log_selector)
                {
                    var message = "needed to find " + Environment.NewLine + selectors[i].ToString() + Environment.NewLine + "but found only: " + Environment.NewLine;
                    foreach (var element in elements)
                    {
                        MSHTML.IHTMLElementCollection children = (MSHTML.IHTMLElementCollection)element.RawElement.children;
                        foreach (MSHTML.IHTMLElement c in children)
                        {
                            try
                            {
                                // message += automationutil.getSelector(c, (i == selectors.Count - 1)) + Environment.NewLine;
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                    Log.Selector(message);
                    return(new IEElement[] { });
                }
            }
            if (result == null)
            {
                return new IEElement[] { }
            }
            ;
            Log.Selector(string.Format("GetElementsWithuiSelector::end {0:mm\\:ss\\.fff}", sw.Elapsed));
            return(result);
        }
    }
        private void button1_Click(object sender, EventArgs e)
        {
            lbl();

            p = new perceptron3(100, 70, 2);

            btmpList.Add(new Bitmap(интелл_системы_нейросеть_попытка2.Properties.Resources.a1));
            btmpList.Add(new Bitmap(интелл_системы_нейросеть_попытка2.Properties.Resources.a2));
            btmpList.Add(new Bitmap(интелл_системы_нейросеть_попытка2.Properties.Resources.a3));
            btmpList.Add(new Bitmap(интелл_системы_нейросеть_попытка2.Properties.Resources.a4));
            btmpList.Add(new Bitmap(интелл_системы_нейросеть_попытка2.Properties.Resources.a5));
            btmpList.Add(new Bitmap(интелл_системы_нейросеть_попытка2.Properties.Resources.x1));
            btmpList.Add(new Bitmap(интелл_системы_нейросеть_попытка2.Properties.Resources.x2));
            btmpList.Add(new Bitmap(интелл_системы_нейросеть_попытка2.Properties.Resources.x3));
            btmpList.Add(new Bitmap(интелл_системы_нейросеть_попытка2.Properties.Resources.x4));
            btmpList.Add(new Bitmap(интелл_системы_нейросеть_попытка2.Properties.Resources.x5));
            btmpList.Add(new Bitmap(интелл_системы_нейросеть_попытка2.Properties.Resources._21));
            btmpList.Add(new Bitmap(интелл_системы_нейросеть_попытка2.Properties.Resources._22));
            btmpList.Add(new Bitmap(интелл_системы_нейросеть_попытка2.Properties.Resources._23));
            btmpList.Add(new Bitmap(интелл_системы_нейросеть_попытка2.Properties.Resources._24));
            btmpList.Add(new Bitmap(интелл_системы_нейросеть_попытка2.Properties.Resources._25));

            for (int n = 0; n < btmpList.Count; n++)
            {
                dataList.Add(new List <double>());
                for (int i = 0; i < btmpList[n].Height; i++)
                {
                    for (int j = 0; j < btmpList[n].Width; j++)
                    {
                        if (btmpList[n].GetPixel(i, j).R > 127)
                        {
                            dataList[n].Add(0);
                        }
                        else
                        {
                            dataList[n].Add(1);
                        }
                    }
                }
            }

            for (int i = 0; i < btmpList.Count; i++)
            {
                standart.Add(new List <double>());
                if (i < 5)
                {
                    standart[i].Add(0);
                    standart[i].Add(1);
                }
                else if (i > 4 && i < 10)
                {
                    standart[i].Add(1);
                    standart[i].Add(0);
                }
                else
                {
                    standart[i].Add(1);
                    standart[i].Add(1);
                }
            }
            double sum = 1.0;

            System.Diagnostics.Stopwatch spw = new System.Diagnostics.Stopwatch();
            spw.Start();
            while (sum > 0.1)
            {
                sum = 0.0;
                for (int i = 0; i < 100; i++)
                {
                    number = rnd.Next(15);
                    p.inData(dataList[number]);
                    p.train(standart[number]);
                }

                for (int i = 0; i < btmpList.Count; i++)
                {
                    p.inData(dataList[i]);
                    result = p.work();
                    for (int j = 0; j < standart[i].Count; j++)
                    {
                        sum += (0.5 * Math.Pow((result[j] - standart[i][j]), 2));
                    }
                }
            }
            spw.Stop();
            label4.Text     = "Сеть обучилась за " + (spw.ElapsedMilliseconds / 1000).ToString() + " сек. Ошибка -   " + sum.ToString();
            button6.Enabled = true;
        }
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            if (sender == null)
            {
                return;
            }
            if (((MenuItem)sender).Uid == null)
            {
                return;
            }
            string clip = ClipBoardHelper.GetClipBoard_UnicodeText();

            if (!string.IsNullOrWhiteSpace((string)(((MenuItem)sender).ToolTip)))
            {
                clip = (string)(((MenuItem)sender).ToolTip);
            }
            StringBuilder sb = new StringBuilder();

            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Reset();
            sw.Start();
            switch (((MenuItem)sender).Uid)
            {
            case "1":
                this.Visibility = this.Visibility == Visibility.Visible ? Visibility.Hidden : Visibility.Visible;
                break;

            case "a1":
                if (App.Settings.RecognitionEncoding)
                {
                    int encodingtype = EncodingAnalyzer.Analyze(clip);
                    if (encodingtype == 0 || encodingtype == 1)
                    {
                        if (MessageBox.Show(this, "編碼似乎已是Big5,繼續轉換?", "警告", MessageBoxButton.YesNo) == MessageBoxResult.No)
                        {
                            return;
                        }
                    }
                }
                clip = ConvertHelper.Convert(clip, new Encoding[] { Encoding.GetEncoding("GBK"), Encoding.GetEncoding("BIG5") }, 1);
                break;

            case "a2":
                if (App.Settings.RecognitionEncoding)
                {
                    int encodingtype = EncodingAnalyzer.Analyze(clip);
                    if (encodingtype == 2 || encodingtype == 3)
                    {
                        if (MessageBox.Show(this, "編碼似乎已是GBK,繼續轉換?", "警告", MessageBoxButton.YesNo) == MessageBoxResult.No)
                        {
                            return;
                        }
                    }
                }
                clip = ConvertHelper.Convert(clip, new Encoding[] { Encoding.GetEncoding("BIG5"), Encoding.GetEncoding("GBK") }, 2);
                break;

            case "a3":
                clip = ConvertHelper.Convert(clip, 1);
                break;

            case "a4":
                clip = ConvertHelper.Convert(clip, 2);
                break;

            case "b1":
                Window_DialogHost window_File_FileNameConverter = new Window_DialogHost(Enums.Enum_Mode.Mode.File_FileName);
                window_File_FileNameConverter.Show();
                break;

            case "b2":
                Window_DialogHost window_ClipBoard_Converter = new Window_DialogHost(Enums.Enum_Mode.Mode.ClipBoard);
                window_ClipBoard_Converter.Show();
                break;

            case "c1":
                Window_DialogHost Window_DialogHost = new Window_DialogHost(Enums.Enum_Mode.Mode.AutioTag, Format.ID3);
                Window_DialogHost.Show();
                break;

            case "c2":
                Window_DialogHost Window_DialogHost2 = new Window_DialogHost(Enums.Enum_Mode.Mode.AutioTag, Format.APE);
                Window_DialogHost2.Show();
                break;

            case "c3":
                Window_DialogHost Window_DialogHost3 = new Window_DialogHost(Enums.Enum_Mode.Mode.AutioTag, Format.OGG);
                Window_DialogHost3.Show();
                break;

            case "za1":
                foreach (char c in clip)
                {
                    if ((' ' <= c && c <= '~') || (c == '\r') || (c == '\n'))
                    {
                        if (c == '&')
                        {
                            sb.Append("&amp;");
                        }
                        else if (c == '<')
                        {
                            sb.Append("&lt;");
                        }
                        else if (c == '>')
                        {
                            sb.Append("&gt;");
                        }
                        else
                        {
                            sb.Append(c.ToString());
                        }
                    }
                    else
                    {
                        sb.Append("&#");
                        sb.Append(Convert.ToInt32(c));
                        sb.Append(";");
                    }
                }
                clip = sb.ToString();
                break;

            case "za2":
                foreach (char c in clip)
                {
                    if ((' ' <= c && c <= '~') || (c == '\r') || (c == '\n'))
                    {
                        if (c == '&')
                        {
                            sb.Append("&amp;");
                        }
                        else if (c == '<')
                        {
                            sb.Append("&lt;");
                        }
                        else if (c == '>')
                        {
                            sb.Append("&gt;");
                        }
                        else
                        {
                            sb.Append(c.ToString());
                        }
                    }
                    else
                    {
                        sb.Append("&#x");
                        sb.Append(Convert.ToInt32(c).ToString("X"));
                        sb.Append(";");
                    }
                }
                clip = sb.ToString();
                break;

            case "za3":
                clip.Replace("&amp;", "&");
                clip.Replace("&lt;", "<");
                clip.Replace("&gt;", ">");
                //以;將文字拆成陣列
                string[] tmp = clip.Split(';');
                //檢查最後一個字元是否為【;】,因為有【英文】、【阿拉伯數字】、【&#XXXX;】
                //若最後一個要處理的字並非HTML UNICODE則不進行處理
                bool Process_last = clip.Substring(clip.Length - 1, 1).Equals(";");
                //Debug.WriteLine(tmp.Length + "");
                for (int i = 0; i < tmp.Length; i++)
                {
                    //以&#將文字拆成陣列
                    string[] tmp2 = tmp[i].Split(new string[] { "&#" }, StringSplitOptions.RemoveEmptyEntries);
                    if (tmp2.Length == 1)
                    {
                        //如果長度為1則試圖轉換UNICODE回字符,若失敗則使用原本的字元
                        if (i != tmp.Length - 1)
                        {
                            try
                            {
                                if (tmp2[0].StartsWith("x"))
                                {
                                    sb.Append(Convert.ToChar(Convert.ToInt32(tmp2[0].Substring(1, tmp2[0].Length - 1), 16)).ToString());
                                }
                                else
                                {
                                    sb.Append(Convert.ToChar(Convert.ToInt32(int.Parse(tmp2[0]))).ToString());
                                }
                            }
                            catch
                            {
                                sb.Append(tmp2[0]);
                            }
                        }
                        else
                        {
                            sb.Append(tmp2[0]);
                        }
                    }
                    if (tmp2.Length == 2)
                    {
                        //若長度為2,則第一項不處理,只處理第二項即可
                        sb.Append(tmp2[0]);
                        var g = Convert.ToInt32(tmp2[1].Substring(1, tmp2[1].Length - 1), 16);
                        if (tmp2[1].StartsWith("x"))
                        {
                            sb.Append(Convert.ToChar(Convert.ToInt32(tmp2[1].Substring(1, tmp2[1].Length - 1), 16)).ToString());
                        }
                        else
                        {
                            sb.Append(Convert.ToChar(Convert.ToInt32(tmp2[1])).ToString());
                        }
                    }
                }
                clip = sb.ToString();
                break;

            case "zb1":
                //Unicode>GBK
                clip = Encoding.Default.GetString(Encoding.GetEncoding("GBK").GetBytes(clip));
                break;

            case "zb2":
                clip = Encoding.Default.GetString(Encoding.GetEncoding("BIG5").GetBytes(clip));
                break;

            case "zb3":
                clip = Encoding.Default.GetString(Encoding.GetEncoding("Shift-JIS").GetBytes(clip));
                break;

            case "zb4":
                //GBK>Unicode
                clip = Encoding.GetEncoding("GBK").GetString(Encoding.Default.GetBytes(clip));
                break;

            case "zb5":
                clip = Encoding.GetEncoding("BIG5").GetString(Encoding.Default.GetBytes(clip));
                break;

            case "zb6":
                clip = Encoding.GetEncoding("Shift-JIS").GetString(Encoding.Default.GetBytes(clip));
                break;

            case "zc1":
                //Shift-JIS>GBK
                clip = Encoding.GetEncoding("shift_jis").GetString(Encoding.GetEncoding("GBK").GetBytes(clip));
                break;

            case "zc2":
                clip = Encoding.GetEncoding("shift_jis").GetString(Encoding.GetEncoding("BIG5").GetBytes(clip));
                break;

            case "zc3":
                clip = Encoding.GetEncoding("GBK").GetString(Encoding.GetEncoding("shift_jis").GetBytes(clip));
                break;

            case "zc4":
                clip = Encoding.GetEncoding("BIG5").GetString(Encoding.GetEncoding("shift_jis").GetBytes(clip));
                break;

            case "zd1":
                //hz-gb-2312>GBK
                clip = Encoding.GetEncoding("hz-gb-2312").GetString(Encoding.GetEncoding("GBK").GetBytes(clip));
                break;

            case "zd2":
                clip = Encoding.GetEncoding("hz-gb-2312").GetString(Encoding.GetEncoding("BIG5").GetBytes(clip));
                break;

            case "zd3":
                clip = Encoding.GetEncoding("GBK").GetString(Encoding.GetEncoding("hz-gb-2312").GetBytes(clip));
                break;

            case "zd4":
                clip = Encoding.GetEncoding("BIG5").GetString(Encoding.GetEncoding("hz-gb-2312").GetBytes(clip));
                break;

            case "ze1":
                clip = Moudle.ConvertHelper.ConvertSymbol(clip, 0);
                break;

            case "ze2":
                clip = Moudle.ConvertHelper.ConvertSymbol(clip, 1);
                break;
            }
            ClipBoardHelper.SetClipBoard_UnicodeText(clip);
            sw.Stop();
            //顯示提示
            switch (((MenuItem)sender).Uid)
            {
            case "1":
            case "b1":
            case "b2":
            case "c1":
            case "c2":
            case "c3":
                break;

            default:
                if (App.Settings.Prompt && !(((MenuItem)sender).Visibility == Visibility.Hidden && (App.Settings.HotKey.AutoCopy || App.Settings.HotKey.AutoPaste)))
                {
                    ContextMenu NotifyIconMenu = (ContextMenu)this.FindResource("NotifyIconMenu");
                    string      ItemInfo       = ((MenuItem)GetByUid(NotifyIconMenu, ((MenuItem)sender).Uid)).Header.ToString();
                    new Toast(string.Format("轉換完成\r\n耗時:{0} ms", sw.ElapsedMilliseconds)).Show();
                }
                break;
            }
        }
        public static void Tick()
        {
            if (Plugin.EditMode != EditModes.Design && Plugin.UpdateMode != UpdateModes.Break)
            {
                string msgN = null;
                while (_messagesBuffer.Dequeue(out msgN))
                {
                    lock (_lockObject)
                    {
                        _messages.Add(msgN);
                    }
                }

                lock (_lockObject) {
                    Debug.Check(ProcessMessageHandler != null);

                    if (_currentIndex < _messages.Count)
                    {
                        if (_currentIndex < _messages.Count)
                        {
                            _stopwatch.Reset();
                            _stopwatch.Start();

                            while (_currentIndex < _messages.Count)
                            {
                                string msg = _messages[_currentIndex];
                                _currentIndex++;

                                if (msg.IndexOf("[frame]") == 10)
                                {
                                    int frame = (int.Parse(msg.Substring(17)));
                                    _messsageFrameStartIndex[frame] = _messages.Count - 1;
                                }

                                ProcessMessageHandler(msg);

                                long ms = _stopwatch.ElapsedMilliseconds;

                                if (ms >= kTimeThreshold)
                                {
                                    break;
                                }
                            }

                            if (Plugin.EditMode == EditModes.Connect && _limitMessageCount)
                            {
                                if (_messages.Count > 2 * _maxMessageCount)
                                {
                                    int count = _messages.Count - _maxMessageCount;

                                    if (count > _currentIndex)
                                    {
                                        count = _currentIndex;
                                    }

                                    AppendLog(Workspace.Current.FileName, count);

                                    _savingCount  += count;
                                    _currentIndex -= count;

                                    // update messages
                                    _messages.RemoveRange(0, count);

                                    // update message indexes
                                    updateMessageIndexes();
                                }
                            }

                            _stopwatch.Stop();
                        }
                    }
                }
            }
        }
Exemple #57
0
        public void RecalculateResiudes(TDRParams param, Action <TDRParams, ConcurrentStack <TArchivesValue>, List <TI_ChanelType>, bool> getArchivesAndCalculateResiudesFromMonthStartAction)
        {
            if (getArchivesAndCalculateResiudesFromMonthStartAction == null)
            {
                return;
            }

#if DEBUG
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();
#endif

            if (_tiForRecalculateResiudes != null && _tiForRecalculateResiudes.Count > 0)
            {
                //Перерасчет ТИ по которым небыло найдено остатков в предыдущем дне
                var tiArray = _tiForRecalculateResiudes
                              .Select(t => new TI_ChanelType
                {
                    TI_ID           = t.TI_Ch_ID.TI_ID,
                    ChannelType     = t.TI_Ch_ID.ChannelType,
                    ClosedPeriod_ID = t.TI_Ch_ID.ClosedPeriod_ID,
                    DataSourceType  = t.DataSourceType,
                    IsCA            = t.TI_Ch_ID.IsCA,
                    MsTimeZone      = t.TI_Ch_ID.MsTimeZone,
                    TP_ID           = t.TI_Ch_ID.TP_ID,
                })
                              .ToList();
                var archivesValue30OrHour = new ConcurrentStack <TArchivesValue>();

                //Дата/время с которого пересчитываем
                var dtStartMonthClient = param.DtServerStart.AddMonths(-MonthForRecalculateResidues);
                dtStartMonthClient = new DateTime(dtStartMonthClient.Year, dtStartMonthClient.Month, 1);

                var newParam = new TDRParams(param.IsCoeffEnabled, param.isCAEnabled, param.OvMode, param.isCAReverse,
                                             enumTimeDiscreteType.DBHalfHours, param.UnitDigit,
                                             param.IsPower, param.TIs, dtStartMonthClient.ClientToServer(param.ClientTimeZoneId),
                                             param.DtServerStart.AddMinutes(-30),
                                             MyListConverters.GetIntervalTimeList(dtStartMonthClient,
                                                                                  param.DtServerStart.AddMinutes(-30).ServerToClient(param.ClientTimeZoneId),
                                                                                  enumTimeDiscreteType.DBHalfHours, param.ClientTimeZoneId), param.ClientTimeZoneId,
                                             param.IsValidateOtherDataSource, param.IsReadCalculatedValues, param.IsReadAbsentChannel,
                                             param.RoundData)
                {
                    IsNotRecalculateResiudes = true
                };

                //Запрос данных с начала месяца
                getArchivesAndCalculateResiudesFromMonthStartAction(newParam, archivesValue30OrHour, tiArray, false);

#if DEBUG
                sw.Stop();
                Console.WriteLine("Запрос архивов для перерасчета - > ПУ: {0} шт, время: {1} млс", tiArray.Count, sw.ElapsedMilliseconds);
                sw.Restart();
#endif

                //if (newParam.RecalculatorResiudes != null && newParam.RecalculatorResiudes.TiForResaveResiudes.Count > 0)
                //{
                //TiForResaveResiudes.PushRange(newParam.RecalculatorResiudes.TiForResaveResiudes.ToArray());
                //}

                var prev24HEventDate = param.DtServerStart.AddMinutes(-30);

                Dictionary <int, List <DBResiduesTable> > resiudesDict = null;
                if (newParam.RecalculatorResiudes != null &&
                    newParam.RecalculatorResiudes.TiForResaveResiudes != null)
                {
                    resiudesDict = newParam.RecalculatorResiudes.TiForResaveResiudes
                                   .GroupBy(r => r.TI_ID)
                                   .ToDictionary(k => k.Key, v => v.ToList());
                }

                //Дорасчитываем остатки по ТИ у которых их нет в предыдущих сутках
                foreach (var av in _tiForRecalculateResiudes)
                {
                    List <DBResiduesTable> resiudesTi;
                    DBResiduesTable        prevDayResiude = null;
                    if (resiudesDict != null && resiudesDict.TryGetValue(av.TI_Ch_ID.TI_ID, out resiudesTi) && resiudesTi != null)
                    {
                        prevDayResiude = resiudesTi
                                         .FirstOrDefault(r => r.ChannelType == av.TI_Ch_ID.ChannelType &&
                                                         r.EventDate < prev24HEventDate && //Коллеция идет от Stack поэтому дата, время идет по убывающей
                                                         r.DataSourceType == av.DataSourceType);
                    }

                    CalculateResiudes(av, prevDayResiude, true, param.UseLossesCoefficient, isNotRecalculateResiudes: param.IsNotRecalculateResiudes);
                }

#if DEBUG
                sw.Stop();
                Console.WriteLine("Расчет остатков - > {0} млс", sw.ElapsedMilliseconds);
                sw.Restart();
#endif
            }

            //Запускаем сохранение остатков и выходим
            if (TiForResaveResiudes.Count > 0)
            {
                Task.Factory.StartNew(() => SaveResiudes(TiForResaveResiudes, param.HalfHoursShiftClientFromServer, param.IsReadCalculatedValues));
            }

#if DEBUG
            sw.Stop();
            Console.WriteLine("Сохранение остатков - > {0} млс", sw.ElapsedMilliseconds);
#endif
        }
Exemple #58
0
        public void ExecuteScript(string data, bool dataIsFile)
        {
            Core.Client.EngineBusy = true;


            try
            {
                CurrentStatus = EngineStatus.Running;

                //create stopwatch for metrics tracking
                sw = new System.Diagnostics.Stopwatch();
                sw.Start();

                //log starting
                ReportProgress("Bot Engine Started: " + DateTime.Now.ToString());

                //get automation script
                Core.Script.Script automationScript;
                if (dataIsFile)
                {
                    ReportProgress("Deserializing File");
                    engineLogger.Information("Script Path: " + data);
                    FileName         = data;
                    automationScript = Core.Script.Script.DeserializeFile(data);
                }
                else
                {
                    ReportProgress("Deserializing XML");
                    automationScript = Core.Script.Script.DeserializeXML(data);
                }

                if (serverSettings.ServerConnectionEnabled && taskModel == null)
                {
                    taskModel = HttpServerClient.AddTask(data);
                }
                else if (serverSettings.ServerConnectionEnabled && taskModel != null)
                {
                    taskModel = HttpServerClient.UpdateTask(taskModel.TaskID, "Running", "Running Server Assignment");
                }

                //track variables and app instances
                ReportProgress("Creating Variable List");


                //set variables if they were passed in
                if (VariableList != null)
                {
                    foreach (var var in VariableList)
                    {
                        var variableFound = automationScript.Variables.Where(f => f.VariableName == var.VariableName).FirstOrDefault();

                        if (variableFound != null)
                        {
                            variableFound.VariableValue = var.VariableValue;
                        }
                    }
                }


                VariableList = automationScript.Variables;


                ReportProgress("Creating App Instance Tracking List");
                //create app instances and merge in global instances
                this.AppInstances = new Dictionary <string, object>();
                var GlobalInstances = GlobalAppInstances.GetInstances();
                foreach (var instance in GlobalInstances)
                {
                    this.AppInstances.Add(instance.Key, instance.Value);
                }


                //execute commands
                foreach (var executionCommand in automationScript.Commands)
                {
                    if (IsCancellationPending)
                    {
                        ReportProgress("Cancelling Script");
                        ScriptFinished(ScriptFinishedEventArgs.ScriptFinishedResult.Cancelled);
                        return;
                    }

                    ExecuteCommand(executionCommand);
                }

                if (IsCancellationPending)
                {
                    //mark cancelled - handles when cancelling and user defines 1 parent command or else it will show successful
                    ScriptFinished(ScriptFinishedEventArgs.ScriptFinishedResult.Cancelled);
                }
                else
                {
                    //mark finished
                    ScriptFinished(ScriptFinishedEventArgs.ScriptFinishedResult.Successful);
                }
            }
            catch (Exception ex)
            {
                ScriptFinished(ScriptFinishedEventArgs.ScriptFinishedResult.Error, ex.ToString());
            }
        }
Exemple #59
0
        // todo: restructure this function since it currently changes the state of the object after running
        public GameResults Run() // yield, async, parallel, task.run() ?
        {
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

            if (rules.LoggingSettings.logTime)
            {
                watch.Start();
            }

            List <Player> activePlayers = null;

            // allow each player to make a move, checking for end state or limit
            for (CurrentBoard.TurnNumber = 1; CurrentBoard.TurnNumber <= rules.MaxPhysicalTurns; CurrentBoard.TurnNumber++)
            {
                // have the player decide on a move
                Move playersMove = PlayersTurn.chooseMove(this);

                // automatic forfeit if player is unable to make a move
                if (playersMove == null)
                {
                    rules.PlayerOrder.Remove(PlayersTurn);
                }
                else
                {
                    CurrentBoard.applyMove(playersMove, rules); // apply the move

                    // add the move to the current game's seqence of moves
                    MoveSequence.Add(CurrentBoard.TurnNumber, playersMove);
                }


                if (rules.LoggingSettings.showMovePerTurn)
                {
                    Console.WriteLine($"#{CurrentBoard.TurnNumber} {playersMove}");
                }

                if (rules.LoggingSettings.showStatePerTurn)
                {
                    if (rules.LoggingSettings.showHiddenPieces)
                    {
                        Console.WriteLine(CurrentBoard.ToAsciiLayout());
                    }
                    else
                    {
                        Console.WriteLine(CurrentBoard.ToAsciiLayout(PlayersTurn));  // shows what that player sees
                    }
                }


                if (rules.LoggingSettings.pausePerMove)
                {
                    Console.WriteLine("Press <enter> to continue...");
                    Console.ReadLine();
                }

                // check if after the move if any players are remaning
                activePlayers = CurrentBoard.TerminalStateCheck(rules);

                if (activePlayers.Count <= 1) // no win scenario is possible, so activePlayers might be 0
                {
                    break;
                }
            }

            watch.Stop();

            if (rules.LoggingSettings.listMoveSeqenceAtEnd)
            {
                Console.WriteLine("Move Sequence:");
                foreach (KeyValuePair <int, Move> sequence in MoveSequence)
                {
                    Console.WriteLine($"Turn {sequence.Key} = {sequence.Value?.ToString() ?? "no move available"}");
                }
            }

            //if (CurrentBoard.TurnNumber < 2)
            //    return null;


            return(new GameResults()
            {
                turnsElapsed = CurrentBoard.TurnNumber,
                Winners = activePlayers,
                timeElapsed = watch.Elapsed,
            });
        }
Exemple #60
0
        static void Main()
        {
            #region d3d initialization
            // create winform
            Form1 form = new Form1();
            form.Text   = "D3D debug";
            form.Width  = 800;
            form.Height = 600;

            // device & swapChain
            Device    device;
            SwapChain swapChain;

            // create device & swapChain
            Device.CreateWithSwapChain(
                SharpDX.Direct3D.DriverType.Hardware,
                DeviceCreationFlags.None,
                new[]
            {
                SharpDX.Direct3D.FeatureLevel.Level_11_1,
                SharpDX.Direct3D.FeatureLevel.Level_11_0
            },
                new SwapChainDescription()
            {
                ModeDescription   = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                SampleDescription = new SampleDescription(1, 0),
                Usage             = SharpDX.DXGI.Usage.BackBuffer | SharpDX.DXGI.Usage.RenderTargetOutput,
                BufferCount       = 1,
                Flags             = SwapChainFlags.None,
                IsWindowed        = true,
                OutputHandle      = form.Handle,
                SwapEffect        = SwapEffect.Discard,
            },
                out device, out swapChain
                );

            // Create references to backBuffer and renderTargetView
            var backBuffer       = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);
            var renderTargetView = new RenderTargetView(device, backBuffer);
            #endregion

            // Setup object debug names
            device.DebugName           = "The Device";
            swapChain.DebugName        = "The SwapChain";
            backBuffer.DebugName       = "The Backbuffer";
            renderTargetView.DebugName = "The RenderTargetView";

            #region render loop

            // Create Clock and FPS counters
            var clock          = new System.Diagnostics.Stopwatch();
            var clockFrequency = (double)System.Diagnostics.Stopwatch.Frequency;
            clock.Start();
            var deltaTime = 0.0;
            var fpsTimer  = new System.Diagnostics.Stopwatch();
            fpsTimer.Start();
            var fps       = 0.0;
            int fpsFrames = 0;

            RenderLoop.Run(form, () =>
            {
                // Time in seconds
                var totalSeconds = clock.ElapsedTicks / clockFrequency;

                #region FPS and title update
                fpsFrames++;
                if (fpsTimer.ElapsedMilliseconds > 1000)
                {
                    fps = 1000.0 * fpsFrames / fpsTimer.ElapsedMilliseconds;

                    // Update window title with FPS once every second
                    form.Text = string.Format("D3D debug - FPS: {0:F2} ({1:F2}ms/frame)", fps, (float)fpsTimer.ElapsedMilliseconds / fpsFrames);

                    // Restart the FPS counter
                    fpsTimer.Reset();
                    fpsTimer.Start();
                    fpsFrames = 0;
                }
                #endregion

                // clearcolor
                var lerpColor = SharpDX.Color.Lerp(Color.LightBlue, Color.DarkBlue, (float)(Math.Sin(totalSeconds) / 2.0 + 0.5));

                device.ImmediateContext.ClearRenderTargetView(renderTargetView, lerpColor);

                // rendering commands

                // Present the frams
                System.Diagnostics.Debug.Write(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects());
                // This is a deliberate invalid call to Present
                // swapChain.Present(0, PresentFlags.RestrictToOutput);
                swapChain.Present(0, PresentFlags.None);

                // Determine the time it took to render the frame
                deltaTime = (clock.ElapsedTicks / clockFrequency) - totalSeconds;
            });
            #endregion

            #region d3d cleanup
            // release
            renderTargetView.Dispose();
            backBuffer.Dispose();
            device.Dispose();
            swapChain.Dispose();
            #endregion
        }