Beispiel #1
0
        public static void RunSpawningThreads()
        {
            ConsoleEx.WriteLnThreaded("spawning threads...");

            InstrumentedOperation.Test(() =>
            {
                var t = new Thread(() =>
                {
                    //...
                    ConsoleEx.WriteLnThreaded("inside thread...");
                    //ConsoleEx.ReadLn("press ENTER");
                });

                t.Start();
                t.Join();
            }, "System.Threading.Thread");

            InstrumentedOperation.Test(() =>
            {
                const int SIZE       = 5;
                CountdownEvent latch = new CountdownEvent(SIZE);

                for (int i = 0; i < SIZE; ++i)
                {
                    ThreadPool.QueueUserWorkItem(state =>
                    {
                        var j = (int)state;
                        ConsoleEx.WriteLnThreaded("inside thread pool {0}...", j);

                        Thread.Sleep(RandomGenerator.GetRandomInt32(1000, 5000));

                        latch.Signal();
                    }, i + 1);
                }

                latch.Wait();
            }, "System.Threading.ThreadPool");

            var a = new Action(() => {
                ConsoleEx.WriteLnThreaded("inside Parallel.Invoke...");
                Thread.Sleep(RandomGenerator.GetRandomInt32(1000, 5000));
            });

            InstrumentedOperation.Test(() =>
            {
                Parallel.Invoke
                (
                    a,
                    a,
                    a //, ...
                );
            }, "System.Threading.Tasks.Parallel.Invoke");

            InstrumentedOperation.Test(() =>
            {
                const int SIZE   = 50;
                List <string> xs = new List <string>(SIZE);
                for (int i = 0; i < SIZE; ++i)
                {
                    xs.Add(String.Format("inside Parallel.ForEach item #{0}...", i + 1));
                }

                Parallel.ForEach
                (
                    xs,

                    x =>
                {
                    ConsoleEx.WriteLnThreaded(x);
                    Thread.Sleep(RandomGenerator.GetRandomInt32(1000, 5000));
                }
                );
            }, "System.Threading.Tasks.Parallel.ForEach");

            InstrumentedOperation.Test(() =>
            {
                var a2 = new Action(() => {
                    ConsoleEx.WriteLnThreaded("inside Task...");
                    Thread.Sleep(RandomGenerator.GetRandomInt32(1000, 5000));
                });

                var t1 = Task.Factory.StartNew(a2);
                var t2 = Task.Factory.StartNew(a2);
                var t3 = Task.Factory.StartNew(a2);
                var t4 = Task.Factory.StartNew(a2);
                //...
                Task.WaitAll(t1, t2, t3, t4);
            }, "System.Threading.Tasks.Task");
        }
Beispiel #2
0
 public void giveInfo()
 {
     ConsoleEx.WriteAt(1, 1, "Hiya, folks.");
 }
Beispiel #3
0
        private async Task PrintResponse(HttpResponseMessage response, bool binary, CancellationToken cancellationToken)
        {
            ConsoleEx.Write(ConsoleColor.White, "HTTP{0} ", response.Version);

            // Status

            if (response.IsSuccessStatusCode)
            {
                ConsoleEx.Write(ConsoleColor.Green, "{0} {1}", (int)response.StatusCode, response.ReasonPhrase);
            }
            else if (response.StatusCode >= System.Net.HttpStatusCode.InternalServerError)
            {
                ConsoleEx.Write(ConsoleColor.Yellow, "{0} {1}", (int)response.StatusCode, response.ReasonPhrase);
            }
            else
            {
                ConsoleEx.Write(ConsoleColor.Red, "{0} {1}", (int)response.StatusCode, response.ReasonPhrase);
            }
            Console.WriteLine();

            // Headers

            void PrintHeaders(string title, HttpHeaders headers)
            {
                if (headers.Any())
                {
                    ConsoleEx.WriteLine(ConsoleColor.Cyan, "#{0}", title);

                    foreach (var pair in headers)
                    {
                        foreach (var value in pair.Value)
                        {
                            ConsoleEx.Write(ConsoleColor.Gray, " - ");
                            ConsoleEx.Write(ConsoleColor.White, pair.Key);
                            ConsoleEx.WriteLine(ConsoleColor.Gray, ": {0}", value);
                        }
                    }
                }
            }

            PrintHeaders("Headers", response.Headers);

            // Content

            if (response.Content != null)
            {
                byte[] bytes;

                try
                {
                    bytes = await response.Content.ReadAsByteArrayAsync();
                }
                catch
                {
                    ConsoleEx.WriteLine(ConsoleColor.Red, "Error reading response content");
                    return;
                }

                if (!binary)
                {
                    try
                    {
                        PrintHeaders("Content Headers", response.Content.Headers);

                        var charSet  = response.Content.Headers.ContentType.CharSet;
                        var encoding = charSet.IsNotNullOrWhiteSpace() ? Encoding.GetEncoding(charSet) : Encoding.UTF8;
                        var text     = encoding.GetString(bytes);
                        // TODO: if it is JSON, pretty print it
                        Console.WriteLine(text);

                        return;
                    }
                    catch
                    {
                        // could not read as string, show as binary
                    }
                }

                Console.WriteLine(Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks));
            }

            // Trailing Headers

            PrintHeaders("Trailing Headers", response.TrailingHeaders);
        }
Beispiel #4
0
    // Use this for initialization
    void Start()
    {
        IPAddress ip = LocalIp.localAddress;

        ConsoleEx.DebugLog(ip.ToString());
    }
        public double[] Minimize(Function f, double[] start, double[] eps)
        {
            if (f == null)
            {
                throw new ArgumentNullException(nameof(f));
            }

            if (eps == null)
            {
                throw new ArgumentNullException(nameof(eps));
            }

            if (start.Length != eps.Length)
            {
                throw new ArgumentException("Invalid parameter dimension.", nameof(eps));
            }

            // Clear f
            f.Clear();

            double[] e = eps.Copy();

            if (IsOutputEnabled)
            {
                ConsoleEx.WriteLine();
                ConsoleEx.WriteLineGreen("**********************************************************");
                ConsoleEx.WriteLineGreen("Starting minimization with Coordinate Descent method...");

                ConsoleEx.WriteLine();
                ConsoleEx.WriteLine("Parameters: ");
                ConsoleEx.WriteLine("x0 = " + start.Format(PRECISION));
                ConsoleEx.WriteLine("e = " + e.Format(PRECISION));
                ConsoleEx.WriteLine();
            }

            int iterations = 0;

            var x  = new Vector(start);
            var xs = x.Copy();

            do
            {
                iterations++;

                xs = x.Copy();
                for (int i = 0; i < start.Length; i++)
                {
                    Vector identity  = Vector.Identity(start.Length, i);
                    double minLambda = CalculateOptimalStepSize(f, x, identity);
                    x[i] += minLambda * identity[i];
                }

                if (IsOutputPerIterationEnabled && IsOutputEnabled)
                {
                    f.DisableStatistics();
                    LogIteration(iterations, x, f.Value(x.AsArray()));
                    f.EnableStatistcs();
                }

                if (iterations == MAX_ITERATIONS)
                {
                    break;
                }
            } while ((x - xs).Norm() > e.Norm());

            if (IsOutputPerIterationEnabled && IsOutputEnabled)
            {
                ConsoleEx.WriteLine();
            }

            if (IsOutputEnabled)
            {
                var evaluations = f.Evaluations;
                var cachedCalls = f.CachedCalls;
                ConsoleEx.WriteLineGreen("Final position found. Returning value: x = " + x.AsArray().Format(PRECISION));
                if (iterations == MAX_ITERATIONS)
                {
                    ConsoleEx.WriteLineRed($"Maximum number of iterations were hit [{MAX_ITERATIONS}]");
                }
                ConsoleEx.WriteLineGreen("Function value of final position is: " + f.Value(x.AsArray()).ToString("F" + PRECISION));
                ConsoleEx.WriteLine("Number of algorithm iterations: " + iterations);
                ConsoleEx.WriteLine("Number of function cached calls: " + cachedCalls);
                ConsoleEx.WriteLine("Number of function evaluations: " + evaluations);
                ConsoleEx.WriteLine();
            }

            return(x.AsArray());
        }
