コード例 #1
0
        public RandomHelpersTests()
        {
            _contextMock = new Mock <IHandlebars>();
            _contextMock.SetupGet(c => c.Configuration).Returns(new HandlebarsConfiguration());

            _sut = new RandomHelpers(_contextMock.Object);
        }
コード例 #2
0
        private static void CreateProducts(StoreContext context)
        {
            var categoryRepository = new CategoryRepository(context);
            var categoryIds        = categoryRepository.GetAll().ToArray();

            var productRepository = new ProductRepository(context);

            if (!productRepository.IsEmpty())
            {
                return;
            }

            for (var i = 1; i <= 100; i++)
            {
                productRepository.AddOrUpdate(new ProductModel {
                    Id                  = i,
                    Category            = RandomHelpers.GetRandom(categoryIds),
                    Title               = string.Format("محصول آزمایشی {0}", i),
                    Slug                = StringHelpers.Slugify(string.Format("Test Product {0}", i)),
                    Summary             = "خلاصه ای در مورد این محصول",
                    Description         = "توضیحات کامل مربوط به این محصول.",
                    Features            = "<ul><li>ویژگی شماره 1</li><li>ویژگی شماره 2</li><li>ویژگی شماره 3</li><li>و...</li></ul>",
                    MetaKeywords        = "کلمه 1, کلمه 2, کلمه 3",
                    MetaDescription     = "توضیحاتی در مورد محصول",
                    UnitPrice           = 55500 * i,
                    ReleaseDateUtc      = RandomHelpers.GetRandom(DateTime.UtcNow.AddYears(-2), DateTime.UtcNow),
                    LastModifiedDateUtc = RandomHelpers.GetRandom(DateTime.UtcNow.AddYears(-1), DateTime.UtcNow),
                    ViewsCount          = 0,
                    AddedToCartCount    = 0
                });
            }

            productRepository.SaveChanges();
        }
コード例 #3
0
        public void TestCasePositiveOnly12()
        {
            var arr    = RandomHelpers.SuffleSequence <int>(102, 200);
            var result = Solution.Solve(arr);

            Assert.Equal(1, result);
        }
コード例 #4
0
        public void CasHashRoundTrip()
        {
            CasHash hash      = RandomHelpers.CreateRandomCasHash();
            CasHash roundTrip = hash.ToMemoization().FromMemoization();

            Assert.Equal(hash, roundTrip);
        }
コード例 #5
0
        public void CasEntriesRoundTrip(int casEntryCount, int determinism)
        {
            CasEntries casEntries = RandomHelpers.CreateRandomCasEntries(casEntryCount, m_buildXLDeterminism[determinism]);
            CasEntries roundTrip  = casEntries.ToMemoization().FromMemoization();

            Assert.Equal(casEntries, roundTrip);
        }
コード例 #6
0
        public void WeakFingerprintHashToMemoization()
        {
            WeakFingerprintHash weak        = RandomHelpers.CreateRandomWeakFingerprintHash();
            Fingerprint         fingerprint = weak.ToMemoization();

            Assert.Equal(weak.ToArray(), fingerprint.ToByteArray());
        }
コード例 #7
0
    private Vector2 GenerateRelictVelocity()
    {
        Vector2 normal   = Vector2Helpers.DegreeToVector2(RandomHelpers.Range(relicAngle));
        float   velocity = TileHelpers.TileToWorld(RandomHelpers.Range(relicTileVelocity));

        return(normal * velocity);
    }
コード例 #8
0
        public unsafe NetworkInterfaceEndPoint CreateEndPoint(ushort port)
        {
            ManagerAccessHandle.Complete();
            int id = 0;

            if (port == 0)
            {
                while (id == 0)
                {
                    port = RandomHelpers.GetRandomUShort();
                    if (!m_IPCChannels.TryGetValue(port, out _))
                    {
                        id = m_IPCChannels.Count() + 1;
                        m_IPCChannels.TryAdd(port, id);
                    }
                }
            }
            else
            {
                if (!m_IPCChannels.TryGetValue(port, out id))
                {
                    id = m_IPCChannels.Count() + 1;
                    m_IPCChannels.TryAdd(port, id);
                }
            }

            var endpoint = default(NetworkInterfaceEndPoint);

            endpoint.dataLength   = 4;
            *(int *)endpoint.data = id;

            return(endpoint);
        }
