Esempio n. 1
0
        public int[] RandomIndex()
        {
            int[] index;
            int   x;
            int   y;

            x     = random.Next(Seed, 0, board.Width);
            y     = random.Next(Seed, 0, board.Height);
            index = new int[] { x, y };

            return(index);
        }
Esempio n. 2
0
        /// <summary>
        /// Attempts to find a random port to bind to
        /// </summary>
        /// <returns></returns>
        protected int FindOpenRandomPort()
        {
            var tryThis     = NextRandomPort();
            var seekingPort = true;

            while (seekingPort)
            {
                try
                {
                    Action($"Attempting to connect to random port {tryThis} on localhost");
                    using (var client = new TcpClient())
                    {
                        client.Connect(new IPEndPoint(IPAddress.Loopback, tryThis));
                    }

                    Thread.Sleep(RandomNumber.Next(1, 50));
                    tryThis = NextRandomPort();
                }
                catch
                {
                    Action($"HUZZAH! We have a port, squire! ({tryThis})");
                    seekingPort = false;
                }
            }

            return(tryThis);

            void Action(string s)
            {
                if (LogRandomPortDiscovery)
                {
                    Log(s);
                }
            }
        }
Esempio n. 3
0
        public void Should_Generate_Number_Between_50_And_100()
        {
            int num = RandomNumber.Next(50, 100);

            Assert.That(num, Is.GreaterThanOrEqualTo(50)
                        .And.LessThan(100));
        }
Esempio n. 4
0
        public void NextDouble_MaxValue_Multithreaded()
        {
            // Although it's an internal
            const double d = 42.0;

            RunMultithreaded(() => RandomNumber.Next(d));
        }
Esempio n. 5
0
        /// <summary>
        /// Function to Initialize a new Particle's properties
        /// </summary>
        /// <param name="cParticle">The Particle to be Initialized</param>
        public void InitializeParticleProperties(SpriteParticleSystemTemplateParticle cParticle)
        {
            //-----------------------------------------------------------
            // TODO: Initialize all of the Particle's properties here.
            // In addition to initializing the Particle properties you added, you
            // must also initialize the Lifetime property that is inherited from DPSFParticle
            //-----------------------------------------------------------

            // Set the Particle's Lifetime (how long it should exist for)
            cParticle.Lifetime = 2.0f;

            // Set the Particle's initial Position to be wherever the Emitter is
            cParticle.Position = Emitter.PositionData.Position;

            // Set the Particle's Velocity
            Vector3 sVelocityMin = new Vector3(-200, -200, 0);
            Vector3 sVelocityMax = new Vector3(200, -400, 0);

            cParticle.Velocity = DPSFHelper.RandomVectorBetweenTwoVectors(sVelocityMin, sVelocityMax);

            // Adjust the Particle's Velocity direction according to the Emitter's Orientation
            cParticle.Velocity = Vector3.Transform(cParticle.Velocity, Emitter.OrientationData.Orientation);

            // Set the Particle's Width and Height
            cParticle.Width  = RandomNumber.Next((int)mfSizeMin, (int)mfSizeMax);
            cParticle.Height = RandomNumber.Next((int)mfSizeMin, (int)mfSizeMax);
        }
        public override void DoMove()
        {
            int counterPositionOnScreen = 0;

            while (true)
            {
                RandomCheaterPlayerHandler.WaitOne();

                int Rand = RandomNumber.Next(MinValue, MaxValue);

                while (TestEnterdNumberInArray(Rand))
                {
                    Rand = RandomNumber.Next(MinValue, MaxValue);
                }

                AddEnterdNumberInArray(Rand);

                if (Rand == RezultValue)
                {
                    Win     = true;
                    EndGame = true;
                }

                Console.SetCursorPosition(55, 9 + counterPositionOnScreen);
                Console.Write("{0,4} {1}", Rand, Thread.CurrentThread.Name);
                counterPositionOnScreen++;

                HardWorkingCheaterPlayerHandler.Set();
            }
        }