Beispiel #6
0
        public double Minimize(Function f, Interval startingInterval, double eps)
        {
            if (f == null)
            {
                throw new ArgumentNullException(nameof(f));
            }

            if (eps < 0)
            {
                throw new ArgumentException("eps is less than zero");
            }

            // Clear f
            f.Clear();

            if (IsOutputEnabled)
            {
                ConsoleEx.WriteLine();
                ConsoleEx.WriteLineGreen("**********************************************************");
                ConsoleEx.WriteLineGreen("Starting minimization with Golden Section Search method...");

                ConsoleEx.WriteLine();
                ConsoleEx.WriteLine("Parameters: ");
                ConsoleEx.WriteLine("EPSILON = " + eps);
                ConsoleEx.WriteLine("K = " + GOLDEN_RATIO);
                ConsoleEx.WriteLine("Start interval = " + startingInterval.ToString(6));
                ConsoleEx.WriteLine();
            }

            var lowerBound = startingInterval.Lower;
            var upperBound = startingInterval.Upper;

            int iterations = 1;

            double c  = upperBound - GOLDEN_RATIO * (upperBound - lowerBound);
            double d  = lowerBound + GOLDEN_RATIO * (upperBound - lowerBound);
            double fc = f.Value(c);
            double fd = f.Value(d);

            if (IsOutputPerIterationEnabled && IsOutputEnabled)
            {
                LogIteration(iterations, lowerBound, upperBound, c, d, f.Value(lowerBound), f.Value(upperBound), fc, fd);
            }

            while (upperBound - lowerBound > eps)
            {
                if (fc < fd)
                {
                    upperBound = d;
                    d          = c;
                    c          = upperBound - GOLDEN_RATIO * (upperBound - lowerBound);
                    fd         = fc;
                    fc         = f.Value(c);
                }
                else
                {
                    lowerBound = c;
                    c          = d;
                    d          = lowerBound + GOLDEN_RATIO * (upperBound - lowerBound);
                    fc         = fd;
                    fd         = f.Value(d);
                }

                iterations++;
                if (IsOutputPerIterationEnabled && IsOutputEnabled)
                {
                    f.DisableStatistics();
                    LogIteration(iterations, lowerBound, upperBound, c, d, f.Value(lowerBound), f.Value(upperBound), fc, fd);
                    f.EnableStatistcs();
                }
            }

            var finalPosition = FinalPosition(lowerBound, upperBound);
            var cachedCalls   = f.CachedCalls;
            var evaluations   = f.Evaluations;

            if (IsOutputPerIterationEnabled && IsOutputEnabled)
            {
                ConsoleEx.WriteLine();
            }

            if (IsOutputEnabled)
            {
                ConsoleEx.WriteLineGreen("Final position found. Returning value: " + finalPosition.ToString("F" + PRECISION));
                ConsoleEx.WriteLineGreen("Function value of final position is: " + f.Value(finalPosition).ToString("F" + PRECISION));
                ConsoleEx.WriteLine("Number of algorithm iterations: " + iterations);
                ConsoleEx.WriteLine("Number of function cached calls: " + cachedCalls);
                ConsoleEx.WriteLine("Number of function evaluations: " + evaluations);
                ConsoleEx.WriteLine();
            }

            return(finalPosition);
        }
 /// <summary>Copy the log to the clipboard.</summary>
 public void CopyLogToClipboard()
 {
     Clipboard.SetText(ConsoleEx.Generate(_exception));
 }
Beispiel #8
0
        private IServiceProvider ConfigureServices()
        {
            var services = new ServiceCollection()
                           .AddSingleton(Client)
                           .AddSingleton <LoggerService>()
                           .AddSingleton(new CommandService(new CommandServiceConfig {
                CaseSensitiveCommands = false, DefaultRunMode = RunMode.Async, ThrowOnError = false
            }))
                           .AddSingleton <MathService>()
                           .AddSingleton(Config)
                           .AddSingleton <DBContextFactory>()
                           .AddSingleton <ImageService>()
                           .AddSingleton <HttpService>()
                           .AddSingleton <TickService>()
                           .AddSingleton <CooldownService>()
                           .AddSingleton <EmbedService>()
                           .AddSingleton <TrackingService>()
                           .AddSingleton <AudioService>()
                           .AddSingleton <ReminderService>()
                           .AddSingleton <RedditService>()
                           .AddSingleton <CNNService>()
                           .AddSingleton <SalutationsService>()
                           .AddSingleton <ExecuteService>()
                           .AddSingleton <PrefixService>();
            IServiceProvider provider = null;

            provider = services.BuildServiceProvider();
            //We want this injected first.
            provider.GetService <DiscordSocketClient>();
            string connString = $"server={Config.MySQLServerAddress};database={Config.MySQLDatabase};uid={Config.MySQLUsername};pwd={Config.MySQLPassword};";

            provider.GetService <DBContextFactory>().ConnectionString = connString;
            provider.GetService <RedditService>();
            // Instantiate and autowire these services.

            foreach (ServiceDescriptor service in services.ToList())
            {
                var nsWhitelist = new List <string> {
                    "Discord", "Misaka"
                };
                var    serviceType = service.ServiceType;
                string nsBase      = serviceType.Namespace.Split('.').FirstOrDefault();

                if (serviceType.GetGenericArguments().Count() == 0 && nsWhitelist.Contains(nsBase))
                {
                    provider.GetService(serviceType);
                    ConsoleEx.WriteColoredLine($"Autowiring $[[DarkCyan]]${serviceType}$[[Gray]]$.");
                }
            }

            /*provider.GetService<MathService>();
             * provider.GetService<HttpService>();
             * provider.GetService<Config>();
             * provider.GetService<TickService>();
             * provider.GetService<CooldownService>();
             * provider.GetService<EmbedService>();
             * provider.GetService<DBContextFactory>();*/

            //provider.GetService<BotDBContext>().ConnectionString = connString;
            //provider.GetService<BotDBContext>().Database.EnsureCreated();

            /*provider.GetService<TrackingService>();
             * provider.GetService<AudioService>();
             * provider.GetService<ReminderService>();
             * provider.GetService<RedditService>();
             * provider.GetService<CNNService>();
             * provider.GetService<SalutationsService>();
             * provider.GetService<PrefixService>();*/
            return(provider);
        }
 /// <inheritdoc/>
 public string SelectEnvironment(
     IEnumerable <string> environments)
 {
     Console.WriteLine("Select cloud (or enter for default):");
     return(ConsoleEx.Select(environments));
 }
Beispiel #10
0
        public static void RunCommands()
        {
            var liveCommands = new LiveCommand[commandsQueue.Count];

            commandsQueue.CopyTo(liveCommands);
            foreach (LiveCommand c in liveCommands)
            {
                commandsQueue.Remove(c);
                var user = User.FromId(c.SenderId);
                if (user == null)
                {
                    commandsQueue.Remove(c);
                    continue;
                }
                ConsoleEx.Debug($"Executing command {c.Text} from {user.Nickname}");
                string[] cmd = c.Text.Split(' ');
                switch (cmd[0])
                {
                case "!help":
                    if (!user.IsAnAdmin())
                    {
                        user.SendPrivateMessage("[color=red]Sorry, your level is too low for this command ;)[/color]");
                    }
                    else
                    {
                        user.SendPrivateMessage("[color=green]!help, !ping, !kick [clid][/color]");
                    }
                    break;

                case "!ping":
                    if (!user.IsAnAdmin())
                    {
                        user.SendPrivateMessage("[color=red]Sorry, your level is too low for this command ;)[/color]");
                    }
                    else
                    {
                        user.SendPrivateMessage("[color=green]Pong! :)[/color]");
                    }
                    break;

                case "!kick":
                    if (!user.IsAnAdmin())
                    {
                        user.SendPrivateMessage("[color=red]Sorry, your level is too low for this command ;)[/color]");
                    }
                    else
                    {
                        int kickedid = -1;
                        if (cmd.Length < 2 || !int.TryParse(cmd[1], out kickedid))
                        {
                            user.SendPrivateMessage("[b][color=red]USE: !kick [clid][/color][/b]");
                            break;
                        }
                        var kicked = User.FromId(kickedid);
                        if (kicked == null)
                        {
                            user.SendPrivateMessage("[b][color=red]Wrong client id![/b]");
                            break;
                        }
                        kicked.KickFromServer("Bo tak \"bug\" nakazał.", 418);
                        user.SendPrivateMessage("[color=green]User kicked out from the server! :)[/color]");
                        ConsoleEx.WriteLine($"User {kicked.Nickname} was kicked from the server by {user.Nickname} using live command.");
                    }
                    break;

                case "!on":
                    if (user.GetServerGroups().Contains(49))
                    {
                        user.RemoveServerGroup(49);
                        user.AddServerGroup(42);
                        user.SendPrivateMessage("Ranga została zmieniona.");
                    }
                    break;

                case "!ona":
                    if (user.GetServerGroups().Contains(42))
                    {
                        user.RemoveServerGroup(42);
                        user.AddServerGroup(49);
                        user.SendPrivateMessage("Ranga została zmieniona.");
                    }
                    break;
                }
            }
        }
