private void Clasterization()
        {
            foreach (var creature in creatures)
            {
                creature.species = null;
            }

            for (int i = 0; i < species.Count; i++)
            {
                Species spice = species[i];
                spice.amount = 0;
                spice.creatures.Clear();
                TryAddAllToSpecies(spice, spice.median);
                if (spice.amount == 0)
                {
                    species.RemoveAt(i);
                    i--;
                }
                RecalculateMedian(spice);
            }

            for (int i = 0; i < creatures.Count; i++)
            {
                var creature = creatures[i];
                if (creature.species == null)
                {
                    Species newSpec = new Species(RandomWordGenerator.GenerateName());
                    newSpec.median = creature.parameters.ToVector3();
                    species.Add(newSpec);
                    TryAddAllToSpecies(newSpec, newSpec.median);
                }
            }
        }
        public void TestBoundaryLanguages(int k)
        {
            var lengthsBoundary = Enumerable.Range(1, 10).Select(n => n * 100).ToArray();
            var strategy        = new RemoveBorderStrategy();
            var e              = new RationalNumber(k, k - 1);
            var detector       = new RepetitionDetector(new StringBuilder(), e, false);
            var generator      = new RandomCharGenerator(k);
            var charsGenerated = 0;
            var times          = new List <long>();
            var coefs          = new List <double>();
            var sw             = Stopwatch.StartNew();

            foreach (var length in lengthsBoundary)
            {
                RandomWordGenerator.Generate(detector, length, strategy, generator);
                charsGenerated += RandomWordGenerator.Statistics.CharsGenerated;
                times.Add(sw.ElapsedMilliseconds);
                coefs.Add(charsGenerated * 1.0 / length);
            }
            sw.Stop();
            Console.WriteLine((string)"Alphabet size = {0}, e = {1}+", (object)k, (object)e);
            for (var i = 0; i < lengthsBoundary.Length; ++i)
            {
                Console.WriteLine("\tLength: {0}, Time: {1} ms, Conversion coeff: {2}", lengthsBoundary[i], times[i], coefs[i]);
            }
        }
Exemple #3
0
        public async Task <GameWrapperClass> Get()
        {
            IUniqueIdGen     idGen   = new UniqueIdGen <GameWrapperClass>(repo);
            IWordGenerator   wordGen = new RandomWordGenerator();
            GameWrapperClass newGame = new  GameWrapperClass((await idGen.GetUniqueIdAsync(idLengthPolicy)), (await wordGen.GetWordAsync()), triesNo);
            await repo.WriteAsync(newGame);

            return(newGame);
        }
Exemple #4
0
    public static CardDeck NewDeck(string name)
    {
        CardDeck deck = new CardDeck(new List <int>());

        deck.name = name == string.Empty ? RandomWordGenerator.CreateRandomWordNumberCombination() : name;
        SaveDeck(deck);
        CollectionManager.currentDecks.Add(deck);
        return(deck);
    }
 public DictionaryEditViewModel(RandomWordGenerator randomWordGenerator)
 {
     ViewLogCommand           = new RelayCommand(RunViewLog, CanExecuteViewLog);
     RandomizeSettingsCommand = new RelayCommand(RunRandomizeSettings, CanExecuteRandomizeSettings);
     GenerateCommand          = new RelayCommand(RunGenerate, CanExecuteGenerate);
     this.randomWordGenerator = randomWordGenerator;
     this.randomWordGenerator.GenerateChanged   += RandomWordGenerator_GenerateChanged;
     this.randomWordGenerator.GenerateCompleted += RandomWordGenerator_GenerateCompleted;
 }
        public void Test(int alphabet, int numerator, int denominator, bool detectEqual, Type detectorType, int length)
        {
            var generator = new RandomCharGenerator(alphabet);
            var detector  = GetDetector(detectorType, detectEqual, new RationalNumber(numerator, denominator));

            detector.Reset();
            var sw = Stopwatch.StartNew();

            RandomWordGenerator.Generate(detector, length, new RemoveBorderStrategy(), generator);
            sw.Stop();
            Console.WriteLine("Length: {0}\n\tTime: {1} ms\n\tConversion coeff: {2:0.000000}", length, sw.ElapsedMilliseconds, RandomWordGenerator.Statistics.CharsGenerated * 1.0 / length);
        }
        public void WordNoRevealLetterTest()
        {
            IRandomGenerator random = new RandomGenerator();

            string[]             words = { "test" };
            IRandomWordGenerator randomWordGenerator = new RandomWordGenerator(random, words);
            Word word = new Word(randomWordGenerator);

            string actual   = word.RevealLetter('k');
            string expected = "t _ _ t ";

            Assert.AreEqual(expected, actual);
        }
        public void WordNumberOfLetterTest()
        {
            IRandomGenerator random = new RandomGenerator();

            string[]             words = { "test" };
            IRandomWordGenerator randomWordGenerator = new RandomWordGenerator(random, words);
            Word word = new Word(randomWordGenerator);

            int actual   = word.NumberOfLetter('e');
            int expected = 1;

            Assert.AreEqual(expected, actual);
        }
        public void WordNotContainsLetterTest()
        {
            IRandomGenerator random = new RandomGenerator();

            string[]             words = { "test" };
            IRandomWordGenerator randomWordGenerator = new RandomWordGenerator(random, words);
            Word word = new Word(randomWordGenerator);

            bool actual   = word.ContainsLetter('k');
            bool expected = false;

            Assert.AreEqual(expected, actual);
        }
        public void MaskedWordTest()
        {
            IRandomGenerator random = new RandomGenerator();

            string[]             words = { "test" };
            IRandomWordGenerator randomWordGenerator = new RandomWordGenerator(random, words);
            Word word = new Word(randomWordGenerator);

            string actual   = word.MaskedWord;
            string expected = "t _ _ t ";

            Assert.AreEqual(expected, actual);
        }