Esempio n. 7
0
        public override void DoMove()
        {
            int counterPositionOnScreen = 0;

            while (true)
            {
                RandomCleverPlayerHandler.WaitOne();

                int Rand = RandomNumber.Next(MinValue, MaxValue);

                for (var i = 0; i < EnteredNumberLocal.Length; i++)
                {
                    if (Rand == EnteredNumberLocal[i])
                    {
                        Rand = RandomNumber.Next(MinValue, MaxValue);
                        i    = -1;
                    }
                }

                AddEnterdNumberInLocalArray(Rand);
                AddEnterdNumberInArray(Rand);

                if (Rand == RezultValue)
                {
                    Win     = true;
                    EndGame = true;
                }

                Console.SetCursorPosition(35, 9 + counterPositionOnScreen);
                Console.Write("{0,4} {1}", Rand, Thread.CurrentThread.Name);
                counterPositionOnScreen++;

                RandomCheaterPlayerHandler.Set();
            }
        }
Esempio n. 8
0
 public ACHInfo()
 {
     BankName        = Name.First() + "Bank";
     BankRouting     = Generics.RoutingNumberList[Generics.r.Next(0, 2)];
     BankAccountNum  = RandomNumber.Next(1001, 3000000000).ToString();
     BankAccountType = Generics.BankTypeList[RandomNumber.Next(0, 1)];
 }
Esempio n. 9
0
        public void GivenIHaveAGetDetailsForAConferenceRequestByUsernameWithAValidUsername(Scenario scenario)
        {
            string username;

            switch (scenario)
            {
            case Scenario.Valid:
            {
                username = _context.Test.Conference.Participants.First().Username;
                break;
            }

            case Scenario.Nonexistent:
                username = $"{RandomNumber.Next()}@hmcts.net";
                break;

            case Scenario.Invalid:
                username = "******";
                break;

            default: throw new ArgumentOutOfRangeException(nameof(scenario), scenario, null);
            }

            _context.Uri        = GetConferencesTodayForIndividual(username);
            _context.HttpMethod = HttpMethod.Get;
        }
Esempio n. 10
0
        /// <summary>
        /// Returns a single name with no regard for how many times that name may have been generated before.
        /// </summary>
        /// <returns>A single Markov-generated name</returns>
        public string GenerateWord(int wordLength = 0)
        {
            string nextName = GetRandomKey();

            // get a random name from the input samples
            // then generate a word length to aim at
            int minLength  = tokenLength + nextName.Length;
            int nameLength = wordLength;

            if (wordLength <= 0)
            {
                wordLength = RandomNumber.Next(minLength + tokenLength, GetRandomSampleWord().Length + minLength);
                nameLength = RandomNumber.Next(minLength, wordLength);
            }

            // generate the next name: a random substring of the random sample name
            // then get a random next letter based on the previous ngram

            while (nextName.Length < nameLength)
            {
                string token = nextName.Substring(nextName.Length - tokenLength, tokenLength);
                if (MarkovChain.ContainsKey(token))
                {
                    nextName += NextLetter(token);
                }
                else
                {
                    break;
                }
            }

            nextName = textInfo.ToTitleCase(nextName.ToLower());

            return(nextName);
        }
Esempio n. 11
0
        private char NextLetter(string token)
        {
            List <char> letters;

            // get all the letters that come after the passed-in token
            // then pick a random one and return it
            if (RandomNumber.NextDouble() > 0.05)
            {
                letters = MarkovChain[token];
            }
            else
            {
                letters = MarkovChain[GetRandomKey()];
            }

            int nextLetter = RandomNumber.Next(letters.Count);

            var c = letters[nextLetter];

            while (token.IsAllConsonants())
            {
                if (c.IsVowel())
                {
                    return(c);
                }
                else
                {
                    c = NextLetter(token);
                }
            }

            return(c);
        }
Esempio n. 12
0
        private static IEnumerable <ExternalIssueDetails> CreateExternalIssueDetails(IEnumerable <Issue> issues, BuildTemplate template)
        {
            var returnIssues = issues.Select(CreateRandomExternalIssue);
            var tempIssues   = new List <ExternalIssueDetails>();

            if (template.NestedIssueChance > 0 && template.NestedIssueDepth > 0)
            {
                for (int j = 0; j < template.NestedIssueDepth; j++)
                {
                    foreach (var externalIssueDetails in returnIssues.ToList())
                    {
                        if (RandomNumber.Next(0, 100) < template.NestedIssueChance)
                        {
                            var uniqueIssueId = Enumerable.Repeat(RandomNumber.Next(2000), 50)
                                                .First(r => returnIssues.All(i => Convert.ToInt16(i.Id) != r));
                            var parentIssue = CreateRandomExternalIssue(new Issue {
                                Id = uniqueIssueId.ToString()
                            });
                            parentIssue.SubIssues.Add(externalIssueDetails);
                            tempIssues.Add(parentIssue);
                        }
                    }
                    returnIssues = tempIssues;
                    tempIssues   = new List <ExternalIssueDetails>();
                }
            }
            return(returnIssues);
        }