Beispiel #11
0
        public override void Start()
        {
            base.Start();
            // 1. wygeneruj dla wszystkich uzytkownikow broń {DrawWeapon}

            // WeaponService.GenerateWeaponForPlayers(LIst<Players> players)
            // WeaponService.GenerateWeaponForAllPlayers()

            // albo weapon service dostaje sie do wszystkich playerow poprzez Game.Players, albo wprowazdasz konkretnych playerow w parametr dla ktorych wygenerujesz bronie
            // zrob tak i tak

            Players.ForEach(x => x.ActiveGear.DrawWeapon());

            // 2. zaatakuj 30 uzytkownikami 30 innych uzytkownikow.

            // PlayerService
            // parametrem ma byc ilosc uzytkownikow nic wiecej.
            // _playerService.PrepareAttack(int userCount); <- 30

            // rozwiazanie pierwsze w jednej lini LINQ
            int indexOfiar = 0;

            Players.Take(30)
            .ToList()
            .ForEach(x => x.Attack(Players.Skip(30).ToArray()[indexOfiar++]));


            var psiontgraczy = from p in Players where p.CurrentHealth > 10000 select p;
            var psiontgracz2 = Players.Where(p => p.CurrentHealth > 10000);

            // 2.1 pobierz 30 graczy bez LINQ

            // PlayerService Browse()
            // niech browse dziala tak ze mozna pobrac wszystkich jesli nie podamy zadnego argumentu (parametru)
            // jesli podamy to ma byc ilosc ludzi do pobrania np 30
            // Browse() Browse(30)

            // Player[] trzydziesciGraczy = new Player[30];
            List <Player> trzydziesciGraczy = new List <Player>();

            for (int i = 0; Players.Count < 30; i++)
            {
                trzydziesciGraczy.Add(Players[i]);
            }

            // Inne rozwiazania:

            // przygotowanie listy graczy
            var trzydziesciGraczyGotowychDoAtaku = Players.Take(30).ToList();
            var trzydziesciOfiar = Players.Skip(30).ToArray();

            // rozwiązanie drugie
            indexOfiar = 0;
            trzydziesciGraczyGotowychDoAtaku.ForEach(gracz => gracz.Attack(trzydziesciOfiar[indexOfiar++]));

            // rozwiązanie trzecie
            indexOfiar = 0;
            foreach (var gotowyGraczDoAtaku in trzydziesciGraczyGotowychDoAtaku)
            {
                var ofiara = trzydziesciOfiar[indexOfiar];
                gotowyGraczDoAtaku.Attack(ofiara);
                indexOfiar++;
            }

            // rozwiazanie czwarte
            indexOfiar = 0;
            for (int indexGotowychGraczy = 0; indexGotowychGraczy < trzydziesciGraczyGotowychDoAtaku.Count; indexGotowychGraczy++)
            {
                var ofiara = trzydziesciOfiar[indexOfiar];
                trzydziesciGraczyGotowychDoAtaku[indexGotowychGraczy].Attack(ofiara);
                indexOfiar++;
            }


            // 3. pobrac 10 uzytkownikow ktorzy maja najmniej {CurrentHealth}.

            // PlayerService GetPlayersWithLowerstHealth(int count)

            var tenPlayersWithLowestHealth = Players.OrderBy(x => x.CurrentHealth)
                                             .Take(10)
                                             .ToList();


            // PlayerService GetSortedByHealth

            // 4. posortowac wszystkich uzytkowników po poziomie {CurrentHealth} malejąco.

            Players.OrderByDescending(x => x.CurrentHealth)
            .ToList()
            .ForEach(p => ConsoleEx.Log($"Players with name {p.Name} health: {p.CurrentHealth}", ConsoleColor.DarkBlue));

            Players.OrderBy(x => x.Friends);


            // 5. SERVICe -> wyświetlic 10 uzytkownikow poprzez serwis
            // PlayerService.LogPlayers(int count);

            // 5. wyświetlic ostatnio posortowanych 10 uzytkownikow uzywajac petli z LINQ.

            tenPlayersWithLowestHealth.ForEach(p => ConsoleEx.Log($"Players with name {p.Name} health: {p.CurrentHealth}", ConsoleColor.Cyan));

            foreach (var p in tenPlayersWithLowestHealth)
            {
                ConsoleEx.Log($"Players with name {p.Name} health: {p.CurrentHealth}", ConsoleColor.Cyan);
            }

            // FriendsService.AddRandomFriends(Player player, int count)

            // 6. dodaj do znajomych 15 uzytkownikow z najwieksza iloscia {CurrentHealth}

            You.AddFriends(Players.OrderBy(x => x.CurrentHealth).ToList().Take(15).ToList());

            You.AddFriends(Players.OrderByDescending(x => x.CurrentHealth).Take(15).ToList());

            // 7. dodaj do znajomych 10 uzytkownikow z najwiekszą ilościa statystyki {Agility}.
            // FriendsService.AddFriendsWithHighestAgility(Player player, int count)

            You.AddFriends(Players.OrderByDescending(x => x.BaseStatiscits.Agility).Take(10).ToList());

            // 8. dodaj do znajomych 5 randomowych uzytkownikow
            //Friends.Service.AddFriendsRandom(Player player, int count)

            You.AddFriends(Players.TakeRandomly(5).ToList());

            You.AddFriends(Players.Skip(154).Take(5).ToList());

            Enumerable.Range(0, 5).ToList().ForEach(x => You.AddFriends(new List <Player>()
            {
                Players[new Random().Next(1, PlayerConfig.FAKE_PLAYERS)]
            }));

            for (int i = 0; i > 5; i++)
            {
                You.AddFriends(new List <Player>()
                {
                    Players[new Random().Next(1, PlayerConfig.FAKE_PLAYERS)]
                });
            }

            Players.Take(5);


            Players.TakeRandomly(5);

            // 9. usuń ze swoich znajomych uzytkownika z najgorszą ilością {CurrentHealth} (agregate, remove)
            //Frends.Service.RemoveYourFriendWithTheLowestCurrentHealth()

            You.Friends.Remove(You.Friends.OrderBy(x => x.CurrentHealth).First());

            var a = You.Friends.Aggregate((prev, next) => prev.CurrentHealth < next.CurrentHealth ? prev : next);

            You.Friends.Remove(a);

            // 10. pogrupuj uzytkownikow po takich samych broniach {PrimaryWeapon}
            //Weponservice.GroupByTheSameWeapon()

            var grouppedWeapons = Players.GroupBy(x => x.ActiveGear.PrimaryWeapon);

            // 11. wyswietl sume powtarzalnych broni z pogrupowanej powyzej listy {PrimaryWeapon}

            // 12. wyswietl top 100 graczy uzywajac modelu PlayerStatiscic w folderze DTOs, lista musi byc posortowana po punktach malejąco {Points} (select)
            //Players.LogTop100Players()


            int index = 1;

            Players.Select(x => new PlayerStatistic(x)).OrderByDescending(x => x.Points).Take(100).ToList().ForEach(x => ConsoleEx.Log($"{index++}. Name: {x.Name}, Points: {x.Points}", ConsoleColor.Green));

            // 13. zamien 50 randomowym uzytkownikom broń na inna randomową broń

            Players.Take(50).ToList().ForEach(x => x.ActiveGear.DrawWeapon());

            // 14. znajdz 10 uzytkownikow z najwieksza iloscia zycia, oraz z najwieksza iloscia stoczonych walk {Fights}

            var players_with_the_most_lives_and_fights = Players.OrderByDescending(x => x.CurrentHealth)
                                                         .ThenByDescending(x => x.Fights)
                                                         .Take(10)
                                                         .ToList();

            players_with_the_most_lives_and_fights.ForEach(x => ConsoleEx.Log($"Players with the most lives and fights: {x.Name}", ConsoleColor.Yellow));

            // 15. zaatakuj 10-cioma uzytkownikami 10 innych uzytkownikow 10 razy (foreach), (foreach, enumerable.range) lub (select).

            // 1
            //for(int i = 0; i < 10; i++)
            //{
            //      ...
            //}

            // 2
            //new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }.ToList().ForEach(i => )

            // 3
            //Enumerable.Range(0, 10).ToList().ForEach(i => ....)

            // 1. rozwiazanie gdzie atakujacy atakuje kazdego jeden raz


            Players.Take(10).ToList().ForEach(atakujący1 => {
                for (int ofiaraIndex = 10; ofiaraIndex < 20; ofiaraIndex++)
                {
                    atakujący1.Attack(Players[ofiaraIndex]);
                }
            });

            // 1. rozwiazanie gdzie atakujacy atakuje 10 razy ta sama ofiare


            int indexOfiary2 = 0;

            Players.Take(10).ToList().ForEach(atakujący1 => {
                for (int i = 10; i < 20; i++)
                {
                    var ofiara = Players[indexOfiary2];
                    atakujący1.Attack(ofiara);
                }
                indexOfiary2++;
            });

            // 2 rozwiazanie gdzie atakujacy atakuje kazdego jeden raz

            Players.Take(10).ToList().ForEach(atakujący1 => new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }.ToList().ForEach(ofiaraIndex => atakujący1.Attack(Players.Skip(10).Take(10).ToArray()[ofiaraIndex])));


            // 3 rozwiazanie gdzie atakujacy atakuje kazdego jeden raz

            Players.Take(10).ToList().ForEach(atakujący1 => Enumerable.Range(0, 10).ToList().ForEach(ofiaraIndex => atakujący1.Attack(Players.Skip(10).Take(10).ToArray()[ofiaraIndex])));


            ConsoleEx.Log("#######################", ConsoleColor.Red);

            Players.Take(10).ToList().ForEach(_atakujacy => Players.Skip(10).Take(10).ToList().ForEach(ofiara => _atakujacy.Attack(ofiara)));

            ConsoleEx.Log("#######################", ConsoleColor.Red);


            Players.Take(10).Select((x, i) => new { player = x, index = i }).ToList().ForEach(x => x.player.Attack(Players.Skip(10).ToList()[x.index]));

            // 16. wyświetl przegranych uzytkownikow jesli tacy są CurrentHealth < 0

            Players.Where(x => x.CurrentHealth <= 0)
            .ToList()
            .ForEach(x => ConsoleEx.Log($"Players killed: {x.Name}.", ConsoleColor.Black));


            // 17. Przepisz konstruktor na get i set w statystykach.

            // 18. Sprawdź czy {You} wystepuje w liscie {Players}. (Contains)

            ConsoleEx.Log(Players.Contains(You) ? $"Current player exists in Player list." : $"Current player does not exists in Player list.");

            // 19. Wyświetl średnią ilość żyć wszystkich graczy

            string averageHealth = Players.Average(x => x.CurrentHealth).ToString();

            ConsoleEx.Log($"Average life expectancy of all players: {averageHealth}");

            // 20. Wyświetl średnią ilość agility wszystkich graczy

            string averageAgility = Players.Average(x => x.BaseStatiscits.Agility).ToString();

            ConsoleEx.Log($"Average agility of all players: {averageAgility}");

            // 21. Wyświetl gracza który posiada najwiekszą ilosc jednej z statystyk

            // 1. znajdź wartość maksymalną dla agility, health, stamina, strenght (linq, max) i i utwórz nową zmienną
            // 2. używając if, else if, if sprawdź, która wartość z tych 4 jest największa

            // Rozwiązanie pierwsze

            double agility  = Players.Max(x => x.BaseStatiscits.Agility);
            double health   = Players.Max(x => x.BaseStatiscits.Health);
            double stamina  = Players.Max(x => x.BaseStatiscits.Stamina);
            double strenght = Players.Max(x => x.BaseStatiscits.Strenght);

            if (agility > health && agility > stamina && agility > strenght)
            {
                ConsoleEx.Log($"The highest value of agility:{agility}");
            }
            else if (health > agility && health > stamina && health > strenght)
            {
                ConsoleEx.Log($"The highest value of health:{health}");
            }
            else if (stamina > health && stamina > agility && stamina > strenght)
            {
                ConsoleEx.Log($"The highest value of stamina:{stamina}");
            }
            else
            {
                ConsoleEx.Log($"The highest value of strenght:{strenght}");
            }

            // Rozwiązanie drugie

            // 1. Utwórz tablicę z parametrami nazwa i wartość (wykorzystując linq max)
            // 2. Użyj agreggate, aby znaleźć najwyższą wartość.
            // 3. Wyświetl wartość na konsoli na podstawie danych z punktu pierwszego.

            var highestStat = new[]
            {
                new { name = "Agility", value = Players.Max(x => x.BaseStatiscits.Agility) },
                new { name = "Health", value = Players.Max(x => x.BaseStatiscits.Health) },
                new { name = "Stamina", value = Players.Max(x => x.BaseStatiscits.Stamina) },
                new { name = "Strenght", value = Players.Max(x => x.BaseStatiscits.Strenght) }
            }.Aggregate((prev, next) => prev.value > next.value ? prev : next);

            ConsoleEx.Log($"The highest Statistics is {highestStat.name} with value: {highestStat.value}");

            // Rozwiązanie trzecie (almost pro)

            Func <Player, int> agilitySelector  = selector => selector.BaseStatiscits.Agility;
            Func <Player, int> healthSelector   = selector => selector.BaseStatiscits.Health;
            Func <Player, int> staminaSelector  = selector => selector.BaseStatiscits.Stamina;
            Func <Player, int> strenghtSelector = selector => selector.BaseStatiscits.Strenght;

            // delegate int selector(Func<Player, int> selector);

            var playerWithBestStats = new[]
            {
                new { selector = agilitySelector, player = Players.Aggregate((prev, next) => prev.BaseStatiscits.Agility > next.BaseStatiscits.Agility ? prev : next) },
                new { selector = healthSelector, player = Players.Aggregate((prev, next) => prev.BaseStatiscits.Health > next.BaseStatiscits.Health ? prev : next) },
                new { selector = staminaSelector, player = Players.Aggregate((prev, next) => prev.BaseStatiscits.Stamina > next.BaseStatiscits.Stamina ? prev : next) },
                new { selector = strenghtSelector, player = Players.Aggregate((prev, next) => prev.BaseStatiscits.Strenght > next.BaseStatiscits.Strenght ? prev : next) }
            }.Aggregate((prev, next) => prev.selector(prev.player) > next.selector(next.player) ? prev : next);

            ConsoleEx.Log($"The highest Statistics is {playerWithBestStats.selector(playerWithBestStats.player)}");

            // 22. Utwórz i dodaj nowego gracza na początku sekwencji/listy graczy

            var newplayer = new Player("Guzik");

            Players.Insert(0, newplayer);

            // 23. Usuń wszystkich graczy którzy posiadają broń "Amnesia" oraz wyświetl liczbe usuniętych graczy


            var listaużytkownikówdousunięcia = Players.Where(x => x.ActiveGear?.PrimaryWeapon?.Name == "Amnesia").ToList();

            foreach (var użytkownikdousunięcia in listaużytkownikówdousunięcia)
            {
                Players.Remove(użytkownikdousunięcia);
            }

            Players.Where(x => x.ActiveGear?.PrimaryWeapon?.Name == "Amnesia").ToList().ForEach(x => ConsoleEx.Log(x.Name));
            Players.RemoveAll(x => x.ActiveGear?.PrimaryWeapon?.Name == "Amnesia");

            // 24. Wyświetl całkowitą liczbe stoczonych walk wszystkich graczy (pojedyncza liczba)
            // -

            int stoczonewalki = Players.Sum(x => x.Fights);

            ConsoleEx.Log($"{stoczonewalki}");

            var liczba = 0;

            foreach (var gracz in Players)
            {
                liczba = liczba + gracz.Fights;
            }

            Console.WriteLine("Liczba stoczonych walk to " + liczba);

            liczba = 0;
            for (int i = 0; i < Players.Count; i++)
            {
                liczba = liczba + Players[i].Fights;
            }

            Console.WriteLine("Liczba stoczonych walk to " + liczba);

            Console.WriteLine("Liczba stoczonych walk to " + Players.Sum(x => x.Fights));

            // 25. Spróbuj zabić jednego uzytkownika (while, bez linQ)

            // rozwiązanie 1

            var ofiara2   = Players[101];
            var atakujący = Players[102];


            while (ofiara2.CurrentHealth > 0)
            {
                atakujący.Attack(ofiara2);
            }

            // rozwiązanie 2

            Players[32].Friends.Add(atakujący);

            while (ofiara2.CurrentHealth > 0)
            {
                Players[32].Attack(ofiara2);
            }

            Console.WriteLine(ofiara2.DeathDate.ToString());


            // 26. Zmodyfikuj model playera o date zgonu

            // done

            // 27. Wyświetl wszystkie informacje powyższego uzytkownika, uwzgledniając date zgonu.

            Console.WriteLine($"Informacje o użytkowniku Imię: {ofiara2.Name}, " +
                              $"Agility: {ofiara2.BaseStatiscits.Agility}, " +
                              $"Stamina: {ofiara2.BaseStatiscits.Stamina}, " +
                              $"Strengh: {ofiara2.BaseStatiscits.Strenght}, " +
                              $"Health: {ofiara2.BaseStatiscits.Health}," +
                              $"Ponits: {new PlayerStatistic(ofiara2).Points}," +
                              $"Data zgonu: {ofiara2.DeathDate}"
                              );


            // 28. Usuń połowe graczy z najsłabszym hp {CurrentHealth}

            Players.OrderByDescending(x => x.CurrentHealth).Take(Players.Count / 2).ToList().ForEach(x => Players.Remove(x));

            // 29. Sprawdź czy jakiś uzytkonik ma w znajomych zgona. (where, any)

            var usersWithDeathPlayers = Players.Where(x => x.Friends.Any(y => y.CurrentHealth <= 0));

            // 30. Znajdz uzytkownika z najdłuższym imieniem.


            var nnnn = Players.OrderByDescending(x => x.Name.Length).First();

            Players.Aggregate((prev, next) =>
            {
                if (prev.Name.Length > next.Name.Length)
                {
                    return(prev);
                }
                return(next);
            });

            // true ? true : false

            var użytkownikznajdłuższymimieniem1 = Players.Aggregate((prev, next) => prev.Name.Length > next.Name.Length ? prev : next);



            // 31. Znajdz uzytkownika z najwiekszą ilością życia.


            Players.Aggregate((prev, next) =>
            {
                if (prev.CurrentHealth > next.CurrentHealth)
                {
                    return(prev);
                }
                return(next);
            });

            Players.Aggregate((prev, next) => prev.CurrentHealth > next.CurrentHealth ? prev : next);

            // 32. Utworz metode ktora przyjmuje dwóch playerów i zwraca tego ktory ma wieksze {MaxHealth}


            Player GetPlayerWithHigherMaxHealth(Player first, Player next)
            {
                if (first.MaxHealth > next.MaxHealth)
                {
                    return(first);
                }

                return(next);
            }

            Player GetPlayerWithHigherMaxHealth2(Player first, Player next) => first.MaxHealth > next.MaxHealth ? first : next;

            var abcdef1 = GetPlayerWithHigherMaxHealth(new Player("asdasd"), new Player("Asdasd"));

            // 33. Uzyj jeden z utworzonej powyzej metody jako parametr metody Aggregate

            Func <Player, Player, Player> GetPlayerWithHigherMaxHealthFunc = (first, next) => first.MaxHealth > next.MaxHealth ? first : next;


            Players.Aggregate(GetPlayerWithHigherMaxHealth);

            Players.Aggregate(GetPlayerWithHigherMaxHealthFunc);

            // 34. Dodaj do każdego uzytkownika kilku randomowych znajomych.

            Players.ForEach(x => x.AddFriends(Players.ToList().TakeRandomly(5).ToList()));

            // 35. Znajdź uzytkownika z najwiekszą ilościa znajomych.


            Players.Aggregate((prev, next) => prev.Friends.Count > next.Friends.Count ? prev : next);
        }