コード例 #9
0
        public void CasHashToMemoization()
        {
            CasHash     hash        = RandomHelpers.CreateRandomCasHash();
            ContentHash contentHash = hash.ToMemoization();

            Assert.Equal(hash.BaseHash.RawHash.ToByteArray(), contentHash.ToHashByteArray());
        }
コード例 #10
0
    public void OnDeath(PlayerUnitController unit, Vector2 relictVelocity)
    {
        PlayerBaseStats stats         = unit.di.stats;
        SlimeType       poofType      = stats.SlimeType;
        Vector2         spawnPosition = unit.transform.position;

        SlimePoof slimePoof = poofs[poofType];

        slimePoof.SpawnAt(spawnPosition);

        foreach (SlimeType type in SlimeTypeHelpers.GetEnumerable())
        {
            if (stats.HasType(type))
            {
                SlimeRelict relict = relicts[type];
                relict.SpawnAt(spawnPosition);

                Vector2 velocity = GenerateRelictVelocity();

                relict.SetVelocity(velocity);
                relict.SetRotation(RandomHelpers.Range(relicRotationsPerSecond));
                //relictVelocity = Vector2.zero;
            }
        }
    }
コード例 #11
0
        // random utility, worth moving to Utilities.h?


        void RegenerateMap()
        {
            // regenerate map: clear and add random "rocks"
            _vehicle.Map.Clear();
            DrawRandomClumpsOfRocksOnMap(_vehicle.Map);
            ClearCenterOfMap(_vehicle.Map);

            // draw fences for first two demo modes
            if (MapDriver.DemoSelect < 2)
            {
                DrawBoundaryFencesOnMap(_vehicle.Map);
            }

            // randomize path widths
            if (MapDriver.DemoSelect == 2)
            {
                int   count          = _vehicle.Path.PointCount;
                bool  upstream       = _vehicle.PathFollowDirection > 0;
                int   entryIndex     = upstream ? 1 : count - 1;
                int   exitIndex      = upstream ? count - 1 : 1;
                float lastExitRadius = _vehicle.Path.Radii[exitIndex];
                for (int i = 1; i < count; i++)
                {
                    _vehicle.Path.Radii[i] = RandomHelpers.Random(4, 19);
                }
                _vehicle.Path.Radii[entryIndex] = lastExitRadius;
            }

            // mark path-boundary map cells as obstacles
            // (when in path following demo and appropriate mode is set)
            if (_usePathFences && (MapDriver.DemoSelect == 2))
            {
                DrawPathFencesOnMap(_vehicle.Map, _vehicle.Path);
            }
        }