Esempio n. 13
0
        private static IEnumerable <ChangeDetail> SetupBuildTypeAndBuilds(ITeamCityApi api, BuildTemplate template)
        {
            A.CallTo(() => api.GetBuildDetailsByBuildId(template.BuildId)).Returns(new BuildDetails {
                BuildTypeId = template.BuildId, Name = template.BuildName, Id = template.BuildId
            });
            var builds = Enumerable.Range(1, template.BuildCount).Select(i => new Build {
                BuildTypeId = template.BuildId, Id = i.ToString(), Number = String.Format(template.BuildNumberPattern, i)
            });
            var changeDetails = Enumerable.Range(1, template.BuildCount).Select(i => new ChangeDetail
            {
                Comment  = Company.CatchPhrase(),
                Id       = i.ToString(),
                Username = Name.FullName(),
                Version  = (100 + i * 10 + RandomNumber.Next(9)).ToString(),
                Files    = Enumerable.Range(1, RandomNumber.Next(1, 50)).Select(j => new FileDetails
                {
                    beforerevision = RandomNumber.Next(50, 500).ToString(),
                    afterrevision  = RandomNumber.Next(450, 700).ToString(),
                    File           = Path.GetTempFileName(),
                    relativefile   = Path.GetTempFileName()
                }).ToList(),
            });

            A.CallTo(() => api.GetBuildsByBuildType(template.BuildId)).Returns(builds);
            return(changeDetails);
        }
        public async Task InsertQueryDeleteLASets()
        {
            var client        = IocConfig.CreateHttpClient();
            var clientWrapper = new HttpClientWrapper(client, IocConfig.CreateJsonMediaTypeFormatter());
            var l             = new LookupApiService(clientWrapper, new SecurityApiService(clientWrapper));
            var las           = (await l.LocalAuthorityGetAllAsync()).ToArray();

            var subject = new LocalAuthoritySetRepository();

            for (int i = 0; i < 1000; i++)
            {
                var laIds = Enumerable.Range(0, RandomNumber.Next(0, 15)).Select(x => las.ElementAt(RandomNumber.Next(las.Length)).Id).ToArray();
                await subject.CreateAsync(new LocalAuthoritySet
                {
                    Ids   = laIds,
                    Title = Lorem.Sentence(2)
                });
            }

            //var result = await subject.GetAllAsync(100);
            //Assert.AreEqual(100, result.Items.Count());
            //foreach (var item in result.Items)
            //{
            //    Assert.IsNotNull(item.Ids);
            //    Assert.That(item.Ids.Count, Is.EqualTo(3));
            //}


            //result = await subject.GetAllAsync(1000);
            //foreach (var item in result.Items)
            //{
            //    await subject.DeleteAsync(item.RowKey);
            //}
        }
        public override void DoMove()
        {
            int counterPositionOnScreen = 0;

            while (true)
            {
                //   RandomPlayerHandler.WaitOne();

                int Rand = RandomNumber.Next(MinValue, MaxValue);

                AddEnterdNumberInArray(Rand);
                if (Rand == RezultValue)
                {
                    Win     = true;
                    EndGame = true;
                }
                lock (locker)
                {
                    Console.SetCursorPosition(20, 9 + counterPositionOnScreen);
                    Console.Write("{0,4} {1}", Rand, Thread.CurrentThread.Name);
                }
                counterPositionOnScreen++;
                if (EndGame)
                {
                    break;
                }
                //   RandomCleverPlayerHandler.Set();
            }
        }