Beispiel #12
0
        public Answers Ask()
        {
            var answers = new Answers(_promptItems.Count);

            EventHandler <BeforeAfterPromptEventArgs> beforePrompt   = BeforePrompt;
            EventHandler <BetweenPromptEventArgs>     betweenPrompts = BetweenPrompts;
            EventHandler <BeforeAfterPromptEventArgs> afterPrompt    = AfterPrompt;

            for (int i = 0; i < _promptItems.Count; i++)
            {
                PromptItem promptItem = _promptItems[i];

                beforePrompt?.Invoke(this, new BeforeAfterPromptEventArgs {
                    Prompt = promptItem
                });

                object answer;

                // If the prompt cannot be displayed, continue the loop.
                // If it is a question, try assigning the default value, if available, before
                // continuing.
                if (!promptItem.CanAsk(answers))
                {
                    if (promptItem is Question q)
                    {
                        answer = q.DefaultValue.Resolve(answers);
                        if (answer != null)
                        {
                            answers.Add(q.Name, answer);
                        }
                    }

                    continue;
                }

                // If the prompt is static text, just display it and continue the loop.
                if (promptItem is StaticText)
                {
                    promptItem.AskerFn(promptItem, answers);
                    continue;
                }

                var question = promptItem as Question;

                if (question.Instructions.Count > 0)
                {
                    foreach (FunctionOrColorString instruction in question.Instructions)
                    {
                        var cstr = new ColorString().Text(instruction.Resolve(answers),
                                                          Style.Instructions.ForeColor, Style.Instructions.BackColor);
                        ConsoleEx.PrintLine(cstr.ToString());
                    }
                }

                answer = null;
                bool validAnswer = false;
                do
                {
                    object input = question.AskerFn(question, answers);

                    if (question.RawValueValidator != null)
                    {
                        ValidationResult validationResult = question.RawValueValidator(input, answers);
                        if (!validationResult.Valid)
                        {
                            if (!string.IsNullOrWhiteSpace(validationResult.ErrorMessage))
                            {
                                ConsoleEx.PrintLine($"{Clr.Red}{validationResult.ErrorMessage}");
                            }
                            continue;
                        }
                    }

                    if (input is null || (input is string s && s.Length == 0))
                    {
                        answer = question.DefaultValue.Resolve(answers);
                    }
                    else
                    {
                        answer = input;
                    }

                    answer = question.Convert(answer);

                    if (question.ConvertedValueValidator != null)
                    {
                        ValidationResult validationResult = question.ConvertedValueValidator(answer, answers);
                        if (!validationResult.Valid)
                        {
                            if (!string.IsNullOrWhiteSpace(validationResult.ErrorMessage))
                            {
                                ConsoleEx.PrintLine($"{Clr.Red}{validationResult.ErrorMessage}");
                            }
                            continue;
                        }
                    }

                    validAnswer = true;
                }
#pragma warning disable S2583 // Conditionally executed blocks should be reachable
                while (!validAnswer);
#pragma warning restore S2583 // Conditionally executed blocks should be reachable

                answers.Add(question.Name, answer);

                if (i < _promptItems.Count - 1)
                {
                    betweenPrompts?.Invoke(this, new BetweenPromptEventArgs
                    {
                        PreviousPrompt = promptItem,
                        NextPrompt     = _promptItems[i + 1],
                    });
                }

                afterPrompt?.Invoke(this, new BeforeAfterPromptEventArgs {
                    Prompt = promptItem
                });
            }
Beispiel #13
0
        private const string CServerVersion = "13.0.4001.0"; // https://support.microsoft.com/en-us/help/3182545

        static void Main(string[] args)
        {
            var connectionString = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
            ServerConnection cnn;
            string           databaseName;

            using (var sqlConnection = new SqlConnection(connectionString))
            {
                cnn = new ServerConnection(sqlConnection);
                // Read the database name from app.config
                databaseName = sqlConnection.Database;
            }
            cnn.Connect();
            var server = new Server(cnn);

            if (server.Version <= new Version(CServerVersion))
            {
                ConsoleEx.WriteLine("Only supported for SQL 2016+");
                Console.ReadLine();
            }
            try
            {
                var db = server.Databases[databaseName];
                //Person.EmailAddress
                var tbl = db.Tables["EmailAddress", "Person"];

                // --== Let's define the first column 'ValidFrom' ==---
                //      the equivalent T-SQL would be 'ValidFrom DATETIME2 GENERATED ALWAYS AS ROW START HIDDEN NOT NULL'
                var col = new Column(tbl, "ValidForm")
                {
                    DataType = DataType.DateTime2(7),
                    //IsHidden = true,
                    //GeneratedAlwaysType = GeneratedAlwaysType.AsRowStart,
                    Nullable = false,
                };
                col.AddDefaultConstraint("DfValidFrom");
                col.DefaultConstraint.Text = "'1991-01-01 00:00:00.0000000'";

                tbl.Columns.Add(col);


                // --== Let's define the column 'ValidTo' ==---
                var col2 = new Column(tbl, "ValidTo")
                {
                    DataType = DataType.DateTime2(7),
                    //IsHidden = true,
                    //GeneratedAlwaysType = GeneratedAlwaysType.AsRowEnd,
                    Nullable = false,
                };
                col2.AddDefaultConstraint("DfValidTo");
                col2.DefaultConstraint.Text = "'9999-12-31 23:59:59.9999999'";
                tbl.Columns.Add(col2);


                // --== Let's define the period ==---
                tbl.Alter();
                tbl.AddPeriodForSystemTime(col.Name, col2.Name, true);
                tbl.Alter();


                tbl.IsSystemVersioned    = true;
                tbl.HistoryTableSchema   = tbl.Schema;
                tbl.HistoryTableName     = $"{tbl.Name}_History";
                tbl.DataConsistencyCheck = true;
                tbl.Alter();

                ConsoleEx.WriteLine("Let's Examine the Table ", ConsoleColor.Red);
                ConsoleEx.WriteLine($"Is System Versioned Enabled {tbl.IsSystemVersioned}", ConsoleColor.Blue);
                ConsoleEx.WriteLine($"History Table Name {tbl.HistoryTableSchema}.{tbl.HistoryTableName}", ConsoleColor.Blue);
                ConsoleEx.WriteLine($"Data Consistency Check {tbl.DataConsistencyCheck}", ConsoleColor.Blue);


                ConsoleEx.WriteLine("Let's make some updates - change the email address for the first record and see the result", ConsoleColor.Red);


                var ds = db.ExecuteWithResults("UPDATE [Person].[EmailAddress] SET [EmailAddress] = '*****@*****.**' " +
                                               "WHERE BusinessEntityID=1 AND EmailAddressID=1; " +
                                               "DECLARE @Now AS DATE = CAST(GETDATE() AS DATE);" +
                                               "SELECT EmailAddress FROM [Person].[EmailAddress] FOR SYSTEM_TIME AS OF @Now WHERE BusinessEntityID=1 AND EmailAddressID=1");


                ConsoleEx.WriteLine($"The Email Address Is {ds.Tables[0].Rows[0][0]}");

                Console.ReadLine();
            }
            catch (Exception ex)
            {
                ConsoleEx.WriteLine(ex.ToString(), ConsoleColor.Red);
                Console.ReadLine();
            }
        }
 public void CheckAllErrorBack(BaseHttpRequest request, string error)
 {
     SQYAlertViewMove.CreateAlertViewMove(Core.Data.stringManager.getString(7365));
     ConsoleEx.DebugLog(" --- CheckAllErrorBack : ---- " + error);
 }
Beispiel #15
0
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            ConsoleEx.WriteLineWithColor("[Inbound message]", ConsoleColor.Yellow);

            ConsoleEx.WriteLineWithColor(reply.ToString(), ConsoleColor.Blue);
        }
 /// <inheritdoc/>
 public string SelectRegion(
     IEnumerable <string> regions)
 {
     Console.WriteLine("Select region (or enter for default):");
     return(ConsoleEx.Select(regions));
 }
        public static void Main()
        {
            ConsoleEx.WriteAlert("# Ejercicio 3 #", ConsoleColor.Green);

            Console.ReadKey(true);
        }
 /// <inheritdoc/>
 public string SelectSubscription(
     IEnumerable <string> subscriptions)
 {
     Console.WriteLine("Select subscription (or enter for default):");
     return(ConsoleEx.Select(subscriptions));
 }
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            try
            {
                Graphics graphics = e.Graphics;
                graphics.SmoothingMode      = SmoothingMode.HighQuality;
                graphics.CompositingQuality = CompositingQuality.GammaCorrected;

                Size      textArea = TextManager.MeasureText(Text, Font, graphics);
                Rectangle group    = ConfigureStyleBox(textArea);
                Rectangle title    = ConfigureStyleTitleBox(textArea);

                _titleBoxRectangle = new Rectangle(title.X, title.Y, title.Width - 1, title.Height);

                Rectangle _clientRectangle = new Rectangle(group.X, group.Y, group.Width, group.Height);
                ControlGraphicsPath = VisualBorderRenderer.CreateBorderTypePath(_clientRectangle, _border);
                graphics.FillRectangle(new SolidBrush(BackColor), _clientRectangle);

                Color _backColor = Enabled ? BackColorState.Enabled : BackColorState.Disabled;
                VisualBackgroundRenderer.DrawBackground(e.Graphics, _backColor, BackgroundImage, MouseState, group, Border);

                if (_borderEdge.Visible)
                {
                    _borderEdge.Location = new Point(_titleBoxRectangle.X + _border.Thickness, _titleBoxRectangle.Bottom);
                    _borderEdge.Size     = new Size(Width - _border.Thickness - 1, 1);
                }

                VisualBorderRenderer.DrawBorderStyle(e.Graphics, _border, ControlGraphicsPath, MouseState);

                if (_boxStyle == GroupBoxStyle.Classic)
                {
                    Size _newSize;
                    if (_image != null)
                    {
                        _newSize = _image.Size;
                    }
                    else
                    {
                        _newSize = new Size(0, 0);
                    }

                    _titleBoxRectangle = new Rectangle(5, 0, title.Width - 1, title.Height);
                    Point _titleBoxBackground = RelationManager.GetTextImageRelationLocation(graphics, _textImageRelation, new Rectangle(new Point(0, 0), _newSize), Text, Font, _titleBoxRectangle, Relation.Text);
                    graphics.FillRectangle(new SolidBrush(BackColorState.Enabled), new Rectangle(new Point(_titleBoxBackground.X, _titleBoxBackground.Y), new Size(_titleBoxRectangle.Width, _titleBoxRectangle.Height)));
                }

                if (_image != null)
                {
                    VisualControlRenderer.DrawContent(e.Graphics, _titleBoxRectangle, Text, Font, ForeColor, _image, _image.Size, _textImageRelation);
                }
                else
                {
                    StringFormat _stringFormat = new StringFormat {
                        Alignment = _textAlignment, LineAlignment = _textLineAlignment
                    };

                    VisualTextRenderer.RenderText(e.Graphics, _titleBoxRectangle, Text, Font, ForeColor, _stringFormat);
                }
            }
            catch (Exception exception)
            {
                ConsoleEx.WriteDebug(exception);
            }
        }
