public static Tuple <TimeSpan, double> GetOptimal2( TimeSpan deadline, int k, DistType t1, double mean1, double sigma1, DistType t2, double mean2, double sigma2) { // TODO : MaxTime is in seconds TimeSpan time = new TimeSpan(0, 0, 0, 0, 1); double quality = 0.0; double maxQuality = 0; TimeSpan maxTime; TimeSpan increment = new TimeSpan(0, 0, 0, 0, 2); while (time < deadline) { double aboveQualityWithoutWait = GetOptimal1(deadline - time, t2, mean2, sigma2).Item2; double aboveQualityWithWait = GetOptimal1(deadline - time - increment, t2, mean2, sigma2).Item2; double gain = (Randomness.GetCdf((time + increment).TotalMilliseconds, t1, mean1, sigma1) - Randomness.GetCdf(time.TotalMilliseconds, t1, mean1, sigma1) ) * aboveQualityWithWait; double loss = (Randomness.GetCdf(time.TotalMilliseconds, t1, mean1, sigma1) - Math.Pow(Randomness.GetCdf(time.TotalMilliseconds, t1, mean1, sigma1), k)) * (aboveQualityWithoutWait - aboveQualityWithWait); quality += gain - loss; if (quality > maxQuality) { maxQuality = quality; maxTime = time; } time += increment; } return(new Tuple <TimeSpan, double> (maxTime, maxQuality)); }
public static Tuple <TimeSpan, double> GetOptimal1( TimeSpan deadline, DistType t1, double mean1, double sigma1) { return(new Tuple <TimeSpan, double> (deadline, Randomness.GetCdf((deadline).TotalMilliseconds, t1, mean1, sigma1))); }
public void BigInt_MulAddDivRemTest() { const int WordBitSize = 23; var r = Randomness.NextRandom(); for (int i = 0; i < 1000; i++) { var list = new List <uint>(); var bigInt = BigInt.FromByteCount(256); var q = r .NextUInt32Sequence() .Select(x => x & ((1U << WordBitSize) - 1)) .Take(1 + r.Next(64)); foreach (var x in q) { bigInt.Mul(1U << WordBitSize); bigInt.Add(x); list.Add(x); } list.Reverse(); foreach (var x in list) { uint y = bigInt.DivRem(1U << WordBitSize); Assert.AreEqual(x, y); } } }
public void BaseConverter_RandomIntsLexTest(BaseConverter converter) { var r = Randomness.NextRandom(); var a = r.NextInt32Sequence().Take(1000); var b = r.NextUInt32Sequence().Take(1000); var c = r.NextInt64Sequence().Take(1000); var d = r.NextUInt64Sequence().Take(1000); var actions = new Action[] { TestBuilder .NewLexicographicOrderTest(a, converter, converter.Encode) .Create(), TestBuilder .NewLexicographicOrderTest(b, converter, converter.Encode) .Create(), TestBuilder .NewLexicographicOrderTest(c, converter, converter.Encode) .Create(), TestBuilder .NewLexicographicOrderTest(d, converter, converter.Encode) .Create(), }; foreach (var action in actions) { action(); } }
private void ButtonRandomizeUserNameClick(object sender, RoutedEventArgs e) { if (Program.LobbyClient.IsConnected == false) { TextBoxUserName.Text = Randomness.GrabRandomJargonWord() + "-" + Randomness.GrabRandomNounWord(); } }
public Action Create() { return(() => { var list = _source.ToList(); var r = Randomness.NextRandom(); var q = from v in list let s = _encoder(v) let t = Translate(r, s) let y = _decoder(t) select Tuple.Create(v, s, y); var message = string.Format(_message ?? "Cannot encoder/decode '{0}'", typeof(T)); int i = 0; foreach (var item in q) { #if DEBUG if ((i != 0) & ((i % 100) == 0)) { var s = _strFunc != null?_strFunc(item.Item1) : item.Item1.ToString(); Trace.WriteLine(s + " <-> " + item.Item2); } #endif Assert.AreEqual(item.Item1, item.Item3, message); i++; } }); }
public async Task <ActionResult> PickArtists() { var currentListener = GetCurrentListener(); var artists = new List <Artist>(); var genres = new List <Genre>(); if (!db.Genres.Any()) { await SpotifyInteractionController.SpotifyGenerateGenreSeeds(currentListener); } genres.AddRange(db.Genres.AsNoTracking().ToList()); List <Task <Artist> > artistTask = new List <Task <Artist> >(); for (int i = 0; i < 25; i++) { var genre = genres[Randomness.RandomInt(0, genreSeedCount)]; artistTask.Add(SpotifyInteractionController.SpotifySearchForArtistInGenre(genre, currentListener)); } foreach (var task in artistTask) { var artist = await task; if (artist != null && artists.FirstOrDefault(a => a.ArtistSpotifyId == artist.ArtistSpotifyId) is null) { artists.Add(artist); } } return(View(artists)); }
public static void init(int seed) { currentTime = new TimeSpan(0, 0, 0, 0, 1); requests = new List <Request> (); flowCompletionTimesMla = new List <double> (); flowCompletionTimesTla = new List <double> (); rnd = new Randomness(seed); numFlowsMissed = 0; ReadFacebookTaskDurations(seed + 5); ReadDcTcpNumbers(); ReadLogNormalOrderStats(); /* * string[] lines = System.IO.File.ReadAllLines(@"Optimal.txt"); * * computeToWaitTime = new Dictionary<Tuple<int, int>, int>(); * fore ach (string l in lines) * { * string[] split = l.Split(new char[] { ' ' }); * double mlaT = double.Parse(split[0]); * double wlaT = double.Parse(split[1]); * int waitTime = int.Parse(split[2]); * int mlaI = (int)(1000.0 * mlaT); * int wlaI = (int)(1000.0 * wlaT); * //Console.Error.WriteLine("Adding " + mlaI + " " + * // wlaI + " " + waitTime); * computeToWaitTime.Add(new Tuple<int, int>(mlaI, wlaI), waitTime); * * } */ }
public void BaseConverter_RandomIntsCodingTest(BaseConverter converter) { var r = Randomness.NextRandom(); var a = r.NextInt32Sequence().Take(1000); var b = r.NextUInt32Sequence().Take(1000); var c = r.NextInt64Sequence().Take(1000); var d = r.NextUInt64Sequence().Take(1000); var actions = new Action[] { TestBuilder .NewCodingTest(a, converter, converter.Encode, x => converter.DecodeInt32(x)) .Create(), TestBuilder .NewCodingTest(b, converter, converter.Encode, x => converter.DecodeUInt32(x)) .Create(), TestBuilder .NewCodingTest(c, converter, converter.Encode, x => converter.DecodeInt64(x)) .Create(), TestBuilder .NewCodingTest(d, converter, converter.Encode, x => converter.DecodeUInt64(x)) .Create(), }; foreach (var action in actions) { action(); } }
public void RandomKeyTest() { int expected = 30; //Length of string var actual = Randomness.RandomKey().Length; Assert.AreEqual(expected, actual); }
public HostGameSettings() { InitializeComponent(); Specators = true; Program.IsHost = true; Games = new ObservableCollection <DataGameViewModel>(); Program.LobbyClient.Hosting().HostedGameReady += LobbyClient_HostedGameReady; Program.LobbyClient.Connected += LobbyClient_Connected; Program.LobbyClient.Disconnected += LobbyClient_Disconnected; TextBoxGameName.Text = Prefs.LastRoomName ?? Randomness.RandomRoomName(); CheckBoxIsLocalGame.IsChecked = !Program.LobbyClient.IsConnected; CheckBoxIsLocalGame.IsEnabled = Program.LobbyClient.IsConnected; LabelIsLocalGame.IsEnabled = Program.LobbyClient.IsConnected; lastHostedGameType = Prefs.LastHostedGameType; TextBoxUserName.Text = (Program.LobbyClient.IsConnected == false || Program.LobbyClient.User == null || Program.LobbyClient.User.DisplayName == null) ? Prefs.Nickname : Program.LobbyClient.User.DisplayName; Program.OnOptionsChanged += ProgramOnOptionsChanged; TextBoxUserName.IsReadOnly = Program.LobbyClient.IsConnected; if (Program.LobbyClient.IsConnected) { PasswordGame.IsEnabled = SubscriptionModule.Get().IsSubscribed ?? false; } else { PasswordGame.IsEnabled = true; } StackPanelIsLocalGame.Visibility = Prefs.EnableAdvancedOptions ? Visibility.Visible : Visibility.Collapsed; }
public override void OnCycle() { if (SpeechTimer <= 0) { Entity.OnChat("testing", 1, ChatType.CHAT); SpeechTimer = 20; } else { SpeechTimer--; } if (Entity.CanWalk) { if (ActionTimer <= 0) { RoomTile tile = CurrentRoom.Mapping.RandomWalkableTile; if (tile != null) { Entity.TargetPosition = new UserPosition() { X = tile.Position.X, Y = tile.Position.Y }; Entity.Path = CurrentRoom.PathFinder.Path(Entity); } ActionTimer = Randomness.RandomNumber(5, 20); } else { ActionTimer--; } } }
public void GetValue() { var value = new Randomness().GetValue(2, 10); Assert.IsTrue(value >= 2); Assert.IsTrue(value <= 10); }
public override void OnEntityJoin() { SpeechTimer = 20; ActionTimer = Randomness.RandomNumber(5, 20); CurrentRoom.EntityManager.Send(new RoomUserDanceComposer(Entity)); CurrentRoom.EntityManager.Send(new RoomUserEffectComposer(Entity)); }
public static Uri GetSpotifyAuthorization() { storedState = Randomness.RandomString(); var url = $"https://accounts.spotify.com/authorize?client_id={Keys.SpotifyClientId}&response_type=code&redirect_uri={redirect_url}&scope=playlist-modify-private,user-read-private&state={storedState}"; Uri uri = new Uri(url); return(uri); }
/// <summary> /// Generate values to create and validate the article in the database /// </summary> public void readInTestData() { nodeValues.Add(Service_ArticleService.nodes.DESCRIPTION, Randomness.randomAlphaNumeric(8)); nodeValues.Add(Service_ArticleService.nodes.ID, "AR-12345"); nodeValues.Add(Service_ArticleService.nodes.NAME, Randomness.randomString(8)); nodeValues.Add(Service_ArticleService.nodes.PRICEAMOUNT, "1.0"); nodeValues.Add(Service_ArticleService.nodes.PRICECURRENCY, "USD"); }
public static TestModel Random() { return(new TestModel { Id = Randomness.Number(), ColumnOne = Randomness.Text(), ColumnTwo = Randomness.Text() }); }
protected void Process(JobSegment job) { try { if (job.JobStatus <= JobStatus.Paused) { job.Started = DateTime.Now; if (job.JobStatus == JobStatus.Pending) { job.JobStatus = JobStatus.Running; } Randomness.Seed((job.Id.GetHashCode() + DateTime.Now.Ticks).GetHashCode()); var simulator = job.Specification.CreateSimulator(); var visitorCount = simulator.GetVisitors(job.TargetVisitors); var partitioner = Partitioner.Create(visitorCount, EnumerablePartitionerOptions.NoBuffering); Parallel.ForEach(partitioner, ParallelOptions, (visitor, loopState) => { while (job.JobStatus == JobStatus.Paused) { Thread.Sleep(1000); } if (job.JobStatus > JobStatus.Paused) { loopState.Break(); } try { foreach (var visit in visitor.Commit()) { ++job.CompletedVisits; } } catch (Exception ex) { ++job.Exceptions; job.LastException = ex.ToString(); } ++job.CompletedVisitors; }); } job.Ended = DateTime.Now; job.JobStatus = job.CompletedVisitors < job.TargetVisitors ? JobStatus.Cancelled : JobStatus.Complete; } catch (Exception ex) { job.JobStatus = JobStatus.Failed; job.Ended = DateTime.Now; job.LastException = ex.ToString(); } }
public void Test2() { for (var i = 0; i < 1000; i++) { var num = Randomness.RandomInteger(1, 5); Assert.IsTrue(num >= 1); Assert.IsTrue(num < 5); } }
protected void Process(JobSegment job) { try { if (job.JobStatus <= JobStatus.Paused) { job.Started = DateTime.Now; if (job.JobStatus == JobStatus.Pending) { job.JobStatus = JobStatus.Running; } Randomness.Seed((job.Id.GetHashCode() + DateTime.Now.Ticks).GetHashCode()); var sim = job.Specification.CreateSimulator(); foreach (var visitor in sim.NextVisitors(job.TargetVisitors, false)) { while (job.JobStatus == JobStatus.Paused) { Thread.Sleep(100); } if (job.JobStatus > JobStatus.Paused) { break; } try { foreach (var visit in visitor.Commit()) { ++job.CompletedVisits; } } catch (Exception ex) { ++job.Exceptions; job.LastException = ex.ToString(); } ++job.CompletedVisitors; } } job.Ended = DateTime.Now; job.JobStatus = job.CompletedVisitors < job.TargetVisitors ? JobStatus.Cancelled : JobStatus.Complete; } catch (Exception ex) { job.JobStatus = JobStatus.Failed; job.Ended = DateTime.Now; job.LastException = ex.ToString(); } }
public void StatisticsHelper_Mean_Average_Test(double expected, double[] xs) { var r = Randomness.NextRandom(); for (int i = 0; i < 10; i++) { var mean = r.NextShuffle(xs).Mean(); Assert.AreEqual(expected, mean.Average); } }
private int GetRandomEffectId(RoomItem item) { int id = 0; List <int> items = item.ItemData.ExtraData.Split(',').Select(Int32.Parse).ToList(); if (items.Count != 0) { id = items[Randomness.RandomNumber(items.Count) - 1]; } return(id); }
private async Task Host() { await StartLocalGame(HostGame, Randomness.RandomRoomName(), ""); Octgn.Play.Player.OnLocalPlayerWelcomed += PlayerOnOnLocalPlayerWelcomed; Program.GameSettings.UseTwoSidedTable = HostGame.UseTwoSidedTable; if (Program.GameEngine != null) { Dispatcher.CurrentDispatcher.Invoke(new Action(() => Program.GameEngine.Begin())); } }
public void GenerateNewGuidTest() { //References: //GUID Patterns http://www.regexlib.com/Search.aspx?k=guid string expected = @"^\{?[a-fA-F\d]{8}-?([a-fA-F\d]{4}-?){3}[a-fA-F\d]{12}\}?$"; // GUID Pattern string actual = Randomness.GenerateNewGuid(); //Digits only - 32 characters Regex rgx = new Regex(expected, RegexOptions.None); Assert.IsTrue(rgx.IsMatch(actual)); }
private static void Main2(string[] args) { Randomness.Seed(1337); var segment = new VisitorSegment("Test"); segment.VisitorVariables.Add(Variables.Fixed("Country", "DK")); //Simulate visitors from Jan 1 2012 until now segment.StartDateTime(new DateTime(2012, 1, 1), DateTime.Now, //Create a linear trend in year d => d.Year(trend => trend.SetLevel(0).LineRelativePercentage(1, 1)) //Add a peak in the summer .PartOfYear(trend => trend.AddPeak(0.5, 0.1, pct: true))); var simulator = new SegmentBasedSimulator(segment); //Create a 1000 visitors. These are ordered by start date foreach (var visitor in simulator.NextVisitors(1000)) { System.Console.Out.WriteLine("."); var ctx = new SitecoreRequestContext("http://sc80rev150209/", visitor); using (var visit = ctx.NewVisit()) { //Request home page as if coming from Google visit.Request("/", TimeSpan.FromSeconds(2), new { Referrer = "http://www.google.com" }); //Request home page again var info = visit.Request("/", TimeSpan.FromSeconds(2)); //"info" contains information from Sitecore, including the item displayed, it's fields, the visit's current VisitData from the tracker etc. //This can be used to change the behavior of the visit if (info.VisitData.ContactVisitIndex == 2) { } } //Wait 14 days before making the next visit ctx.Pause(TimeSpan.FromDays(14)); using (var visit = ctx.NewVisit()) { visit.Request("/", TimeSpan.FromSeconds(2)); System.Console.Out.WriteLine(visit.VisitData.ContactVisitIndex); } } }
public void OnCycle(RoomItem item) { if (item.Mode == -1) { if (count >= 2) { item.Mode = Randomness.RandomNumber(item.ItemData.Modes); item.Room.EntityManager.Send(new FloorItemUpdateComposer(item)); } count++; } }
//================================================================================================================ //================================================================================================================ #endregion // Card Shuffler #region Randomness //================================================================================================================ //================================================================================================================ public ActionResult Randomness() //================================================================================================================ // This action is invoked when the randomness comparison page is requested. // // Event Arguments // arg_CardPackId: Unique id of the selected card pack // arg_SampleSize: Unique id of the selected sample size // // Returns // The card shuffler page view //================================================================================================================ { // Safety check for the server if ((bool)Session[SiteHelpers.ServerRunning] == false) { return(View("ServerNotRunning", new PokerPlayground())); } // Retrieve the selected card pack int cardPackId = !string.IsNullOrEmpty(Request.Params[ARG_CARD_PACK_ID]) ? int.Parse(Request.Params[ARG_CARD_PACK_ID]) : 0; int sampleSize = !string.IsNullOrEmpty(Request.Params[ARG_SAMPLE_SIZE]) ? int.Parse(Request.Params[ARG_SAMPLE_SIZE]) : (int)SiteHelpers.SampleSizes.FourCardSample; // Create the model Randomness model = new Randomness(); // Populate the model SSCasino_DBContext dbCasino = null; try { // Connect the the database dbCasino = new SSCasino_DBContext(); // Get card packs for the card shuffler model.ShuffledPackageFisher.CardPack = CreateCardPackModel(dbCasino, cardPackId, (SiteHelpers.SampleSizes)sampleSize); model.ShuffledPackageNaive.CardPack = CreateCardPackModel(dbCasino, cardPackId, (SiteHelpers.SampleSizes)sampleSize); // Load the shuffler control panel with card packs LoadShufflerCards(dbCasino, model.ControlPanel, cardPackId); // Get the total number of shuffles and aggregated results GetShuffleResults(model.ShuffleResultsData); } finally { if (dbCasino != null) { dbCasino.Dispose(); } } return(View("Randomness", model)); }
public static Vector3 TwoDWithMagnitude(float magnitude) { Vector3 v = new Vector3( (-1.0f + Randomness.Value() * 2.0f), (-1.0f + Randomness.Value() * 2.0f), 0.0f ); v.Normalize(); v *= magnitude; return(v); }
public void RunningStat_Average_Test1() { foreach (var n in new[] { 1, 2, 3, 10, 100, 1000 }) { var xs = Randomness.NextRandom().NextSequence(n).Select(x => (double)x).Take(n).ToList(); var stat = new RunningStat(); foreach (var x in xs) { stat.Push(x); } Assert.AreEqual(xs.Average(), stat.Average, 1d / 1000000); } }
public void BaseConverter_RandomBytesLexTest(BaseConverter converter) { var r = Randomness.NextRandom(); var a = Enumerable.Range(0, 1000) .Select(x => { var v = new byte[r.Next(8)]; r.NextBytes(v); return(v); }); var b = Enumerable.Range(0, 1000) .Select(x => { var v = new byte[r.Next(16)]; r.NextBytes(v); return(v); }); var c = Enumerable.Range(0, 1000) .Select(x => { var v = new byte[r.Next(256)]; r.NextBytes(v); return(v); }); var actions = new Action[] { TestBuilder .NewLexicographicOrderTest(a, converter, converter.Encode) .WithComparer(new ByteArrayComparer()) .WithStringFunction(x => string.Join(",", x.Select(y => y.ToString("X2")))) .WithVariableLengthData(true) .Create(), TestBuilder .NewLexicographicOrderTest(b, converter, converter.Encode) .WithComparer(new ByteArrayComparer()) .WithStringFunction(x => string.Join(",", x.Select(y => y.ToString("X2")))) .WithVariableLengthData(true) .Create(), TestBuilder .NewLexicographicOrderTest(c, converter, converter.Encode) .WithComparer(new ByteArrayComparer()) .WithStringFunction(x => string.Join(",", x.Select(y => y.ToString("X2")))) .WithVariableLengthData(true) .Create(), }; foreach (var action in actions) { action(); } }
public void Initialize(I_SceneRandGenerator SceneRand) { GeneratorRand = new Randomness(); GeneratorRand.GenerateScene = SceneRand; }