Esempio n. 16
0
 public void GivenIHaveEnteredInvalidDetail(int ignore)
 {
     _ignore = ignore - 1;
     if (!(ignore == 1))
     {
         _spartaFormPage.Firstname = Name.First();
     }
     if (!(ignore == 2))
     {
         _spartaFormPage.Lastname = Name.Last();
     }
     if (!(ignore == 3))
     {
         _spartaFormPage.Age = RandomNumber.Next(99).ToString();
     }
     if (!(ignore == 4))
     {
         _spartaFormPage.Address = Address.StreetAddress();
     }
     if (!(ignore == 5))
     {
         _spartaFormPage.Postcode = Address.UkPostCode();
     }
     if (!(ignore == 6))
     {
         _spartaFormPage.EmailAddress = Internet.Email();
     }
     if (!(ignore == 7))
     {
         _spartaFormPage.PhoneNumber = Phone.Number();
     }
 }
Esempio n. 17
0
 protected void btnFakeNumber_Click(object sender, EventArgs e)
 {
     for (int i = 0; i < 10; i++)
     {
         Response.Write((i + 1) + " : " + RandomNumber.Next() + "<br><br>");
     }
 }
Esempio n. 18
0
        private int[] GetTarget(int[] source)
        {
            int[][]      neighbor = GetNeighbor(source);
            int          min      = GetMinDistance(distance, neighbor);
            List <int[]> targets  = new List <int[]>();

            foreach (int[] n in neighbor)
            {
                if (distance[n[0], n[1]] == min)
                {
                    targets.Add(n);
                }
            }

            SeedTag tag = GetComponent <IAutoExplore>().GetSeedTag();

            int[] target = (targets.Count > 1)
                ? targets[random.Next(tag, 0, targets.Count)]
                : targets[0];
            // The actor might dance around two grids of the same distance
            // repeatedly. We need to at least prevent PC from doing this.
            if (GetComponent <IAutoExplore>().IsValidDestination(target))
            {
                return(target);
            }
            return(null);
        }