Beispiel #20
0
 private void DrawHud(int xOff, int yOff)
 {
     ConsoleEx.WriteCoord(xOff, yOff + 22);
     ConsoleEx.WriteLine("SCORE", 0xf);
     ConsoleEx.WriteLine(game.Score.ToString("D10"), 0x7);
 }
 /// <summary>Saves the log to a file.</summary>
 /// <param name="filePath">The file Path.</param>
 public void SaveLog(string filePath)
 {
     File.WriteAllText(filePath, ConsoleEx.Generate(_exception));
 }
 private void Print(string value)
 {
     ConsoleEx.Write(value);
 }
Beispiel #23
0
        private void SimulateWalkers()
        {
            var n    = DateTime.UtcNow;
            var to   = new DateTime(n.Year, n.Month, n.Day, 0, 0, 0, DateTimeKind.Utc);
            var from = to - TimeSpan.FromDays(1);

            var fromDate               = ConsoleEx.ReadLine("From (UTC)", from);
            var toDate                 = ConsoleEx.ReadLine("To (UTC)", to);
            var timeZoneDiff           = ConsoleEx.ReadLine("Time Zone Diff (h)", 1);
            var warmupTime             = ConsoleEx.ReadLine("Warmup Time (min)", 15);
            var gamerTagFile1          = ConsoleEx.ReadLine("GamerTags File 1", "DataFiles/GamerTags1.txt", s => File.Exists(s));
            var gamerTagFile2          = ConsoleEx.ReadLine("GamerTags File 2", "DataFiles/GamerTags2.txt", s => File.Exists(s));
            var gamerTagFile3          = ConsoleEx.ReadLine("GamerTags File 3", "DataFiles/GamerTags3.txt", s => File.Exists(s));
            var playerDistributionFile = ConsoleEx.ReadLine("Player Distribution File", "DataFiles/PlayerDistribution.tsv", s => File.Exists(s));
            var routesFolder           = ConsoleEx.ReadLine("GeoJson Routes Folder", DefaultRoutesFolder, s => Directory.Exists(s));
            var step = ConsoleEx.ReadLine("Increase Clock With (s)", 12);

            var gamerTagProvider    = new GamerTagProvider(gamerTagFile1, gamerTagFile2, gamerTagFile3);
            var gameSessionProvider = new GameSessionProvider();
            var geoRouteProvider    = new GeoRouteProvider(routesFolder);


            var playerDistribution = new PlayerDistributionProvider(playerDistributionFile);
            var now        = fromDate.AddMinutes(-warmupTime);
            var bots       = new List <NetherBot>();
            var botsNeeded = 0d;

            var lastTick = now.AddSeconds(-1);

            while (now < toDate)
            {
                bool warmup = now <= fromDate;

                if (now.Second == 0)
                {
                    Console.WriteLine();
                    Console.WriteLine(now.ToString());
                    Console.WriteLine($"Number of players: {bots.Count}");
                }

                Console.Write(".");
                var delta = now - lastTick;

                botsNeeded += playerDistribution.GetDistribution(now) / 60; // * delta.TotalMinutes;
                var botsToSpawnNow = (int)botsNeeded;

                // Add any new bots needed
                for (int i = 0; i < botsToSpawnNow; i++)
                {
                    var bot = new GeoBot(_client, gamerTagProvider, gameSessionProvider, geoRouteProvider);

                    bots.Add(bot);
                }

                // Deduct the number of bots that was just spawned from the needed count of bots
                botsNeeded -= botsToSpawnNow;

                // Update each bot
                foreach (var bot in bots)
                {
                    bot.TickAsync(now, warmup).Wait();
                }

                // Remove bots that are done
                bots.RemoveAll(b => b.SessionEnded);

                now += TimeSpan.FromSeconds(step);
            }

            _client.FlushAsync().Wait();
        }
 private void Print(ConsoleColor color, string value)
 {
     ConsoleEx.ColorWrite(color, value);
 }