Exemple #11
0
        public NewSearchViewModel()
        {
            //TODO: Dummy data for UI testing, get rid
            Random rnd = new Random();

            WorkingSets = new ObservableCollection <WorkingSet>();
            for (int i = 0; i < 10; i++)
            {
                WorkingSet thisSet = new WorkingSet()
                {
                    Name        = "Test working set: " + i.ToString("000"),
                    Description = RandomWordGenerator.GenerateRandomText(rnd.Next(5, 10), CaseOption.LowerCase, NumberOption.NoNumbers)
                };

                int fileCount = rnd.Next(1000);
                for (int j = 0; j < fileCount; j++)
                {
                    thisSet.TrackedFiles.Add(new TrackedFile());
                }
                WorkingSets.Add(thisSet);
            }

            AvailableRegExTemplates = new ObservableCollection <RegExTemplate>();
            SelectedRegExTemplates  = new ObservableCollection <RegExTemplate>();
            SelectedRegExTemplates.Add(new RegExTemplate()
            {
                Syntax      = @"(\b(07[0-9]{9}|0[1-3][0-9]{9})\b)",
                Title       = "UK phones",
                Description = "UK landline or mobile numbers with no spaces, as a distinct word"
            });
            AvailableRegExTemplates.Add(new RegExTemplate()
            {
                Syntax      = @"(?i)(\b[a-z]{5}\d{2}\b)",
                Title       = "Ref number on its own",
                Description = "5 letters and 2 numbers, as a distinct word"
            });
            AvailableRegExTemplates.Add(new RegExTemplate()
            {
                Syntax      = @"(?i)([a-z]{5}\d{2})",
                Title       = "Ref number within other words",
                Description = "5 letters and 2 numbers"
            });
            AvailableRegExTemplates.Add(new RegExTemplate()
            {
                Syntax      = @"([A-Z])",
                Title       = "All uppercase letters",
                Description = "Just all uppercase letters"
            });
        }
        public void WordCheckIfWordIsRevealedReturnFalseTest()
        {
            IRandomGenerator random = new RandomGenerator();

            string[]             words = { "test" };
            IRandomWordGenerator randomWordGenerator = new RandomWordGenerator(random, words);
            Word word = new Word(randomWordGenerator);

            word.RevealLetter('e');

            bool actual   = word.CheckIfWordIsRevealed();
            bool expected = false;

            Assert.AreEqual(expected, actual);
        }
 public static IEnumerable <EventDefinition> GetEventDefintion()
 {
     return(new List <EventDefinition>
     {
         new EventDefinition(1, "Publish a regular event",
                             new SomethingCrazyHappendEvent
         {
             What = RandomWordGenerator.Generate()
         }
                             ),
         new EventDefinition(2, "Publish a event that correlates",
                             new CorrelationEventOne()
                             ),
         new EventDefinition(3, "Publish an event that causes exception",
                             new ThisThrowsAnExceptionEvent()
                             ),
     });
 }