コード例 #12
0
ファイル: MainWindow.xaml.cs プロジェクト: coman3/Experiments
        private void GenerateCubesButton_OnClick(object sender, RoutedEventArgs e)
        {
            if (Size > 256)
            {
                MessageBox.Show("Size must not be larger than 128", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            Clear();
            Noise.SetSeed(RandomHelpers.Random(0, int.MaxValue));
            CubeItems = new CubeItem[Size, Size];
            for (int x = 0; x < Size; x++)
            {
                for (int y = 0; y < Size; y++)
                {
                    var noiseValue = Noise.GetValue(x, y).Map(-1, 1, 0, 1000);
                    CubeItems[x, y] = new CubeItem()
                    {
                        IsFull = noiseValue > NoiseFilter
                    };
                }
            }

            DrawCubes();
        }
コード例 #13
0
        public void PinResultSuccessFromMemoization()
        {
            PinResult pinResult = PinResult.Success;
            Possible <string, Failure> maybe = pinResult.FromMemoization(RandomHelpers.CreateRandomCasHash(), CacheId);

            Assert.True(maybe.Succeeded);
            Assert.Equal(CacheId, maybe.Result);
        }
コード例 #14
0
ファイル: Generation.cs プロジェクト: afalz/NEAT
        private double GetSoftenFactor(double fitness, IEnumerable <IGenome> genomes)
        {
            double fitnessThreshold = RandomHelpers.GetRandomBiasingLow(1, 5);

            fitnessThreshold = genomes.Max(g => g.Fitness) / fitnessThreshold;

            return(fitness > fitnessThreshold ? new Random().Next(2, 4) : 1);
        }
コード例 #15
0
        public void PinResultErrorFromMemoization()
        {
            PinResult pinResult = new PinResult(ErrorMessage);
            Possible <string, Failure> maybe = pinResult.FromMemoization(RandomHelpers.CreateRandomCasHash(), CacheId);

            Assert.False(maybe.Succeeded);
            Assert.Contains(ErrorMessage, maybe.Failure.Describe());
        }
コード例 #16
0
ファイル: Generation.cs プロジェクト: afalz/NEAT
        private IGenome GetRandomGenomeBiasFitness(IEnumerable <IGenome> genomes)
        {
            double fitnessThreshold = RandomHelpers.GetRandomBiasingLow(1, 5);

            fitnessThreshold = genomes.Max(g => g.Fitness) / fitnessThreshold;

            return(genomes.OrderBy(g => g.Fitness).Where(g => g.Fitness >= fitnessThreshold).First());
        }
コード例 #17
0
        public void GetRandomAlphanumericString_Returns_String_Having_Requested_Length()
        {
            // ACT
            var result = RandomHelpers.GetRandomAlphanumericString(8);

            // ASSERT
            Assert.IsNotNull(result);
            Assert.AreEqual(8, result.Length);
        }
コード例 #18
0
        public void GetRandomAlphanumericString_Returns_Alphanumeric_String()
        {
            // ACT
            var result = RandomHelpers.GetRandomAlphanumericString(8);

            // ASSERT
            Assert.IsNotNull(result);
            Assert.IsTrue(result.All(char.IsLetterOrDigit));
        }
コード例 #19
0
        public void GetRandomAlphanumericString_Returns_Empty_String_When_Length_Equals_Zero()
        {
            // ACT
            var result = RandomHelpers.GetRandomAlphanumericString(0);

            // ASSERT
            Assert.IsNotNull(result);
            Assert.AreEqual(string.Empty, result);
        }
コード例 #20
0
 public static T GetRandomElement <T>(this T src) where T : struct
 {
     if (!typeof(T).IsEnum)
     {
         throw new ArgumentException(String.Format("Argument {0} is not an Enum", typeof(T).FullName));
     }
     T[] Arr = (T[])Enum.GetValues(src.GetType());
     return(Arr[RandomHelpers.Range(Arr.Length)]);
 }
コード例 #21
0
        private void RandomizeStartingPositionAndHeading()
        {
            // randomize position on a ring between inner and outer radii
            // centered around the home base
            float   rRadius      = RandomHelpers.Random(10, 50);
            Vector3 randomOnRing = Vector3Helpers.RandomUnitVectorOnXZPlane() * rRadius;

            Position = (Globals.HomeBaseCenter + randomOnRing);
            RandomizeHeadingOnXZPlane();
        }
コード例 #22
0
        public void BoundedRandomInt()
        {
            const int LOWER = -17;
            const int UPPER = 24;

            var rand = RandomHelpers.RandomInt(LOWER, UPPER);

            Assert.IsTrue(LOWER <= rand);
            Assert.IsTrue(UPPER >= rand);
        }
コード例 #23
0
        // xxx couldn't this be made more compact using localizePosition?
        /// <summary>
        /// Checks for intersection of the given spherical obstacle with a
        /// volume of "likely future vehicle positions": a cylinder along the
        /// current path, extending minTimeToCollision seconds along the
        /// forward axis from current position.
        ///
        /// If they intersect, a collision is imminent and this function returns
        /// a steering force pointing laterally away from the obstacle's center.
        ///
        /// Returns a zero vector if the obstacle is outside the cylinder
        /// </summary>
        /// <param name="v"></param>
        /// <param name="minTimeToCollision"></param>
        /// <returns></returns>
        public Vector3 SteerToAvoid(IVehicle v, float minTimeToCollision)
        {
            // Capsule x Sphere collision detection
            //http://www.altdev.co/2011/04/26/more-collision-detection-for-dummies/

            var capStart = v.Position;
            var capEnd   = v.PredictFuturePosition(minTimeToCollision);

            var alongCap  = capEnd - capStart;
            var capLength = alongCap.Length();

            //If the vehicle is going very slowly then simply test vehicle sphere against obstacle sphere
            if (capLength <= 0.05)
            {
                var distance = Vector3.Distance(Center, v.Position);
                if (distance < Radius + v.Radius)
                {
                    return(v.Position - Center);
                }
                return(Vector3.Zero);
            }

            var capAxis = alongCap / capLength;

            //Project vector onto capsule axis
            var b = Utilities.Clamp(Vector3.Dot(Center - capStart, capAxis), 0, capLength);

            //Get point on axis (closest point to sphere center)
            var r = capStart + capAxis * b;

            //Get distance from circle center to closest point
            var dist = Vector3.Distance(Center, r);

            //Basic sphere sphere collision about the closest point
            var inCircle = dist < Radius + v.Radius;

            if (!inCircle)
            {
                return(Vector3.Zero);
            }

            //avoidance vector calculation
            Vector3 avoidance = Vector3Helpers.PerpendicularComponent(v.Position - Center, v.Forward);

            //if no avoidance was calculated this is because the vehicle is moving exactly forward towards the sphere, add in some random sideways deflection
            if (avoidance == Vector3.Zero)
            {
                avoidance = -v.Forward + v.Side * 0.01f * RandomHelpers.Random();
            }

            avoidance  = Vector3.Normalize(avoidance);
            avoidance *= v.MaxForce;
            avoidance += v.Forward * v.MaxForce * 0.75f;
            return(avoidance);
        }
コード例 #24
0
        public IActionResult ForgotPassword([FromBody] JObject json)
        {
            try
            {
                JObject jObject = JsonConvert.DeserializeObject <JObject>(DBHelper.ParseString(json));
                if (jObject != null)
                {
                    string emailId = DBHelper.ParseString(jObject["emailId"]);
                    string IsAdmin = DBHelper.ParseString(jObject["IsAdmin"]);
                    if (!string.IsNullOrWhiteSpace(emailId))
                    {
                        if (iforgot.IsEmailExist(emailId, IsAdmin))
                        {
                            string resetCode = RandomHelpers.RandomString();
                            long   isUpdated = iforgot.UpdateForgotPasswordString(resetCode, emailId);
                            if (isUpdated > 0)
                            {
                                var HostingPath = env.ContentRootPath;

                                string clientEmail         = config.GetValue <string>("app_settings:ClientEmail");
                                string clientEmailPassword = config.GetValue <string>("app_settings:ClientEmailPassword");
                                string port     = config.GetValue <string>("app_settings:Port");
                                string mailHost = config.GetValue <string>("app_settings:SMTPURL");
                                string host     = this.Request.Host.Value;
                                string scheme   = this.Request.Scheme;
                                ForgotPasswordHelper.SendResetPasswordMail(emailId, resetCode, HostingPath, clientEmail, clientEmailPassword, port, mailHost, host, scheme);
                                return(Ok(ResponseHelper.Success(MessageConstants.ResetPassordLink)));
                            }
                            else
                            {
                                return(Ok(ResponseHelper.Error(MessageConstants.DataNotFound)));
                            }
                        }
                        else
                        {
                            return(Ok(ResponseHelper.Error(MessageConstants.CheckEmailId)));
                        }
                    }
                    else
                    {
                        return(Ok(ResponseHelper.Error(MessageConstants.CompulsoryData)));
                    }
                }
                else
                {
                    return(Ok(ResponseHelper.Error(MessageConstants.CompulsoryData)));
                }
            }
            catch (Exception ex)
            {
                LogHelper.ExceptionLog(ex.Message + "  :::::  " + ex.StackTrace);
                return(Ok(ResponseHelper.Error(ex.Message)));
            }
        }
コード例 #25
0
        public void SelectorResultSuccessFromMemoization()
        {
            WeakFingerprintHash weak           = RandomHelpers.CreateRandomWeakFingerprintHash();
            GetSelectorResult   selectorResult = new GetSelectorResult(Selector.Random(HashType.Vso0, FingerprintUtilities.FingerprintLength));
            Possible <BuildXLStrongFingerprint, Failure> maybeStrongFingerprint = selectorResult.FromMemoization(weak, CacheId);

            Assert.True(maybeStrongFingerprint.Succeeded);
            Assert.Equal(weak, maybeStrongFingerprint.Result.WeakFingerprint);
            Assert.Equal(selectorResult.Selector.ContentHash.FromMemoization(), maybeStrongFingerprint.Result.CasElement);
            Assert.Equal(selectorResult.Selector.Output, maybeStrongFingerprint.Result.HashElement.ToArray());
            Assert.Equal(CacheId, maybeStrongFingerprint.Result.CacheId);
        }
コード例 #26
0
        public void CasEntriesToMemoization(int casEntryCount, int determinism)
        {
            CasEntries casEntries = RandomHelpers.CreateRandomCasEntries(casEntryCount, m_buildXLDeterminism[determinism]);
            ContentHashListWithDeterminism contentHashListWithDeterminism = casEntries.ToMemoization();

            Assert.Equal(casEntries.Count, contentHashListWithDeterminism.ContentHashList.Hashes.Count);
            for (int i = 0; i < casEntries.Count; i++)
            {
                Assert.Equal(casEntries[i].ToMemoization(), contentHashListWithDeterminism.ContentHashList.Hashes[i]);
            }

            AssertDeterminismEqualEnough(casEntries.Determinism, contentHashListWithDeterminism.Determinism);
        }
コード例 #27
0
        private float GetWaitTime()
        {
            if (m_FSM.LastState == WanderStates.NotWandering || m_FSM.LastState == WanderStates.CannotWander)
            {
                return(0.1f);
            }

            if (randomizeWait)
            {
                return(RandomHelpers.RandomFloatWithinRange(0f, waitTime));
            }
            return(waitTime);
        }
コード例 #28
0
        public static void Shuffle <T>(this List <T> list)
        {
            int n = list.Count;

            while (n > 1)
            {
                n--;
                int k     = RandomHelpers.Next(n + 1);
                T   value = list[k];
                list[k] = list[n];
                list[n] = value;
            }
        }
コード例 #29
0
        /// <summary>
        /// Get time to wait before wandering again
        /// </summary>
        private float GetWaitTime()
        {
            if ((FSM.LastState == FStatesWander.NotWandering || FSM.LastState == FStatesWander.CannotWander) && !_waitOnStart)
            {
                return(0.1f);
            }

            if (_currentBotWanderComponent.randomizeWait)
            {
                return(RandomHelpers.RandomFloatWithinRange(_currentBotWanderComponent.WaitTime * .75f, _currentBotWanderComponent.WaitTime));
            }
            return(_currentBotWanderComponent.WaitTime);
        }
コード例 #30
0
        IEnumerator AutoSpawn(bool useSpawnerTransformValues = true)
        {
            yield return(new WaitForSeconds(RandomHelpers.RandomFloatWithinRange(timeFrom, timeTo)));

            yield return(new WaitUntil(() => !Paused));

            if (IsSpawning)
            {
                SpawningCount     = GetSpawnCount();
                SpawningRemaining = SpawningCount;
                trySpawn(useSpawnerTransformValues);
            }
        }