Beispiel #25
0
        public new static void Parse(XNode node, DefinitionFile file)
        {
            UiContainer.Parse(node, file);

            DefinitionParser parser = new DefinitionParser(node);

            file["Items"]            = parser.ParseDelegate("Items");
            file["Mode"]             = parser.ParseEnum <Mode>("Mode");
            file["Reverse"]          = parser.ParseBoolean("Reverse");
            file["MaxAddFirstTime"]  = parser.ParseInt("MaxAddFirstTime");
            file["MaxAddOneTime"]    = parser.ParseInt("MaxAddOneTime");
            file["ExceedRule"]       = parser.ParseEnum <ScrollingService.ExceedRule>("ExceedRule");
            file["WheelScrollSpeed"] = parser.ParseDouble("WheelScrollSpeed");
            file["MaxScrollExceed"]  = parser.ParseLength("MaxScrollExceed");

            Dictionary <Type, DefinitionFile> additionalTemplates = new Dictionary <Type, DefinitionFile>();

            foreach (var cn in node.Nodes)
            {
                switch (cn.Tag)
                {
                case "UiListBox.ItemTemplate":
                {
                    if (cn.Nodes.Count != 1)
                    {
                        string error = node.NodeError("UiListBox.ItemTemplate must have exactly 1 child.");

                        if (DefinitionParser.EnableCheckMode)
                        {
                            ConsoleEx.WriteLine(error);
                        }
                        else
                        {
                            throw new Exception(error);
                        }
                    }

                    if (string.IsNullOrEmpty(cn.Attribute("DataType")))
                    {
                        if (file["Template"] != null)
                        {
                            string error = node.NodeError("UiListBox default template already defined.");

                            if (DefinitionParser.EnableCheckMode)
                            {
                                ConsoleEx.WriteLine(error);
                            }
                            else
                            {
                                throw new Exception(error);
                            }
                        }

                        file["Template"] = DefinitionFile.LoadFile(cn.Nodes[0]);
                    }
                    else
                    {
                        Type type = Type.GetType(cn.Attribute("DataType"));

                        if (type == null)
                        {
                            string error = node.NodeError("Cannot find type: {0}", cn.Attribute("DataType"));

                            if (DefinitionParser.EnableCheckMode)
                            {
                                ConsoleEx.WriteLine(error);
                            }
                            else
                            {
                                throw new Exception(error);
                            }
                        }

                        additionalTemplates.Add(type, DefinitionFile.LoadFile(cn.Nodes[0]));
                    }
                }
                break;
                }
            }

            if (additionalTemplates.Count > 0)
            {
                file["AdditionalTemplates"] = additionalTemplates;
            }
        }
 private void NewLine()
 {
     ConsoleEx.WriteLine();
 }