Exemple #14
0
        private void Reload()
        {
            CaseOption caseOption = CaseOption.LowerCase;

            if (UpperCaseChecked)
            {
                caseOption = CaseOption.AllCaps;
            }
            if (LowerCaseChecked)
            {
                caseOption = CaseOption.LowerCase;
            }
            if (TitleCaseChecked)
            {
                caseOption = CaseOption.TitleCase;
            }
            if (RandomCaseChecked)
            {
                caseOption = CaseOption.RandomCase;
            }

            NumberOption numberOption = NumberOption.NumbersAsWords;

            if (AllNumbersChecked)
            {
                numberOption = NumberOption.AllNumbers;
            }
            if (NoNumbersChecked)
            {
                numberOption = NumberOption.NoNumbers;
            }
            if (NumbersInsideChecked)
            {
                numberOption = NumberOption.NumbersInWords;
            }
            if (NumbersReplaceChecked)
            {
                numberOption = NumberOption.NumbersAsWords;
            }

            RandomText = RandomWordGenerator.GenerateRandomText
                             (WordCount, caseOption, numberOption);
        }
        private static void Calculate(int runs, Detector detector, int length,
                                      IRemoveStrategy removeStrategy, ICharGenerator generator, IGeneratorLogger logger,
                                      StreamWriter output)
        {
            Console.WriteLine("Conversion for length = {0}", length);
            var conversionCoeffs = new double[runs];
            var times            = new long[runs];

            for (var run = 0; run < runs; ++run)
            {
                detector.Reset();
                var sw = Stopwatch.StartNew();
                RandomWordGenerator.Generate(detector, length, removeStrategy, generator, logger);
                sw.Stop();
                times[run]            = sw.ElapsedMilliseconds;
                conversionCoeffs[run] = RandomWordGenerator.Statistics.CharsGenerated * 1.0 / length;
                Console.WriteLine("\rRun {0} generated in {1} ms", run + 1, sw.ElapsedMilliseconds);
            }
            output.WriteLine("{0} {1} {2} {3}", runs, length, conversionCoeffs.Average(), times.Average());
            output.Flush();
        }