Esempio n. 19
0
        private static async Task Seed(int n = 1000)
        {
            for (var i = 0; i < n; i++)
            {
                var context = new PlaygroundContext(new DbContextOptionsBuilder <PlaygroundContext>()
                                                    .UseNpgsql("Host=localhost;Database=playground;Username=postgres;Password=LocalDev123",
                                                               o => o.UseNodaTime())
                                                    .UseSnakeCaseNamingConvention()
                                                    .EnableSensitiveDataLogging().Options);

                var recipe = new Recipe(name: Company.Name());
                recipe.Description = Company.BS();
                recipe.CookTime    = Duration.FromMinutes(RandomNumber.Next(1, 60));
                recipe.PrepTime    = Duration.FromMinutes(RandomNumber.Next(1, 60));

                var ingredientCount = RandomNumber.Next(3, 8);
                for (var j = 0; j < ingredientCount; j++)
                {
                    var ingredientName = Name.FullName();
                    var existing       = await context.Ingredients.FirstOrDefaultAsync(i => i.Name == ingredientName);

                    var ingredient = existing ?? new Ingredient(ingredientName);

                    var units    = Enum.Random <UnitOfMeasure>();
                    var quantity = RandomNumber.Next(1, 16) / 4.0M;
                    recipe.AddIngredient(ingredient, units, quantity);
                }


                Console.WriteLine($"Entering recipe {i} of {n}");
                context.Recipes.Add(recipe);
                await context.SaveChangesAsync();
            }
        }
        public void InitializeParticleExplosion(DefaultSprite3DBillboardTextureCoordinatesParticle particle)
        {
            particle.Lifetime      = RandomNumber.Between(0.3f, 0.7f);
            particle.Color         = particle.StartColor = ExplosionColor;
            particle.EndColor      = Color.Black;
            particle.Position      = Emitter.PositionData.Position + new Vector3(RandomNumber.Next(-25, 25), RandomNumber.Next(-25, 25), RandomNumber.Next(-25, 25));
            particle.Velocity      = DPSFHelper.RandomNormalizedVector() * RandomNumber.Next(1, 50);
            particle.ExternalForce = new Vector3(0, 80, 0);  // We want the smoke to rise
            particle.Size          = particle.StartSize = 1; // Have the particles start small and grow
            particle.EndSize       = ExplosionParticleSize;

            // Give the particle a random initial orientation and random rotation velocity (only need to Roll the particle since it will always face the camera)
            particle.Rotation           = RandomNumber.Between(0, MathHelper.TwoPi);
            particle.RotationalVelocity = RandomNumber.Between(-MathHelper.PiOver2, MathHelper.PiOver2);

            // Randomly pick which texture coordinates to use for this particle
            Rectangle textureCoordinates;

            switch (RandomNumber.Next(0, 4))
            {
            default:
            case 0: textureCoordinates = _flameSmoke1TextureCoordinates; break;

            case 1: textureCoordinates = _flameSmoke2TextureCoordinates; break;

            case 2: textureCoordinates = _flameSmoke3TextureCoordinates; break;

            case 3: textureCoordinates = _flameSmoke4TextureCoordinates; break;
            }

            particle.SetTextureCoordinates(textureCoordinates);
        }
        private async Task SetUserNameForGivenScenario(Scenario scenario, bool hasSuitability = false, bool addSuitabilityAnswer = false)
        {
            switch (scenario)
            {
            case Scenario.Valid:
            {
                var seededHearing = await Context.TestDataManager.SeedVideoHearing(addSuitabilityAnswer);

                Context.TestData.NewHearingId = seededHearing.Id;
                NUnit.Framework.TestContext.WriteLine($"New seeded video hearing id: {seededHearing.Id}");
                var participants = seededHearing.GetParticipants();
                if (hasSuitability)
                {
                    _username = participants.First(p => p.Questionnaire != null && p.Questionnaire.SuitabilityAnswers.Any()).Person.Username;
                }
                else
                {
                    _username = participants.First().Person.Username;
                }
                Context.TestData.Participant = participants.First(p => p.Person.Username.Equals(_username));
                break;
            }

            case Scenario.Nonexistent:
                _username = $"{RandomNumber.Next()}@hmcts.net";
                break;

            case Scenario.Invalid:
                _username = "******";
                break;

            default: throw new ArgumentOutOfRangeException(nameof(scenario), scenario, null);
            }
        }
        private static void FillData(ModelBuilder modelBuilder)
        {
            var client = Builder <Client> .CreateListOfSize(100)
                         .All()
                         .With(c => c.Id            = Guid.NewGuid())
                         .With(c => c.FirstName     = Name.First())
                         .With(c => c.LastName      = Name.Last())
                         .With(c => c.ContactNumber = Phone.Number())
                         .With(c => c.EmailAddress  = Internet.Email())
                         .Build();

            modelBuilder.Entity <Client>().HasData(client);

            var boardGames = Builder <BoardGame> .CreateListOfSize(100)
                             .All()
                             .With(c => c.Id    = Guid.NewGuid())
                             .With(c => c.Name  = Lorem.GetFirstWord())
                             .With(c => c.Price = RandomNumber.Next(50, 250))
                             .Build();

            modelBuilder.Entity <BoardGame>().HasData(boardGames);

            var rnd     = new Random();
            var rentals = Builder <Rental> .CreateListOfSize(100)
                          .All()
                          .With(c => c.Id             = Guid.NewGuid())
                          .With(c => c.ClientId       = client.OrderBy(x => Guid.NewGuid()).First().Id)
                          .With(c => c.BoardGameId    = boardGames.OrderBy(x => Guid.NewGuid()).First().Id)
                          .With(c => c.ChargedDeposit = 15)
                          .With(c => c.Status         = (Status)rnd.Next(1, 2))
                          .Build();

            modelBuilder.Entity <Rental>().HasData(rentals);
        }
        public async Task GivenIHaveAGetPersonByContactEmailRequest(string personType, Scenario scenario)
        {
            switch (scenario)
            {
            case Scenario.Valid:
            {
                var seededHearing = await Context.TestDataManager.SeedVideoHearing();

                Context.TestData.NewHearingId = seededHearing.Id;
                NUnit.Framework.TestContext.WriteLine($"New seeded video hearing id: {seededHearing.Id}");
                if (personType.Equals("individual"))
                {
                    _username = seededHearing.GetParticipants().First(p => p.HearingRole.UserRole.IsIndividual).Person.ContactEmail;
                }
                else
                {
                    _username = seededHearing.GetParticipants().First().Person.ContactEmail;
                }
                break;
            }

            case Scenario.Nonexistent:
                _username = $"{RandomNumber.Next()}@hmcts.net";
                break;

            case Scenario.Invalid:
                _username = "******";
                break;

            default: throw new ArgumentOutOfRangeException(nameof(scenario), scenario, null);
            }
            Context.Uri        = GetPersonByContactEmail(_username);
            Context.HttpMethod = HttpMethod.Get;
        }