Beispiel #27
0
        public void ConnectAsync(

            [ReplParam(
                 "rootAddress",
                 Caption = "Root Address",
                 Description = "Will be used to automatically determine the base address")]
            [ReplExample(
                 "connect http://example.com/",
                 Scope = ReplExampleScope.All,
                 Caption = "Connect to endpoint with default base address \"/\"")]
            string root = null,

            [ReplOption(
                 "baseAddress",
                 Caption = "Base Address",
                 Description = "Local address to connect to. Can be changed later with command `cd`")]
            [ReplNames("b")]
            [ReplExample(
                 "connect http://example.com/ --base api",
                 Scope = ReplExampleScope.Parent,
                 Caption = "Connect to given endpoint with given base address.")]
            string @base = null)
        {
            if (@base == null && root == null)
            {
                ConsoleEx.WriteLine(ConsoleColor.Red, "One of rootAddress or --base must be specified");
                return;
            }

            if (root != null && !Uri.IsWellFormedUriString(root, UriKind.Absolute))
            {
                ConsoleEx.WriteLine(ConsoleColor.Red, "Root address must be a valid absolute Url");
                return;
            }

            if (@base != null && !Uri.IsWellFormedUriString(@base, UriKind.RelativeOrAbsolute))
            {
                ConsoleEx.WriteLine(ConsoleColor.Red, "Base address must be a valid absolute or relative Url");
                return;
            }

            var rootAddress = root != null ? new Uri(root, UriKind.Absolute) : null;
            var baseAddress = @base != null ? new Uri(@base, UriKind.RelativeOrAbsolute) : new Uri("", UriKind.Relative);

            if (rootAddress == null && !baseAddress.IsAbsoluteUri)
            {
                ConsoleEx.WriteLine(ConsoleColor.Red, "When root address is missing, base address must be an absolute Url");
                return;
            }

            if (rootAddress != null && baseAddress != null && baseAddress.IsAbsoluteUri)
            {
                ConsoleEx.WriteLine(ConsoleColor.Red, "When root address is present, base address must be a relative Url");
                return;
            }

            if (rootAddress == null)
            {
                rootAddress = new Uri(baseAddress.GetLeftPart(UriPartial.Authority), UriKind.Absolute);
                baseAddress = new Uri(baseAddress.AbsolutePath);
            }

            State.RootAddress    = rootAddress;
            State.BaseAddress    = baseAddress;
            State.CurrentAddress = new Uri("", UriKind.Relative);
        }