Exemple #16
0
        public AccountRegistrationStatus RegisterAccount(PlatformUser user,
                                                         string accountCurrency, int startBalance, decimal maxLeverage, string completedPassword, bool autoSignIn)
        {
            // проверить заполнение логина-почты-баланса-плеча
            if (user.Login.Length < PlatformUser.LoginLenMin ||
                user.Login.Length > PlatformUser.LoginLenMax)
            {
                return(AccountRegistrationStatus.IncorrectLogin);
            }
            if (user.Email.Length < PlatformUser.EmailLenMin ||
                user.Email.Length > PlatformUser.EmailLenMax)
            {
                return(AccountRegistrationStatus.IncorrectEmail);
            }
            if (!PlatformUser.CheckLoginSpelling(user.Login))
            {
                return(AccountRegistrationStatus.IncorrectLogin);
            }
            if (startBalance < Account.MinimumStartDepo || startBalance > Account.MaximumStartDepo)
            {
                return(AccountRegistrationStatus.IncorrectBalance);
            }
            if (maxLeverage < 0)
            {
                maxLeverage = 0;
            }
            else if (maxLeverage > Account.MaximumDepoLeverage)
            {
                maxLeverage = Account.MaximumDepoLeverage;
            }
            long hash;

            if (!TradingContractDictionary.Instance.GetTickers(out hash).Any(c => c.ActiveBase == accountCurrency ||
                                                                             c.ActiveCounter == accountCurrency))
            {
                return(AccountRegistrationStatus.WrongCurrency);
            }

            // сгенерировать пароль
            if (string.IsNullOrEmpty(completedPassword))
            {
                string pwrd;
                while (true)
                {
                    pwrd = RandomWordGenerator.Password(new Random().Next(2) + 2);
                    if (pwrd.Length < PlatformUser.PasswordLenMin || pwrd.Length > PlatformUser.PasswordLenMax)
                    {
                        continue;
                    }
                    break;
                }
                user.Password = pwrd;
            }
            else
            {
                user.Password = completedPassword;
            }
            user.RegistrationDate = DateTime.Now;
            Logger.InfoFormat("RegisterAccount (email={0}, login={1}, pwrd={2}{3})",
                              user.Email, user.Login, user.Password, string.IsNullOrEmpty(completedPassword) ? " (auto)" : "");
            if (string.IsNullOrEmpty(user.Title))
            {
                user.Title = string.IsNullOrEmpty(user.Name) ? user.Login : user.Name;
            }
            user.RoleMask = UserRole.Trader;

            // попытка создать пользователя и открыть счет
            using (var ctx = DatabaseContext.Instance.Make())
            {
                try
                {
                    // проверка дублирования
                    var existUser = ctx.PLATFORM_USER.FirstOrDefault(u => u.Email.Equals(user.Email, StringComparison.OrdinalIgnoreCase));
                    Logger.InfoFormat("Регистрация пользователя: email {0} занят", user.Email);
                    if (existUser != null)
                    {
                        return(AccountRegistrationStatus.DuplicateEmail);
                    }
                    existUser = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == user.Login);
                    if (existUser != null)
                    {
                        return(AccountRegistrationStatus.DuplicateLogin);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error("Ошибка в RegisterAccount(checks)", ex);
                    return(AccountRegistrationStatus.ServerError);
                }

                // в рамках одной транзакции создать логин и счет
                //using (var transaction = ctx.Connection.BeginTransaction())
                {
                    DbTransaction transaction;
                    try
                    {
                        if (((IObjectContextAdapter)ctx).ObjectContext.Connection.State != ConnectionState.Open)
                        {
                            ((IObjectContextAdapter)ctx).ObjectContext.Connection.Open();
                        }
                        Logger.Info("Connection's opened");
                        transaction = ((IObjectContextAdapter)ctx).ObjectContext.Connection.BeginTransaction();
                    }
                    catch (Exception ex)
                    {
                        Logger.Error("RegisterAccount - ошибка в ctx.Connection.BeginTransaction", ex);
                        return(AccountRegistrationStatus.ServerError);
                    }

                    try
                    {
                        // добавить пользователя
                        var userBase = LinqToEntity.UndecoratePlatformUser(user);
                        ctx.PLATFORM_USER.Add(userBase);

                        // добавить счет
                        var account = new ACCOUNT
                        {
                            AccountGroup = defaultDemoAccountGroupCode,
                            MaxLeverage  = maxLeverage,
                            Balance      = startBalance,
                            UsedMargin   = 0,
                            Currency     = accountCurrency,
                            Description  = string.Format("demo account for {0}", user.Login),
                            Status       = (int)Account.AccountStatus.Created,
                            TimeCreated  = DateTime.Now,
                        };
                        try
                        {
                            ctx.ACCOUNT.Add(account);
                            // сохранить изменения (добавление пользователя и счета, нужны ID)
                            ctx.SaveChanges();
                        }
                        catch (Exception ex)
                        {
                            Logger.Error("RegisterAccount - ACCOUNT adding error", ex);
                            return(AccountRegistrationStatus.ServerError);
                        }


                        // добавить кошелек
                        try
                        {
                            var wallet = new WALLET
                            {
                                Balance  = 0,
                                Currency = accountCurrency,
                                Password = user.Password,
                                User     = userBase.ID
                            };
                            ctx.WALLET.Add(wallet);
                        }
                        catch (Exception ex)
                        {
                            Logger.Error("RegisterAccount - WALLET adding error", ex);
                            return(AccountRegistrationStatus.ServerError);
                        }

                        // пользователь-счет
                        var userAccount = new PLATFORM_USER_ACCOUNT
                        {
                            PlatformUser = userBase.ID,
                            Account      = account.ID,
                            RightsMask   = (int)AccountRights.Управление
                        };
                        ctx.PLATFORM_USER_ACCOUNT.Add(userAccount);

                        // перевод на счет
                        var trans = new BALANCE_CHANGE
                        {
                            ValueDate   = DateTime.Now,
                            AccountID   = account.ID,
                            Amount      = startBalance,
                            ChangeType  = (int)BalanceChangeType.Deposit,
                            Description = "initial deposit"
                        };
                        ctx.BALANCE_CHANGE.Add(trans);

                        // сделать сигнальщиком
                        if (makeNewlyAddedUsersSignallers)
                        {
                            MakeNewlyRegisteredAccountSignaller(ctx, userBase, account);
                        }

                        // сохранить все изменения
                        ctx.SaveChanges();
                        if (string.IsNullOrEmpty(completedPassword))
                        {
                            if (!SendEmailOnNewAccount(user, true))
                            {
                                transaction.Rollback();
                                return(AccountRegistrationStatus.EmailDeliveryError);
                            }
                        }

                        transaction.Commit();
                        ((IObjectContextAdapter)ctx).ObjectContext.Connection.Close();
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorFormat("Ошибка в RegisterAccount (login={0}, email={1}) : {2}",
                                           user.Login, user.Email, ex);
                        transaction.Rollback();
                        ((IObjectContextAdapter)ctx).ObjectContext.Connection.Close();
                        return(AccountRegistrationStatus.ServerError);
                    }
                } // using (transaction ...
            }
            return(AccountRegistrationStatus.OK);
        }
