public IEnumerable <IDeploymentChromosome> Cross(IEnumerable <IDeploymentChromosome> parents)
        {
            var first  = parents.First();
            var second = parents.ElementAt(1);

            var firstGeneIndex  = _randomProvider.GetRandom(0, first.Genes.Count);
            var secondGeneIndex = _randomProvider.GetRandom(0, second.Genes.Count);

            yield return(Cross(first, second, firstGeneIndex, secondGeneIndex));

            yield return(Cross(second, first, secondGeneIndex, firstGeneIndex));
        }
        public void Cross_WithNoMutation_Returns_CorrectOffspring()
        {
            _mutationOperator = A.Fake <IMutation>();
            _randomProvider   = A.Fake <IRandomProvider>();
            A.CallTo(() => _randomProvider.GetRandom()).WithAnyArguments().Returns(1);
            _mutationProbability = 0;
            ConstructGeneticAlgorithm();

            var deploymentModel = CreateDeploymentModel();

            var genes = new[]
            {
                new DeploymentGene(new FeatureIdentifier("a"), new MicroserviceIdentifier("a"))
            };

            var chromosomes = new[]
            {
                new DeploymentChromosome(deploymentModel.FeatureModel, genes),
                new DeploymentChromosome(deploymentModel.FeatureModel, genes),
            };

            var result = _testGeneticAlgorithm.Mutation(chromosomes);

            A.CallTo(() => _mutationOperator.Mutate(null)).WithAnyArguments().MustNotHaveHappened();
            CollectionAssert.AreEqual(chromosomes, result);
        }
Example #3
0
        public async Task <ServerHelloRequest> ClientHelloWithCookie(ISession session, ClientHelloWithCookieRequest request)
        {
            _logger.Verbose(
                $"Handling {nameof(ClientHelloWithCookieRequest)} " +
                $"(CertificateResponseId={request.CertificateResponseId}, " +
                $"Random='{BitConverter.ToString(request.Random)}', " +
                $"Cookie='{BitConverter.ToString(request.Cookie)}')."
                );
            if (!request.Cookie.SequenceEqual(session.Cookie))
            {
                _logger.Warning(
                    $"Session sent {nameof(ClientHelloWithCookieRequest)} with a mismatching cookie " +
                    $"(EndPoint='{session.EndPoint}', " +
                    $"Cookie='{BitConverter.ToString(request.Cookie)}', " +
                    $"Expected='{BitConverter.ToString(session.Cookie ?? new byte[0])}')."
                    );
                return(null);
            }
            if (!request.Random.SequenceEqual(session.ClientRandom))
            {
                _logger.Warning(
                    $"Session sent {nameof(ClientHelloWithCookieRequest)} with a mismatching client random " +
                    $"(EndPoint='{session.EndPoint}', " +
                    $"Random='{BitConverter.ToString(request.Random)}', " +
                    $"Expected='{BitConverter.ToString(session.ClientRandom ?? new byte[0])}')."
                    );
                return(null);
            }

            // Generate a server random
            session.ServerRandom = _randomProvider.GetRandom();

            // Generate a key pair
            var keyPair = _diffieHellmanService.GetECKeyPair();

            session.ServerPrivateKeyParameters = keyPair.PrivateKeyParameters;

            // Generate a signature
            var certificate = _certificateProvider.GetCertificate();
            var signature   = MakeSignature(session.ClientRandom, session.ServerRandom, keyPair.PublicKey);

            await _messageDispatcher.Send(session, new ServerCertificateRequest()
            {
                RequestId    = session.GetNextRequestId(),
                ResponseId   = request.CertificateResponseId,
                Certificates = new List <byte[]>()
                {
                    certificate.RawData
                }
            });

            return(new ServerHelloRequest()
            {
                Random = session.ServerRandom,
                PublicKey = keyPair.PublicKey,
                Signature = signature
            });
        }
        public GameObject Spawn()
        {
            var randomItem  = _randomItemProvider.GetRandom();
            var spawnedItem = Instantiate(randomItem, transform.position, Quaternion.identity);

            spawnedItem.SetActive(ShouldActivateOnCreation);

            return(spawnedItem);
        }
        public IDeploymentChromosome Mutate(IDeploymentChromosome deployment)
        {
            var genes           = deployment.Genes;
            var microserviceIds = genes.Select(g => new MicroserviceIdentifier(g.FeatureId.ToString())).ToArray();
            var newGenes        = new List <IDeploymentGene>();

            foreach (var gene in genes)
            {
                var clonedGene = new DeploymentGene(gene.FeatureId, microserviceIds[_randomProvider.GetRandom(0, microserviceIds.Length)]);
                newGenes.Add(clonedGene);
            }
            return(deployment.UpdateGenes(newGenes));
        }
        public static IEnumerable <T> Shuffle <T>(this IEnumerable <T> list, IRandomProvider randomProvider)
        {
            var source = list?.ToList() ?? throw new ArgumentNullException(nameof(list));

            _ = randomProvider ?? throw new ArgumentNullException(nameof(randomProvider));

            var shuffled = new List <T>();

            while (source.Any())
            {
                var nextIndex   = randomProvider.GetRandom(min: 0, max: source.Count);
                var currentItem = source.ElementAt(nextIndex);
                source.Remove(currentItem);
                shuffled.Add(currentItem);
            }
            return(shuffled);
        }
Example #7
0
 private string GenerateOtpInternal(OtpOptions otpOptions)
 {
     if (!otpOptions.ShouldBeCryptographicallyStrong)
     {
         _randomProvider = new SimpleRandomProvider();
     }
     else
     {
         _randomProvider = new CryptoRandomProvider();
     }
     char[] charset = new char[] { };
     if (otpOptions.OtpContents.HasFlag(OtpContents.Number))
     {
         charset = Enumerable.Range(0, 9).Select(x => char.Parse(x.ToString())).ToArray();
     }
     return(_randomProvider.GetRandom(otpOptions.Length, charset));
 }
Example #8
0
        public void HandleRequest(RequestModel requestModel, IOutputBoundary <ResponseModel> outputBoundary)
        {
            var game   = gameRepository.GetGame(requestModel.GameIdentifier);
            var circle = circleRepository.GetCircle();
            var space  = circle.GetSpace(randomProvider.GetRandom(0, circle.CountSpaces()));

            game.HandleSpace(space);
            gameRepository.SaveGame(requestModel.GameIdentifier, game);
            var resultDescription = game.RequestLetter ? game.LetterDollarAmount.Value.ToString() : space.Type.ToString();

            outputBoundary.HandleResponse(new ResponseModel()
            {
                ResultDescription = resultDescription,
                RequestLetter     = game.RequestLetter,
                CurrentPlayerName = game.CurrentPlayer.Name
            });
        }