Beispiel #28
0
        private static void OnMessageReceived(object sender, NetCoreEventArgs e)
        {
            try
            {
                // This is where you implement interaction.
                // Warning: Any error thrown in here will be caught by NetCore and handled by being displayed in the console.

                var message         = e.message;
                var simpleMessage   = message as NetCoreSimpleMessage;
                var advancedMessage = message as NetCoreAdvancedMessage;

                ConsoleEx.WriteLine(message.Type);
                switch (message.Type) //Handle received messages here
                {
                case RTCV.NetCore.Commands.Remote.AllSpecSent:
                {
                    //We still need to set the emulator's path
                    AllSpec.VanguardSpec.Update(VSPEC.EMUDIR, Hook.currentDir);
                    SyncObjectSingleton.FormExecute(() =>
                        {
                            Hook.UpdateDomains();
                        });
                }
                break;

                case RTCV.NetCore.Commands.Basic.SaveSavestate:
                    e.setReturnValue("");
                    break;

                case RTCV.NetCore.Commands.Basic.LoadSavestate:
                    e.setReturnValue(true);
                    break;

                case RTCV.NetCore.Commands.Remote.PreCorruptAction:

                    //SyncObjectSingleton.FormExecute(() =>
                    //{
                    //    lock (Hook.CorruptLock)
                    //    {
                    //        if (Hook.SuspendProcess)
                    //        {
                    //            if (!Hook.p?.Suspend() ?? true && !suspendWarned)
                    //            {
                    //                suspendWarned = (MessageBox.Show("Failed to suspend a thread!\nWould you like to continue to receive warnings?", "Failed to suspend thread", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes);
                    //            }
                    //        }

                    //        Hook.DontChangeMemoryProtection = true;
                    //        var count = 0;
                    //        foreach (var m in MemoryDomains.MemoryInterfaces.Values)
                    //        {
                    //            if (m.MD is ProcessMemoryDomain pmd)
                    //            {
                    //                if (!pmd.SetMemoryProtection(ProcessExtensions.MemoryProtection.ExecuteReadWrite))
                    //                    count++;
                    //            }
                    //        }

                    //        Console.WriteLine($"PreCorrupt\n" +
                    //                          $"Total domains: {MemoryDomains.MemoryInterfaces.Values.Count}\n" +
                    //                          $"Errors: {count}");
                    //    }
                    //});

                    break;

                case RTCV.NetCore.Commands.Remote.PostCorruptAction:
                    //SyncObjectSingleton.FormExecute(() =>
                    //{
                    //    lock (Hook.CorruptLock)
                    //    {
                    //        foreach (var m in MemoryDomains.MemoryInterfaces.Values)
                    //        {
                    //            if (m.MD is ProcessMemoryDomain pmd)
                    //            {
                    //                pmd.ResetMemoryProtection();
                    //                pmd.FlushInstructionCache();
                    //            }
                    //        }
                    //        Hook.DontChangeMemoryProtection = false;
                    //        if (Hook.SuspendProcess)
                    //        {
                    //            if (!Hook.p?.Resume() ?? true && !suspendWarned)
                    //            {
                    //                suspendWarned = (MessageBox.Show("Failed to resume a thread!\nWould you like to continue to receive warnings?", "Failed to resume thread", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes);
                    //            }
                    //        }
                    //    }
                    //});
                    break;

                case RTCV.NetCore.Commands.Remote.CloseGame:
                    break;

                case RTCV.NetCore.Commands.Remote.DomainGetDomains:
                    SyncObjectSingleton.FormExecute(() =>
                    {
                        e.setReturnValue(Hook.GetInterfaces());
                    });
                    break;

                case RTCV.NetCore.Commands.Remote.DomainRefreshDomains:
                    SyncObjectSingleton.FormExecute(() => { Hook.UpdateDomains(); });
                    break;

                case RTCV.NetCore.Commands.Remote.EventEmuMainFormClose:
                    SyncObjectSingleton.FormExecute(() =>
                    {
                        Environment.Exit(0);
                    });
                    break;

                case RTCV.NetCore.Commands.Remote.IsNormalAdvance:
                    e.setReturnValue(true);
                    break;

                case RTCV.NetCore.Commands.Remote.EventCloseEmulator:
                    Environment.Exit(-1);
                    break;
                }
            }
            catch (Exception ex)
            {
                if (VanguardCore.ShowErrorDialog(ex, true) == DialogResult.Abort)
                {
                    throw new AbortEverythingException();
                }
            }
        }
Beispiel #29
0
    void decompress()
    {
        string compressed = @"rZTBjpswEIbfxWe6msEhCZwaRT1EatVD91KteqBg0mhdg4xJG0W8e21jgtlCyra9eTzjmfnmH\/lKapWqpibJGwxIzr42x4MoSpI8fQlIqtSu\/HzqjJwVg6E9jyz9TpIrScVRXvZCkQQCouzl05WIT88nzu2xNqdDTpIQMYqCzn7Pzky7sQ1GAbChLwNMtalkEdDNRGzWyJ3SzYSg2+HOEZBKlhWT6kIS3UHKeZEqltuWRaM7RsBVqKPO7CBy9lM7TC51qZiNkSVntug63GyhtcP4G37Y0j\/wx+vl\/Ou7\/HSGH2f4Y+rz48CPAz+07durET\/Nnpm0z3tj789dj4eJmu39XtzK7My4rApuhu4i1CH9KsJvm+gSmr68Bt6J7Ju+esBoeBtOtEQnWvLa7NLAwzZ6UdfUqpuiMKhoS0hlX0d68sVJpPxm9WPHlR6jZFl5ZtKR6UJZWasBvJLMc2khjqXshJnc7o+V9mHsrMd+J03FW5YPTSdzltbKCdMPZAXoc4DPEYPPEYPPAfc5jF7LQNb\/AoKzICNBaOSDGOsGAtv7IAs5vL\/LcIQjCnyVHKMtEw3ns\/rQkT7U1wfh\/2ANX9LrsXDZllkJ+sCRUNZz+7Fm1V2YAGwCF6aX7sdJCJPLfAik\/QU=";

        ConsoleEx.DebugLog(" decompress : " + DeflateEx.Decompress(compressed));
    }
Beispiel #30
0
 public static void Run(Action action, string text = null)
 {
     ConsoleEx.SetTitle(text ?? String.Empty);
     action();
 }