Esempio n. 24
0
        public static void Initialize()
        {
            if (_data == null)
            {
                _data = new List <User>();

                for (var i = 1; i <= 25; i++)
                {
                    _data.Add(new User
                    {
                        Id       = Guid.NewGuid(),
                        Name     = Name.First(),
                        LastName = Name.Last(),
                        Address  = Address.StreetAddress(),
                        City     = Address.City(),
                        Email    = Internet.Email(),
                        Birthday = Identification.DateOfBirth(),
                        MedicareBeneficaryNumber = Identification.MedicareBeneficiaryIdentifier(),
                        SocialSecurityNumber     = Identification.SocialSecurityNumber(),
                        Passport = Identification.UsPassportNumber(),
                        Salary   = RandomNumber.Next(2000, 12000)
                    });
                }
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Sends an extended WHO query asking for specific information about a single user
        /// or the users in a channel, and runs a callback when we have received the response.
        /// </summary>
        public void Who(string target, WhoxFlag flags, WhoxField fields, Action <List <ExtendedWho> > callback)
        {
            if (ServerInfo.ExtendedWho)
            {
                var whox = new List <ExtendedWho>();

                // Generate random querytype for WHO query
                int queryType = RandomNumber.Next(0, 999);

                // Add the querytype field if it wasn't defined
                var _fields = fields;
                if ((fields & WhoxField.QueryType) == 0)
                {
                    _fields |= WhoxField.QueryType;
                }

                string whoQuery = string.Format("WHO {0} {1}%{2},{3}", target, flags.AsString(), _fields.AsString(), queryType);
                string queryKey = string.Format("WHO {0} {1} {2:D}", target, queryType, _fields);

                RequestManager.QueueOperation(queryKey, new RequestOperation(whox, ro =>
                {
                    callback?.Invoke((List <ExtendedWho>)ro.State);
                }));
                SendRawMessage(whoQuery);
            }
        }
Esempio n. 26
0
        private static void GenEmployment(int nRecords)
        {
            for (int i = 0; i < nRecords; i++)
            {
                try
                {
                    Employee insertEmployee = new Employee();
                    insertEmployee.FirstName = Name.First();
                    insertEmployee.LastName  = Name.Last();
                    insertEmployee.Phone     = GenPhone();
                    insertEmployee.Email     = Internet.Email();
                    insertEmployee.City      = Faker.Address.City();
                    insertEmployee.Province  = GetRandProvince();
                    insertEmployee.Street    = Faker.Address.StreetAddress();

                    insertEmployee.PostalCode = GetPostalCode();
                    insertEmployee.Role       = SelectRandomFromString(new string[] { "kitchen assistant", "Helper" });
                    insertEmployee.Type       = "F";

                    if (insertEmployee.Type == "F")
                    {
                        insertEmployee.Salary         = RandomNumber.Next(500, 4000);
                        insertEmployee.EmploymentDate = DateTime.Now.AddDays(RandomNumber.Next(-500, 0));
                    }

                    insertEmployee.Create();
                }
                catch
                {
                }
            }
        }
Esempio n. 27
0
        public void InitializeParticleExplosion(DefaultSprite3DBillboardTextureCoordinatesParticle particle)
        {
            particle.Lifetime = 0.2f;
            particle.Color    = ExplosionColor;
            particle.Position = Emitter.PositionData.Position + new Vector3(RandomNumber.Next(-15, 15), RandomNumber.Next(-15, 15), RandomNumber.Next(-15, 15));
            particle.Size     = particle.StartSize = 1;
            particle.EndSize  = ExplosionParticleSize;

            // Randomly pick which texture coordinates to use for this particle
            Rectangle textureCoordinates;

            switch (RandomNumber.Next(0, 4))
            {
            default:
            case 0: textureCoordinates = _flash1TextureCoordinates; break;

            case 1: textureCoordinates = _flash2TextureCoordinates; break;

            case 2: textureCoordinates = _flash3TextureCoordinates; break;

            case 3: textureCoordinates = _flash4TextureCoordinates; break;
            }

            particle.SetTextureCoordinates(textureCoordinates);
        }
Esempio n. 28
0
        /// <summary>
        /// Example of how to create a Particle Initialization Function
        /// </summary>
        /// <param name="cParticle">The Particle to be Initialized</param>
        public void InitializeParticleProperties(DefaultQuadParticle cParticle)
        {
            //-----------------------------------------------------------
            // TODO: Initialize all of the Particle's properties here.
            // If you plan on simply using the default InitializeParticleUsingInitialProperties
            // Particle Initialization Function (see the LoadParticleSystem() function above),
            // then you may delete this function all together.
            //-----------------------------------------------------------

            // Set the Particle's Lifetime (how long it should exist for)
            cParticle.Lifetime = 2.0f;

            // Set the Particle's initial Position to be wherever the Emitter is
            cParticle.Position = Emitter.PositionData.Position;

            // Set the Particle's Velocity
            Vector3 sVelocityMin = new Vector3(-50, 50, -50);
            Vector3 sVelocityMax = new Vector3(50, 100, 50);

            cParticle.Velocity = DPSFHelper.RandomVectorBetweenTwoVectors(sVelocityMin, sVelocityMax);

            // Adjust the Particle's Velocity direction according to the Emitter's Orientation
            cParticle.Velocity = Vector3.Transform(cParticle.Velocity, Emitter.OrientationData.Orientation);

            // Give the Particle a random Size
            // Since we have Size Lerp enabled we must also set the Start and End Size
            cParticle.Width      = cParticle.StartWidth = cParticle.EndWidth =
                cParticle.Height = cParticle.StartHeight = cParticle.EndHeight = RandomNumber.Next(10, 50);

            // Give the Particle a random Color
            // Since we have Color Lerp enabled we must also set the Start and End Color
            cParticle.Color = cParticle.StartColor = cParticle.EndColor = DPSFHelper.RandomColor();
        }
 private static IEnumerable <char> Transform(string s, bool letterify, bool numerify, bool replaceVariables)
 {
     for (var index = 0; index < s.Length; index++)
     {
         char c = s[index];
         if (numerify && c == '#')
         {
             yield return(RandomNumber.Next(0, 10).ToString()[0]);
         }
         else if (letterify && c == '?')
         {
             yield return(ALPHABET.Random());
         }
         else if (replaceVariables && c == '{' && char.IsLetter(s[++index]))
         {
             string value = GetVariableValue(s, ref index);
             foreach (char chValue in value)
             {
                 yield return(chValue);
             }
         }
         else
         {
             yield return(c);
         }
     }
 }
Esempio n. 30
0
        /// <summary>
        /// Deleting multi users.
        /// </summary>
        /// <param name="Ids">List of users' ids to delete.</param>
        /// <returns>
        /// <para>Tuble of bool, string.</para>
        /// <para>Fisrt is result: represent result statue.</para>
        /// <para>Second is errorMessage: represent error message when something went wrong.</para>
        /// </returns>
        internal async static Task <(bool result, string errorMessage)> DeleteMultiUsers(List <string> Ids)
        {
            // Simulate a data store write latency.
            await Task.Delay(RandomNumber.Next(50 * Ids.Count));

            string failedUsers = "";

            for (int i = 0; i < Ids.Count; i++)
            {
                // Seraching for user with the giving id.
                int userIndex = AllUsres.FindIndex((x) => x.Id == Ids[i]);
                if (userIndex > -1)
                {
                    // Deleting the user.
                    AllUsres.RemoveAt(userIndex);
                }
                else
                {
                    failedUsers += $"'{Ids[i]}', ";
                }
            }

            // Check if all users deleted successfully or not, in this case return an error message contains failed deleted users' ids.
            if (string.IsNullOrEmpty(failedUsers))
            {
                return(true, "");
            }
            else
            {
                failedUsers = failedUsers.Substring(0, failedUsers.Length - 2);
                return(false, $"Can't find user with these ids {failedUsers}!");
            }
        }
Esempio n. 31
0
        public void Can_Generate_Single_Number_Within_One_Number_Range()
        {
            var random = new RandomNumber();

            var res = random.Next(3, 3);

            Assert.Equal(3, res);
        }
Esempio n. 32
0
        public void Can_Generate_Single_Numbers_Within_Range()
        {
            var random = new RandomNumber();

            var res = random.Next(3, 6);

            Assert.InRange(res, 3, 6);
        }