Exemple #17
0
        private void RunWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            StreamWriter statsOutput = null, fullLogOutput = null;

            if (saveData.SaveStats)
            {
                if (!Directory.Exists(saveData.SavePath))
                {
                    Directory.CreateDirectory(saveData.SavePath);
                }
                var path = Path.Combine(saveData.SavePath, "stats_" + DateTime.Now.ToString("yy-MM-dd_HH-mm-ss") + ".txt");
                statsOutput = new StreamWriter(File.Open(path, FileMode.Create));
            }
            if (saveData.SaveFullLog)
            {
                if (!Directory.Exists(saveData.SavePath))
                {
                    Directory.CreateDirectory(saveData.SavePath);
                }
                var path = Path.Combine(saveData.SavePath, "full_" + DateTime.Now.ToString("yy-MM-dd_HH-mm-ss") + ".txt");
                fullLogOutput = new StreamWriter(File.Open(path, FileMode.Create));
            }
            logger      = new OutputLogger(fullLogOutput);
            tokenSource = new CancellationTokenSource();
            token       = tokenSource.Token;
            if (statsOutput != null)
            {
                statsOutput.WriteLine(
                    "Exponent: {0}\nDetect equal to exponent: {1}\nAlphabet size: {2}\nLength: {3}\nRuns count: {4}\nChar generator: {5}\nRemoving strategy: {6}",
                    detector.E, detector.DetectEqual, charGenerator.AlphabetSize, length, runsCount,
                    charGenerator.GetType().Name, removeStrategy);
            }
            Task.Run(() =>
            {
                totalCharsGenerated = 0;
                ms            = 0;
                runsPerformed = 0;
                while (runsPerformed < runsCount && !token.IsCancellationRequested)
                {
                    detector.Reset();
                    if (statsOutput != null)
                    {
                        statsOutput.WriteLine("Run #{0}:", runsPerformed + 1);
                    }

                    var text = RandomWordGenerator.Generate(detector, length, removeStrategy, charGenerator, logger, token);
                    if (!token.IsCancellationRequested)
                    {
                        runsPerformed++;
                        totalCharsGenerated += RandomWordGenerator.Statistics.CharsGenerated;
                        ms += RandomWordGenerator.Statistics.Milliseconds;

                        if (statsOutput != null)
                        {
                            statsOutput.Flush();
                        }
                        if (fullLogOutput != null)
                        {
                            fullLogOutput.WriteLine("Result: {0}\n", text);
                        }
                        if (statsOutput != null)
                        {
                            statsOutput.WriteLine("Coef: {0:0.000000}, Time: {1:0.000} ms",
                                                  RandomWordGenerator.Statistics.CharsGenerated * 1.0 / length,
                                                  RandomWordGenerator.Statistics.Milliseconds);
                            statsOutput.WriteLine("Repetition periods:\n{0}",
                                                  string.Join("\n", RandomWordGenerator.Statistics.CountOfPeriods
                                                              .OrderBy(p => p.Key)
                                                              .Select(p => string.Format("{0}: {1}", p.Key, p.Value))));
                            statsOutput.WriteLine("-----");
                        }
                    }
                }
                if (statsOutput != null)
                {
                    statsOutput.WriteLine("-----");
                    statsOutput.WriteLine("Runs performed: {0}\nAverage coef: {1:0.000000}\nAverage time: {2:0.000} ms",
                                          runsPerformed,
                                          totalCharsGenerated * 1.0 / length / runsPerformed,
                                          ms * 1.0 / runsPerformed);
                }
                Thread.Sleep(500);
                tokenSource.Cancel();
                if (statsOutput != null)
                {
                    statsOutput.Close();
                }
                if (fullLogOutput != null)
                {
                    fullLogOutput.Close();
                }
            }, token);
            UpdateStatus += () => Dispatcher.Invoke(() =>
            {
                TextBoxCurrentLength.Text = logger.TextLength.ToString();
                TextBoxRunsCompleted.Text = runsPerformed.ToString();
                if (runsPerformed > 0)
                {
                    TextBoxAverageCoef.Text = string.Format("{0:0.000000}", totalCharsGenerated * 1.0 / length / runsPerformed);
                    TextBoxAverageTime.Text = string.Format("{0:0.000}", ms * 1.0 / runsPerformed);
                }
            });
            Task.Run(() =>
            {
                while (!token.IsCancellationRequested)
                {
                    // ReSharper disable once PossibleNullReferenceException
                    UpdateStatus();
                    Thread.Sleep(100);
                }
                // ReSharper disable once PossibleNullReferenceException
                UpdateStatus();
            }, token);
        }