private static IEnumerable <Order> GenerateRandom( int orderCount, string baseCurrency, string quoteCurrency, double minPrice, double maxPrice) { var price = new TRandom(); var amount = new TRandom(); for (var i = 0; i < orderCount; i++) { yield return(new Order( new CurrencyPair(baseCurrency, quoteCurrency), Side.Buy, decimal.Round((decimal)price.NextDouble(minPrice, maxPrice), 4), amount.Next(1, 100))); yield return(new Order( new CurrencyPair(baseCurrency, quoteCurrency), Side.Sell, decimal.Round((decimal)price.NextDouble(minPrice, maxPrice), 4), amount.Next(1, 100))); } }
public static async Task <AccountCreationResult> Create(AccountCreationOptions options) { var random = new TRandom(); var client = new RestClient { Proxy = options.Proxy }; var page = client.Execute(new RestRequest("https://club.pokemon.com/us/pokemon-trainer-club/sign-up/", Method.GET)); var csrf = string.Empty; // Get CSRF var match = new Regex("<input type='hidden' name='csrfmiddlewaretoken' value='(\\w+)' />").Match(page.Content); if (match.Success) { csrf = match.Groups[1].Value; } client.Execute(new RestRequest("https://club.pokemon.com/us/pokemon-trainer-club/sign-up/", Method.POST) .AddParameter("csrfmiddlewaretoken", csrf) .AddParameter("dob", options.Dob) .AddParameter("country", "US") .AddParameter("country", "US") .AddParameter("picker__year", options.Dob.Split('-')[0]) .AddParameter("picker__month", options.Dob.Split('-')[1])); await Task.Delay(random.Next(2000, 3000)); var user = client.Execute <VerifyUsernameResponse>(new RestRequest("https://club.pokemon.com/api/signup/" + "verify-username", Method.POST) .AddJsonBody(new { name = options.Username }) .AddHeader("X-CSRFToken", csrf)); // If username is in use, switch to a random suggestion from PTC if (user.Data.InUse) { options.Username = random.Choice(user.Data.Suggestions); } var captcha = options.CaptchaService.Solve(); await Task.Delay(random.Next(1500, 2500)); var res = client.Execute(new RestRequest("https://club.pokemon.com/us/pokemon-trainer-club/sign-up/", Method .POST) .AddParameter("csrfmiddlewaretoken", csrf) .AddParameter("username", options.Username)); return(new AccountCreationResult { Successful = res.StatusCode == HttpStatusCode.Found, Username = options.Username, Password = options.Password }); }
// 명부를 임의로 섞습니다. 배정때마다 기존 명부에서 삭제되고 // 대신 임의로 섞인 새 명부를 반환합니다. private List<string> randomizeList(List<string> destructableList) { List<string> newList = new List<string>(); int initialListCount = destructableList.Count; for(int i = 0; i < initialListCount; i++) { int cursor = m_rng.Next(0, destructableList.Count); newList.Add(destructableList[cursor]); destructableList.RemoveAt(cursor); } return newList; }
//crossover function, swap random two elements public void Crossover(double[] Group) { TRandom rnd = new TRandom(); int index = rnd.Next(0, Group.Length); int index2 = rnd.Next(0, Group.Length); while (index == index2) { index2 = rnd.Next(0, Group.Length); } var value = Group[index]; Group[index] = Group[index2]; Group[index2] = Group[index]; }
/// <summary> /// Generates a few random <see cref="LocationFix"/>es to act like a real GPS sensor. /// </summary> /// <param name="requestEnvelope">The <see cref="RequestEnvelope"/> these <see cref="LocationFix"/>es are used for.</param> /// <param name="timestampSinceStart">The milliseconds passed since starting the <see cref="Session"/> used by the current <see cref="RequestEnvelope"/>.</param> /// <returns></returns> private List <LocationFix> BuildLocationFixes(RequestEnvelope requestEnvelope, long timestampSinceStart) { var locationFixes = new List <LocationFix>(); TRandom Random = new TRandom(); if (requestEnvelope.Requests.Count == 0 || requestEnvelope.Requests[0] == null) { return(locationFixes); } var providerCount = Random.Next(4, 10); for (var i = 0; i < providerCount; i++) { var timestampSnapshot = timestampSinceStart + (150 * (i + 1) + Random.Next(250 * (i + 1) - 150 * (i + 1))); if (timestampSnapshot >= timestampSinceStart) { if (locationFixes.Count != 0) { break; } timestampSnapshot = timestampSinceStart - Random.Next(20, 50); if (timestampSnapshot < 0) { timestampSnapshot = 0; } } locationFixes.Insert(0, new LocationFix { TimestampSnapshot = (ulong)timestampSnapshot, Latitude = (float)_client.CurrentLatitude, Longitude = (float)_client.CurrentLongitude, HorizontalAccuracy = (float)Random.NextDouble(5.0, 25.0), VerticalAccuracy = (float)Random.NextDouble(5.0, 25.0), Altitude = (float)_client.CurrentAltitude, Provider = "fused", ProviderStatus = 3, LocationType = 1, // Speed = ?, Course = -1, // Floor = 0 }); } return(locationFixes); }
/// <summary> /// Generates given number of packages in the path. Wipes the target path /// </summary> /// <param name="count"></param> public void CreatePackages(int count, int maxFiles, int maxFileSize, string path) { if (Directory.Exists(path)) { Directory.Delete(path, true); } Directory.CreateDirectory(path); List <string> packages = new List <string>(); TRandom random = new TRandom(); for (int i = 0; i < count; i++) { List <PackageCreateItem> files = new List <PackageCreateItem>(); int filesToAdd = random.Next(0, maxFiles); for (int j = 0; j < filesToAdd; j++) { byte[] buffer = new byte[maxFileSize]; random.NextBytes(buffer); Stream file = new MemoryStream(buffer); files.Add(new PackageCreateItem(file, $"folder{Guid.NewGuid()}/{Guid.NewGuid()}")); } PackageCreateArguments package = new PackageCreateArguments { Id = Guid.NewGuid().ToString(), Files = files }; _packageServices.CreatePackage(package); Console.WriteLine($"Generated package {package.Id}"); } }
public static Permutation CutAndCrossfillCrossover(Permutation p1, Permutation p2, TRandom random) { if (p1.Count != p2.Count) { throw new ArgumentException("The element count differs.", nameof(p2)); } if (p1.IsCircular != p2.IsCircular) { throw new ArgumentException("The circularity differs.", nameof(p2)); } var min = (p1.IsCircular ? 1 : 0) + 1; var max = p1.Count - 1; if (max < min) { throw new InvalidOperationException("The permutation is to short for this operation."); } var position = (max == min) ? min : random.Next(min, max); var array = new int[p1.Count]; SpanExtensions.CutAndCrossfillCrossover(p1, p2, position, array); return(new Permutation(array, p1.IsCircular)); }
private static void GetRandomIndexPair(TRandom random, int n, int start, out int a, out int b) { a = random.Next(start, n); do { b = random.Next(start, n); }while (a == b); if (b < a) { var tmp = a; a = b; b = tmp; } }
public DateTime GetRandomDate(DateTime minimum, DateTime maximum, TRandom randomizer) { var rangeAsTimeSpan = maximum - minimum; var rangeInDays = rangeAsTimeSpan.Days; var randomNumberOfDaysSinceMin = randomizer.Next(rangeInDays); var randomDate = minimum.AddDays(randomNumberOfDaysSinceMin); return(randomDate); }
private void FlushRandomizer(TRandom randomizer) { int NumClears = 4; for (int i = 0; i < NumClears; i++) { randomizer.Next(); } }
public void Next_MaxExclusive() { for (var i = 0; i < 1000; i++) { if (TRandom.Next(MaxLimitInt) >= MaxLimitInt) { Assert.Fail("Exclusive maximum limit was one of the random results"); } } }
public static void Scramble(this Span <int> span, TRandom random) { var n = span.Length; for (int i = 0; i < n - 1; i++) { var j = random.Next(i + 1, n); span.Swap(i, j); } }
public static void Main() { // 1) Use TRandom to generate a few random numbers - via IGenerator methods. Console.WriteLine("TRandom in action, used as an IGenerator"); var trandom = new TRandom(); Console.WriteLine(trandom.Next() - trandom.Next(5) + trandom.Next(3, 5)); Console.WriteLine(trandom.NextDouble() * trandom.NextDouble(5.5) * trandom.NextDouble(10.1, 21.9)); Console.WriteLine(trandom.NextBoolean()); Console.WriteLine(); // 2) Use TRandom to generate a few random numbers - via extension methods. Console.WriteLine("TRandom in action, used as an IGenerator augmented with extension methods"); Console.WriteLine(string.Join(", ", trandom.Integers().Take(10))); Console.WriteLine(string.Join(", ", trandom.Doubles().Take(10))); Console.WriteLine(string.Join(", ", trandom.Booleans().Take(10))); Console.WriteLine(); // 3) Use TRandom to generate a few distributed numbers. Console.WriteLine("TRandom in action, used as to get distributed numbers"); Console.WriteLine(trandom.Normal(1.0, 0.1)); Console.WriteLine(string.Join(", ", trandom.NormalSamples(1.0, 0.1).Take(20))); Console.WriteLine(trandom.Poisson(5)); Console.WriteLine(string.Join(", ", trandom.PoissonSamples(5).Take(20))); Console.WriteLine(); // 4) There are many generators available - XorShift128 is the default. var alf = new ALFGenerator(TMath.Seed()); var nr3 = new NR3Generator(); var std = new StandardGenerator(127); // 5) You can also use distribution directly, even with custom generators. Console.WriteLine("Showcase of some distributions"); Console.WriteLine("Static sample for Normal: " + NormalDistribution.Sample(alf, 1.0, 0.1)); Console.WriteLine("New instance for Normal: " + new NormalDistribution(1.0, 0.1).NextDouble()); Console.WriteLine(); }
public void Next_MinMaxBounds() { for (var i = 0; i < 1000; i++) { var value = TRandom.Next(MinLimitInt, MaxLimitInt); if (value >= MaxLimitInt || value < MinLimitInt) { Assert.Fail("Random result was out of bounds"); } } }
public void Next_MinMaxNegatives() { for (var i = 0; i < 1000; i++) { if (TRandom.Next(MinLimitInt, MaxLimitInt) < 0) { return; } } Assert.Fail("Negative result never hit"); }
/// <summary> /// Restores the state of the pseudo-random number generator based on the specified state parameter /// </summary> /// <example> /// If you generated three random numbers and then called Save to store the state and /// followed that up by generating 10 more numbers before calling Restore with the previously saved RandomState /// the Restore method should return the generator back to the state when Save was first called. /// This means that if you went on to generate 10 more numbers they would be the same 10 numbers that were /// generated the first time after Save was called. /// </example> /// <param name="state">The state to restore to, usually obtained from calling the Save method</param> /// <exception cref="ArgumentNullException">RandomState cannot be null</exception> public void Restore(RandomState state) { if (state == null) { throw new ArgumentNullException(nameof(state), "RandomState cannot be null"); } _seed = state.Seed[0]; _random = new TRandom(_seed); for (long i = 0; i < state.NumberGenerated; i++) { _random.Next(); } }
//|| date.Text.Trim() != string.Empty || amount.Text.Trim() != string.Empty || bName.Text.Trim() != string.Empty ||bAddress.Text.Trim() != string.Empty || cnic.Text.Trim() != string.Empty private void Generate_Click(object sender, EventArgs e) { if (crn.Text.Trim() != string.Empty || fName.Text.Trim() != string.Empty || tNum.Text.Trim() != string.Empty || fNum.Text.Trim() != string.Empty) { error.Text = ""; int CRN = Convert.ToInt32(crn.Text); int fn = Convert.ToInt32(fNum.Text); var nameGenerator = new PersonNameGenerator(); var trandom = new TRandom(); if (random.Checked) { for (int i = 1; i <= fn; i++) { int tn = Convert.ToInt32(tNum.Text); TextWriter txt = new StreamWriter("E:\\" + fName.Text + i + ".csv"); txt.Write("Global ID,Transdate,Foreign Currency Amount,transferamount,transcurrencid,beneficairy name,beneficairy address1,beneficairy address2,beneficariy CNIC,beneficariy Mobile No,beneficairy city,Delivtype,delivdetail1,delivdetail2,delivdetail3,Sender name,Sender Address1,Sender Address2,Sender City,rem stat,remsource Code,Country Code" + (Environment.NewLine)); for (; tn > 0; tn--) { txt.Write(ValueToId(CRN) + "," + trandom.Next(1, 31) + "/" + trandom.Next(1, 12) + "/2019" + ",," + trandom.Next(10, 10000) + ",PKR," + nameGenerator.GenerateRandomFirstAndLastName() + "," + bAddress.Text + ",," + "42101" + trandom.Next(11111111, 99999999) + "," + "03" + trandom.Next(0, 999999999) + "," + city.Text + "," + tType.Text + "," + bank.Text + ",,0," + nameGenerator.GenerateRandomFirstAndLastName() + "," + rAddress.Text + ",," + rCity.Text + ",A," + ec.Text + ",1350" + (Environment.NewLine)); CRN++; } txt.Close(); } error.Text = "File have been generated!"; } else { for (int i = 1; i <= fn; i++) { int tn = Convert.ToInt32(tNum.Text); TextWriter txt = new StreamWriter("E:\\" + fName.Text + i + ".csv"); txt.Write("Global ID,Transdate,Foreign Currency Amount,transferamount,transcurrencid,beneficairy name,beneficairy address1,beneficairy address2,beneficariy CNIC,beneficariy Mobile No,beneficairy city,Delivtype,delivdetail1,delivdetail2,delivdetail3,Sender name,Sender Address1,Sender Address2,Sender City,rem stat,remsource Code,Country Code" + (Environment.NewLine)); for (; tn > 0; tn--) { txt.Write(ValueToId(CRN) + "," + date.Text + ",," + amount.Text + ",PKR," + bName.Text + "," + bAddress.Text + ",," + cnic.Text + "," + number.Text + "," + city.Text + "," + tType.Text + "," + bank.Text + ",,0," + rName.Text + "," + rAddress.Text + ",," + rCity.Text + ",A," + ec.Text + ",1350" + (Environment.NewLine)); CRN++; } txt.Close(); } error.Text = "File have been generated!"; } } else { error.Text = "All feilds are required to be filled!."; return; } //txt.Write(crn.Text + "," + date.Text + ",," + amount.Text + ",PKR," + bName.Text + "," + bAddress.Text + ",," + cnic.Text + "," + number.Text + "," + city.Text + "," + tType.Text + "," + bank.Text + ",,0," + rName.Text + "," + rAddress.Text + ",," + rCity.Text + ",A," + ec.Text + ",1350" + (Environment.NewLine)); }
//mutation function, changing one value in unit, checking if group is correct public void Mutation(double[] Group) { TRandom rnd = new TRandom(); int MutationNumber = rnd.Next(1, 3); bool works = false; while (works == false) { int MutationIndex = rnd.Next(0, Group.Length); double Prev = Group[MutationIndex]; Group[MutationIndex] = MutationNumber; var check = CheckGroup(Group); if (check == false) { Group[MutationIndex] = Prev; } else { works = true; } } }
public override BaseBuilder <Character> WithRandomizedDefaults(TRandom randomizer) { Entity = new Character(); var namePicker = new NamePicker(randomizer); var gender = (Gender)(randomizer.Next(2) + 1); Entity.Gender = gender; Entity.FirstName = namePicker.GetFirstName(gender); Entity.LastName = namePicker.GetLastName(); Entity.DateOfBirth = new RandomDateGenerator().GetRandomDate(new DateTime(1980, 1, 1), new DateTime(2019, 1, 1), randomizer); Entity.DateSimulatedTo = Entity.DateOfBirth; Entity.LifeLogs.Add(LifeLogFactories.BuildLog_Birth(Entity)); return(this); }
public void Next_MaxInclusive() { for (var i = 0; i < 1000; i++) { var value = TRandom.Next(MaxLimitInt); if (value == 0) { return; } if (value < 0) { Assert.Fail("Random result was less than inclusive minimum limit"); } } Assert.Fail("Inclusive minimum limit never hit"); }
//creating new population (half of last population won, so function is creating new units for the rest of population) public void CreateNewPopulation(Parameters parameters) { //getting winners amount int Winners = parameters.Popsize / 2; double[] CurrentGroup = new double[parameters.NumberOfVertices]; //creating new groups for (int k = Winners; k < parameters.Popsize; k++) { var NewGroup = CreateGroup(parameters.NumberOfVertices); for (int j = 0; j < NewGroup.Length; j++) { parameters.Population[j][k] = NewGroup[j]; } } //checking if mutation or crossover occur for (int i = Winners; i < parameters.Popsize; i++) { double CheckIfMutationHappen = MutationProc.Next(0, 100); double CheckIfCrossOverHappen = CrossoverProc.Next(0, 100); for (int k = 0; k < parameters.NumberOfVertices; k++) { CurrentGroup[k] = parameters.Population[k][i]; } if (CheckIfMutationHappen <= parameters.MutationProbabilityValue) { //mutation Mutation(CurrentGroup); } if (CheckIfCrossOverHappen <= parameters.CrossoverProbabilityValue) { //crossover Crossover(CurrentGroup); } } }
public static async Task CompleteTutorial(Session session, RepeatedField <TutorialState> tutorialState) { var random = new TRandom(); if (!tutorialState.Contains(0)) { await Task.Delay(random.Next(1000, 5000)); var mtcReq = await session.RpcClient.SendRemoteProcedureCallAsync(new Request { RequestType = RequestType.MarkTutorialComplete, RequestMessage = new MarkTutorialCompleteMessage { SendMarketingEmails = false, SendPushNotifications = false }.ToByteString() }); var mtcResp = MarkTutorialCompleteResponse.Parser.ParseFrom(mtcReq); // Form1.Logger.Debug($"Sending 0 tutorials_completed for {session.Player.Data.Username}."); } if (!tutorialState.Contains((TutorialState)1)) { await Task.Delay(random.Next(5000, 12000)); var caReq = await session.RpcClient.SendRemoteProcedureCallAsync(new Request { RequestType = RequestType.SetAvatar, RequestMessage = new SetAvatarMessage { PlayerAvatar = new PlayerAvatar { Hair = random.Next(1, 5), Shirt = random.Next(1, 3), Pants = random.Next(1, 2), Shoes = random.Next(1, 6), Avatar = random.Next(0, 1), Eyes = random.Next(1, 4), Backpack = random.Next(1, 5) } }.ToByteString() }); var caResp = SetAvatarResponse.Parser.ParseFrom(caReq); // Form1.Logger.Debug($"Sending set random player character request for ${session.Player.Data.Username}."); } await Task.Delay(random.Next(500, 600)); var gppr = await session.RpcClient.SendRemoteProcedureCallAsync(new Request { RequestType = RequestType.GetPlayerProfile, RequestMessage = new GetPlayerProfileMessage { PlayerName = session.Player.Data.Username }.ToByteString() }); var gppre = GetPlayerProfileResponse.Parser.ParseFrom(gppr); // Form1.Logger.Debug($"Fetching player profile for {session.Player.Data.Username}..."); if (!tutorialState.Contains((TutorialState)3)) { await Task.Delay(random.Next(1000, 1500)); var starters = new[] { PokemonId.Bulbasaur, PokemonId.Charmander, PokemonId.Squirtle }; var starter = starters[random.Next(0, starters.Length)]; var streq = await session.RpcClient.SendRemoteProcedureCallAsync(new Request { RequestType = RequestType.EncounterTutorialComplete, RequestMessage = new EncounterTutorialCompleteMessage { PokemonId = starter }.ToByteString() }); // Form1.Logger.Debug($"Catching the starter for {session.Player.Data.Username}. (Chose {starter.ToString()})"); var gpr = await session.RpcClient.SendRemoteProcedureCallAsync(new Request { RequestType = RequestType.GetPlayer, RequestMessage = new GetPlayerMessage { PlayerLocale = new GetPlayerMessage.Types.PlayerLocale { Country = "US", Language = "en", Timezone = "America/New_York" } }.ToByteString() }); var gpre = GetPlayerResponse.Parser.ParseFrom(gpr); } if (!tutorialState.Contains((TutorialState)4)) { await Task.Delay(random.Next(5000, 12000)); var ccreq = await session.RpcClient.SendRemoteProcedureCallAsync(new Request { RequestType = RequestType.ClaimCodename, RequestMessage = new ClaimCodenameMessage { Codename = session.Player.Data.Username }.ToByteString() }); var ccres = ClaimCodenameResponse.Parser.ParseFrom(ccreq); // Form1.Logger.Debug($"Claimed codename for {session.Player.Data.Username}."); var gpr = await session.RpcClient.SendRemoteProcedureCallAsync(new Request { RequestType = RequestType.GetPlayer, RequestMessage = new GetPlayerMessage { PlayerLocale = new GetPlayerMessage.Types.PlayerLocale { Country = "US", Language = "en", Timezone = "America/New_York" } }.ToByteString() }); var gpre = GetPlayerResponse.Parser.ParseFrom(gpr); } var firstOrDefault = session.Player.Inventory.InventoryItems.Select(i => i.InventoryItemData?.PokemonData).FirstOrDefault(p => p != null && p.PokemonId > 0); if (firstOrDefault != null) { var starterId = firstOrDefault.Id; if (starterId != null) { var budreq = await session.RpcClient.SendRemoteProcedureCallAsync(new Request { RequestType = RequestType.SetBuddyPokemon, RequestMessage = new SetBuddyPokemonMessage { PokemonId = starterId }.ToByteString() }); var budres = SetBuddyPokemonResponse.Parser.ParseFrom(budreq); // Form1.Logger.Debug($"Setting buddy pokemon for {session.Player.Data.Username}."); } } // Form1.Logger.Info($"And {session.Player.Data.Username} is done. Waiting a sec to avoid throttle."); await Task.Delay(random.Next(2000, 4000)); }
//public int GetNextUk27() //{ // return Uk27Random.Next(); //} //private RequestEnvelope.Types.PlatformRequest GenerateSignature(IEnumerable<IMessage> requests) /// <summary> /// EB Check IMessage /// </summary> /// <param name="requestEnvelope"></param> /// <returns></returns> /// Also pogolib does /// internal async Task<PlatformRequest> GenerateSignatureAsync(RequestEnvelope requestEnvelope) private RequestEnvelope.Types.PlatformRequest GenerateSignature(RequestEnvelope requestEnvelope) { var timestampSinceStart = (long)(Utils.GetTime(true) - _client.StartTime); var locationFixes = BuildLocationFixes(requestEnvelope, timestampSinceStart); if (requestEnvelope.Requests.Count > 0) { requestEnvelope.Accuracy = locationFixes[0].Altitude; requestEnvelope.MsSinceLastLocationfix = (long)locationFixes[0].TimestampSnapshot; } var _activityStatus = new Signature.Types.ActivityStatus() { Stationary = true, Tilting = (TRandomDevice.Next(1, 2) == 1) }; //if (_client.Platform == Platform.Ios) // _activityStatus.Tilting = (TRandomDevice.Next(1,2)==1); #region GenerateSignature var signature = new Signature { TimestampSinceStart = (ulong)timestampSinceStart, Timestamp = (ulong)Utils.GetTime(true), // true means in Ms SensorInfo = { new Signature.Types.SensorInfo { // Values are not the same used in PogoLib TimestampSnapshot = (ulong)(timestampSinceStart + TRandomDevice.Next(100, 250)), LinearAccelerationX = GenRandom(0.12271042913198471), LinearAccelerationY = GenRandom(-0.015570580959320068), LinearAccelerationZ = GenRandom(0.010850906372070313), RotationRateX = GenRandom(-0.0120010357350111), RotationRateY = GenRandom(-0.04214850440621376), RotationRateZ = GenRandom(0.94571763277053833), AttitudePitch = GenRandom(-47.149471283, 61.8397789001), AttitudeYaw = GenRandom(-47.149471283, 61.8397789001), AttitudeRoll = GenRandom(-47.149471283, 5), GravityZ = GenRandom(9.8), GravityX = GenRandom(0.02), GravityY = GenRandom(0.3), MagneticFieldX = GenRandom(-10, 10), MagneticFieldY = GenRandom(-10, 10), MagneticFieldZ = GenRandom(-40, -20), MagneticFieldAccuracy = -1, Status = 3 } }, DeviceInfo = _DeviceInfo,// dInfo, LocationFix = { locationFixes }, ActivityStatus = _activityStatus, SessionHash = _sessionHash, Unknown25 = Resources.Api.IOSUnknown25, Unknown27 = Uk27Random.Next() }; #endregion //signature.SessionHash = _sessionHash; //signature.Unknown25 = Resources.Api.AndroidUnknown25; //if (_client.Platform == Platform.Ios) //signature.Unknown25 = Resources.Api.IOSUnknown25; var serializedTicket = requestEnvelope.AuthTicket != null?requestEnvelope.AuthTicket.ToByteArray() : requestEnvelope.AuthInfo.ToByteArray(); /*var locationBytes = BitConverter.GetBytes(_latitude).Reverse() * .Concat(BitConverter.GetBytes(_longitude).Reverse()) * .Concat(BitConverter.GetBytes(locationFixes[0].Altitude).Reverse()).ToArray(); */ var requestsBytes = requestEnvelope.Requests.Select(x => x.ToByteArray()).ToArray(); var hashRequest = new HashRequestContent() { Timestamp = signature.Timestamp, Latitude64 = BitConverter.DoubleToInt64Bits(requestEnvelope.Latitude), Longitude64 = BitConverter.DoubleToInt64Bits(requestEnvelope.Longitude), Accuracy64 = BitConverter.DoubleToInt64Bits(requestEnvelope.Accuracy), AuthTicket = serializedTicket, SessionData = signature.SessionHash.ToByteArray(), Requests = new List <byte[]>(requestsBytes) }; HashResponseContent responseContent; responseContent = _client.Hasher.RequestHashes(hashRequest); signature.LocationHash1 = unchecked ((int)responseContent.LocationAuthHash); signature.LocationHash2 = unchecked ((int)responseContent.LocationHash); signature.RequestHash.AddRange(responseContent.RequestHashes.Select(x => (ulong)x).ToArray()); var encryptedSignature = new RequestEnvelope.Types.PlatformRequest { Type = PlatformRequestType.SendEncryptedSignature, RequestMessage = new SendEncryptedSignatureRequest { EncryptedSignature = ByteString.CopyFrom(_client.Crypter.Encrypt(signature.ToByteArray(), (uint)timestampSinceStart)) }.ToByteString() }; return(encryptedSignature); }
/// <summary> /// This method simulated bus sensor telemetry /// </summary> private static async Task GenerateTelemetry() { string outputName = "output1"; int routeIdx = 0; // TODO: 13 - Initialize machine learning prediction model infrastructure // var mlContext = new MLContext(); // ITransformer mlModel = mlContext.Model.Load("BusMlModel/MLModel.zip", out var modelInputSchema); // var predEngine = mlContext.Model.CreatePredictionEngine<ModelInput, ModelOutput>(mlModel); while (true) { try { var currRouteData = _routeData[routeIdx]; _borough = GetBorough(); _latitude = currRouteData.Latitude; _longitude = currRouteData.Longitude; // TODO 14: Create input for the machine learning prediction engine by setting the // device current latitude, longitude, and speed limit // var mlInput = new ModelInput() // { // Latitude = currRouteData.Latitude, // Longitude = currRouteData.Longitude, // BusSpeed = currRouteData.BusSpeed // }; // TODO 15: Use this input model to have the prediction engine determine if the // current speed for the device is safe for the latitude and longitude location //var mlOutput = predEngine.Predict(mlInput); if (routeIdx == _routeData.Count - 1) { routeIdx = 0; //restart route } else { routeIdx++; } var info = new BusEvent() { vin = _vin, outsideTemperature = GetOutsideTemp(_borough), engineTemperature = GetEngineTemp(_borough), speed = currRouteData.BusSpeed, fuel = _random.Next(0, 40), engineoil = GetOil(_borough), tirepressure = GetTirePressure(_borough), odometer = _random.Next(0, 200000), accelerator_pedal_position = _random.Next(0, 100), parking_brake_status = GetRandomBoolean(), headlamp_status = GetRandomBoolean(), brake_pedal_status = GetRandomBoolean(), transmission_gear_position = GetGearPos(), ignition_status = GetRandomBoolean(), windshield_wiper_status = GetRandomBoolean(), abs = GetRandomBoolean(), timestamp = DateTime.UtcNow, // TODO: 16 Populate the machine learning prediction into the telemetry data for upstream systems // mlDetectedAggressiveDriving = mlOutput.Prediction }; var serializedString = JsonConvert.SerializeObject(info); Console.WriteLine($"{DateTime.Now} > Sending message: {serializedString}"); var message = new Message(Encoding.UTF8.GetBytes(serializedString)); message.ContentEncoding = "utf-8"; message.ContentType = "application/json"; // TODO: 17 - Have the ModuleClient send the event message asynchronously, using the specified output name //await _vehicleTelemetryModuleClient.SendEventAsync(outputName, message); // TODO: 18 - Send all telemetry to local blob storage // var blockBlob = _blobContainer.GetBlockBlobReference($"telemetry_{info.timestamp.Ticks}.json"); // blockBlob.UploadText(serializedString); } catch (AggregateException ex) { foreach (Exception exception in ex.InnerExceptions) { Console.WriteLine(); Console.WriteLine("Error in sample: {0}", exception); } } catch (Exception ex) { Console.WriteLine(); Console.WriteLine("Error in sample: {0}", ex); } await Task.Delay(200); } }
public static async void Run(string[] args) { var random = new TRandom(); Configuration config; try { config = JsonConvert.DeserializeObject <Configuration>(File.ReadAllText( Directory.GetCurrentDirectory() + "/" + "config.json")); } catch (FileNotFoundException e) { Console.WriteLine("Please create a config.json file to continue."); throw; } Console.Write("Hello and welcome to "); Console.ForegroundColor = ConsoleColor.Magenta; Console.Write("Entropy!\n"); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine("How many accounts would you like to create today?"); var acts = int.Parse(Console.ReadLine()); Console.WriteLine($"This generation session will cost you about ${Math.Round(acts * 0.003, 2)} USD " + $"(for {acts} accounts)"); IProxyPool proxyPool; if (File.Exists($"{Directory.GetCurrentDirectory()}/{config.ProxyFile}")) { proxyPool = new StandardProxyPool(ProxyReader.ReadProxies(config.ProxyFile)); } else { proxyPool = new GimmeProxyPool(); } var captcha = new TwoCaptchaService(config.CaptchaKey); Console.WriteLine("OK! Let's go!"); var tasks = new List <Task>(); Status = "OK"; UpdateStats(); for (var i = acts - 1; i >= 0; i--) { tasks.Add(new Task(async() => { var proxy = proxyPool.NextProxy(); ActiveProxies++; for (var x = 0; x < 5; x++) { var username = random.Choice(config.Usernames.Prefix) + random.Choice(config.Usernames.Root) + random.Choice(config.Usernames.Suffix); var password = config.Password.UseStaticPassword ? config.Password.StaticPassword : String.Empty; var ui = new AccountCreationOptions { CaptchaService = captcha, Dob = $"{random.Next(1970, 2000)}-{FormatPTCNumber(random.Next(1, 12))}-{FormatPTCNumber(random.Next(1, 27))}", Proxy = proxy.ToWebProxy(), Username = username, Password = password }; var res = await Creator.Create(ui); if (res.Successful) { Created++; UpdateStats(); await Creator.HandleAccountAfterCreation(config, res); } else { Failed++; UpdateStats(); } } BenchedProxies++; })); } // Go. await Task.WhenAll(tasks); }
public override void Add(T item, double priority) { _items.Add(WaitQueue.NewPair(item, _random.Next())); }
private async Task <RequestEnvelope.Types.PlatformRequest> GenerateSignature(RequestEnvelope requestEnvelope, GeoCoordinate currentLocation) { byte[] ticketBytes = requestEnvelope.AuthTicket != null?requestEnvelope.AuthTicket.ToByteArray() : requestEnvelope.AuthInfo.ToByteArray(); // Common device info var deviceInfo = new Signature.Types.DeviceInfo { DeviceId = _settings.DeviceId, DeviceBrand = _settings.DeviceBrand, DeviceModel = _settings.DeviceModel, DeviceModelBoot = _settings.DeviceModelBoot + "\0", HardwareManufacturer = _settings.HardwareManufacturer, HardwareModel = _settings.HardwareModel + "\0", FirmwareBrand = (_settings.DeviceModel == "iPhone" ? "iOS" : "iPhone OS"), FirmwareType = _settings.FirmwareType }; // Android if (_client.Platform == Platform.Android) { deviceInfo.AndroidBoardName = _settings.AndroidBoardName; deviceInfo.AndroidBootloader = _settings.AndroidBootloader; deviceInfo.DeviceModelIdentifier = _settings.DeviceModelIdentifier; deviceInfo.FirmwareTags = _settings.FirmwareTags; deviceInfo.FirmwareFingerprint = _settings.FirmwareFingerprint; } var sig = new Signature { SessionHash = _sessionHash, Unknown25 = _client.Unknown25, Timestamp = (ulong)Utils.GetTime(true), TimestampSinceStart = (ulong)(Utils.GetTime(true) - _client.StartTime), DeviceInfo = deviceInfo }; if (sig.TimestampSinceStart < 5000) { sig.TimestampSinceStart = (ulong)TRandomDevice.Next(5000, 8000); } var sen = new Signature.Types.SensorInfo() { LinearAccelerationX = TRandomDevice.Triangular(-3, 1, 0), LinearAccelerationY = TRandomDevice.Triangular(-2, 3, 0), LinearAccelerationZ = TRandomDevice.Triangular(-4, 2, 0), MagneticFieldX = TRandomDevice.Triangular(-50, 50, 0), MagneticFieldY = TRandomDevice.Triangular(-60, 50, -5), MagneticFieldZ = TRandomDevice.Triangular(-60, 40, -30), MagneticFieldAccuracy = TRandomDevice.Choice(new List <int>(new int[] { -1, 1, 1, 2, 2, 2, 2 })), AttitudePitch = TRandomDevice.Triangular(-1.5, 1.5, 0.2), AttitudeYaw = TRandomDevice.NextDouble(-3, 3), AttitudeRoll = TRandomDevice.Triangular(-2.8, 2.5, 0.25), RotationRateX = TRandomDevice.Triangular(-6, 4, 0), RotationRateY = TRandomDevice.Triangular(-5.5, 5, 0), RotationRateZ = TRandomDevice.Triangular(-5, 3, 0), GravityX = TRandomDevice.Triangular(-1, 1, 0.15), GravityY = TRandomDevice.Triangular(-1, 1, -.2), GravityZ = TRandomDevice.Triangular(-1, .7, -0.8), Status = 3 }; sen.TimestampSnapshot = (ulong)TRandomDevice.NextUInt((uint)(sig.TimestampSinceStart - 5000), (uint)(sig.TimestampSinceStart - 100)); sig.SensorInfo.Add(sen); var locationFix = new Signature.Types.LocationFix { Provider = TRandomDevice.Choice(new List <string>(new string[] { "network", "network", "network", "network", "fused" })), Latitude = (float)currentLocation.Latitude, Longitude = (float)currentLocation.Longitude, Altitude = (float)currentLocation.Altitude, ProviderStatus = 3, LocationType = 1 }; locationFix.TimestampSnapshot = (ulong)TRandomDevice.NextUInt((uint)(sig.TimestampSinceStart - 5000), (uint)(sig.TimestampSinceStart - 1000)); if (requestEnvelope.Accuracy >= 65) { locationFix.HorizontalAccuracy = TRandomDevice.Choice(new List <float>(new float[] { (float)requestEnvelope.Accuracy, 65, 65, TRandomDevice.Next(66, 80), 200 })); if (_client.Platform == Platform.Ios) { locationFix.VerticalAccuracy = (float)TRandomDevice.Triangular(35, 100, 65); } } else { locationFix.HorizontalAccuracy = (float)requestEnvelope.Accuracy; if (_client.Platform == Platform.Ios) { locationFix.VerticalAccuracy = requestEnvelope.Accuracy > 10 ? (float)TRandomDevice.Choice(new List <double>(new double[] { 24, 32, 48, 48, 64, 64, 96, 128 })) : (float)TRandomDevice.Choice(new List <double>(new double[] { 3, 4, 6, 6, 8, 12, 24 })); } } locationFix.HorizontalAccuracy = (float)Math.Round(locationFix.HorizontalAccuracy, GEOLOCATION_PRECISION); locationFix.VerticalAccuracy = (float)Math.Round(locationFix.VerticalAccuracy, GEOLOCATION_PRECISION); if (_client.Platform == Platform.Ios) { sig.ActivityStatus = new Signature.Types.ActivityStatus() { Stationary = true }; sig.ActivityStatus.Tilting |= TRandomDevice.NextDouble() > 0.50; if (TRandomDevice.NextDouble() > 0.95) { // No reading for roughly 1 in 20 updates locationFix.Course = -1; locationFix.Speed = -1; } else { // Course is iOS only. locationFix.Course = GetCourse(); // Speed is iOS only. locationFix.Speed = (float)TRandomDevice.Triangular(0.2, 4.25, 1); } } sig.LocationFix.Add(locationFix); string envelopString = JsonConvert.SerializeObject(requestEnvelope); var hashRequest = new HashRequestContent() { Latitude64 = BitConverter.DoubleToInt64Bits(currentLocation.Latitude), Longitude64 = BitConverter.DoubleToInt64Bits(currentLocation.Longitude), Accuracy64 = BitConverter.DoubleToInt64Bits(requestEnvelope.Accuracy), AuthTicket = ticketBytes, SessionData = _sessionHash.ToByteArray(), Requests = new List <byte[]>(), Timestamp = sig.Timestamp }; foreach (var request in requestEnvelope.Requests) { hashRequest.Requests.Add(request.ToByteArray()); } var res = await _client.Hasher.RequestHashesAsync(hashRequest).ConfigureAwait(false); foreach (var item in res.RequestHashes) { sig.RequestHash.Add(((ulong)item)); } sig.LocationHash1 = (int)res.LocationAuthHash; sig.LocationHash2 = (int)res.LocationHash; var encryptedSignature = new RequestEnvelope.Types.PlatformRequest { Type = PlatformRequestType.SendEncryptedSignature, RequestMessage = new SendEncryptedSignatureRequest { EncryptedSignature = ByteString.CopyFrom(_client.Cryptor.Encrypt(sig.ToByteArray(), (uint)_client.StartTime)) }.ToByteString() }; return(encryptedSignature); }
public static async Task HandleAccountAfterCreation(Configuration config, AccountCreationResult account) { var random = new TRandom(); POGOLib.Official.Configuration.Hasher = new PokeHashHasher(config.TutorialSettings.HashKey); var client = await GetSession(new PtcLoginProvider(account.Username, account.Password), config.TutorialSettings.Latitude, config.TutorialSettings.Longitude); if (!await client.StartupAsync()) { throw new SessionFailedError(); } if (config.TutorialSettings.Level2 || config.TutorialSettings.Level5) { var ts = await Tutorial.GetTutorialState(client); await Tutorial.CompleteTutorial(client, ts); // Level 2: Stop here. // Level 5: Keep going. if (config.TutorialSettings.Level5) { while (client.Player.Stats.Level < 5) { var lat = client.Player.Latitude + random.NextDouble(0.005, -0.005); var lng = client.Player.Longitude + random.NextDouble(0.005, -0.005); client.Player.SetCoordinates(lat, lng); foreach (var cell in client.Map.Cells) { foreach (var pokemon in cell.CatchablePokemons) { if (DistanceBetweenPlaces(client.Player.Longitude, client.Player.Latitude, pokemon.Latitude, pokemon.Longitude) <= client.GlobalSettings.MapSettings .EncounterRangeMeters / 1000) { var encRes = EncounterResponse.Parser.ParseFrom(await client.RpcClient. SendRemoteProcedureCallAsync(new Request { RequestType = RequestType.Encounter, RequestMessage = new EncounterMessage { EncounterId = pokemon.EncounterId, SpawnPointId = pokemon.SpawnPointId, PlayerLatitude = client.Player.Latitude, PlayerLongitude = client.Player.Longitude }.ToByteString() })); await Task.Delay(random.Next(825, 1250)); if (encRes.Status == EncounterResponse.Types.Status.EncounterSuccess) { while (true) { var r = CatchPokemonResponse.Parser.ParseFrom( await client.RpcClient.SendRemoteProcedureCallAsync(new Request { RequestType = RequestType.CatchPokemon, RequestMessage = new CatchPokemonMessage { EncounterId = pokemon.EncounterId, HitPokemon = true, SpawnPointId = pokemon.SpawnPointId, NormalizedHitPosition = 1, NormalizedReticleSize = random.NextDouble(1.7, 1.95), Pokeball = ItemId.ItemPokeBall, SpinModifier = 1 }.ToByteString() })); if (r.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess || r.Status == CatchPokemonResponse.Types.CatchStatus.CatchEscape) { break; } } } } } foreach (var fort in cell.Forts) { if (DistanceBetweenPlaces(client.Player.Longitude, client.Player.Latitude, fort.Longitude, fort.Latitude) <= client.GlobalSettings.FortSettings.InteractionRangeMeters / 1000) { if (fort.Type == FortType.Checkpoint) { await client.RpcClient.SendRemoteProcedureCallAsync(new Request { RequestType = RequestType.FortDetails, RequestMessage = new FortDetailsMessage { FortId = fort.Id, Latitude = fort.Latitude, Longitude = fort.Longitude }.ToByteString() }); await Task.Delay(random.Next(600, 750)); await client.RpcClient.SendRemoteProcedureCallAsync(new Request { RequestType = RequestType.FortSearch, RequestMessage = new FortSearchMessage { FortId = fort.Id, FortLatitude = fort.Latitude, FortLongitude = fort.Longitude, PlayerLatitude = client.Player.Latitude, PlayerLongitude = client.Player.Longitude }.ToByteString() }); } } } } } } } }
//creating group public double[] CreateGroup(int GroupSize) { //filling whole group with 0 TRandom rnd = new TRandom(); double[] Group = new double[GroupSize]; for (int i = 0; i < GroupSize; i++) { Group[i] = 0; } //checking size of each group int checkVertexAmount = GroupSize % 3; int normalNumber = (GroupSize - checkVertexAmount) / 3; //creating group if vertex amount is divided by 3 if (checkVertexAmount == 0) { for (int i = 1; i < 4; i++) { for (int j = 0; j < normalNumber; j++) { int index = rnd.Next(0, GroupSize); if (Group[index] == 0) { Group[index] = i; } else { j--; } } } } //creating group if exactly one of groups is bigger than others if (checkVertexAmount == 1) { int OneMore = rnd.Next(1, 3); for (int i = 1; i < 4; i++) { for (int j = 0; j < normalNumber; j++) { int index = rnd.Next(0, GroupSize); if (Group[index] == 0) { Group[index] = i; } else { j--; } } } for (int i = 0; i < GroupSize; i++) { if (Group[i] == 0) { Group[i] = OneMore; } } } //creating group if exactly one group size is less than others if (checkVertexAmount == 2) { int OneBonus = rnd.Next(1, 3); int TwoBonus = rnd.Next(1, 3); while (TwoBonus == OneBonus) { TwoBonus = rnd.Next(1, 3); } for (int i = 1; i < 4; i++) { for (int j = 0; j < normalNumber; j++) { int index = rnd.Next(0, GroupSize); if (Group[index] == 0) { Group[index] = i; } else { j--; } } } for (int i = 0; i < GroupSize; i++) { if (Group[i] == 0) { Group[i] = OneBonus; break; } } for (int i = 0; i < GroupSize; i++) { if (Group[i] == 0) { Group[i] = TwoBonus; } } } return Group; }
/// <summary> /// Gets the next pseudo-random integer between the specified minValue and maxValue inclusive /// </summary> /// <param name="minValue">Inclusive minimum result</param> /// <param name="maxValue">Non-inclusive maximum result</param> /// <returns>Returns a pseudo-random integer between the specified minValue and maxValue inclusive</returns> /// <exception cref="ArgumentOutOfRangeException">Thrown if maxValue equals Int32.MaxValue</exception> public int Next(int minValue, int maxValue) { _numberGenerated++; return(_random.Next(minValue, maxValue)); }