public override void SetUp() { base.SetUp(); INDEX_SIZE = AtLeast(2000); Index = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), Index); RandomGen random = new RandomGen(this, Random()); for (int i = 0; i < INDEX_SIZE; ++i) // don't decrease; if to low the { // problem doesn't show up Document doc = new Document(); if ((i % 5) != 0) // some documents must not have an entry in the first { // sort field doc.Add(NewStringField("publicationDate_", random.LuceneDate, Field.Store.YES)); } if ((i % 7) == 0) // some documents to match the query (see below) { doc.Add(NewTextField("content", "test", Field.Store.YES)); } // every document has a defined 'mandant' field doc.Add(NewStringField("mandant", Convert.ToString(i % 3), Field.Store.YES)); writer.AddDocument(doc); } Reader = writer.Reader; writer.Dispose(); Query = new TermQuery(new Term("content", "test")); }
/*public TestCustomSearcherSort(System.String name):base(name) { }*/ /*[STAThread] public static void Main(System.String[] argv) { // TestRunner.run(suite()); // {{Aroush-2.9}} how is this done in NUnit? }*/ /*public static Test suite() { return new TestSuite(typeof(TestCustomSearcherSort)); }*/ // create an index for testing private Directory GetIndex() { RAMDirectory indexStore = new RAMDirectory(); IndexWriter writer = new IndexWriter(indexStore, new StandardAnalyzer(Util.Version.LUCENE_CURRENT), true, IndexWriter.MaxFieldLength.LIMITED); RandomGen random = new RandomGen(this, NewRandom()); for (int i = 0; i < INDEX_SIZE; ++i) { // don't decrease; if to low the problem doesn't show up Document doc = new Document(); if ((i % 5) != 0) { // some documents must not have an entry in the first sort field doc.Add(new Field("publicationDate_", random.GetLuceneDate(), Field.Store.YES, Field.Index.NOT_ANALYZED)); } if ((i % 7) == 0) { // some documents to match the query (see below) doc.Add(new Field("content", "test", Field.Store.YES, Field.Index.ANALYZED)); } // every document has a defined 'mandant' field doc.Add(new Field("mandant", System.Convert.ToString(i % 3), Field.Store.YES, Field.Index.NOT_ANALYZED)); writer.AddDocument(doc); } writer.Optimize(); writer.Close(); return indexStore; }
public Bullet(Contestant con, Point origin, int dir) { shooter = con; pos = origin; Direction = dir; Console.WriteLine("Bullet shot at " + pos.X + "," + pos.Y + "," + direction); RandomGen r = new RandomGen(); id = r.randomD(1000); }
/// <summary> /// Luodaan peikkoja kentälle satunnaisiin paikkoihin /// </summary> private void LuoPeikko() { for (int i = 0; i < PEIKKOJENMAARA; i++) { double x = RandomGen.NextDouble(Level.Left, Level.Right); double y = RandomGen.NextDouble(Level.Bottom, Level.Top); PhysicsObject peikko = Olio(this, PEIKONLEVEYS, PEIKONKORKEUS, x, y, "peikko", true, true, false, 0, "peikko", Color.Transparent, Shape.Rectangle, true); Add(peikko); //Tehdään ´peikolle polkuaivot PathFollowerBrain peikonAivot = new PathFollowerBrain(200); peikko.Brain = peikonAivot; List <Vector> polku = new List <Vector>(); polku.Add(Vector.FromLengthAndAngle(RandomGen.NextDouble(Screen.Top * 2, Screen.Top * 3), RandomGen.NextAngle())); peikonAivot.Path = polku; peikonAivot.Loop = true; peikonAivot.Speed = 250; } }
public static void GenMap(int numberOfOtherCountries, int bigCountryThickness, double gridCellSize, ref GameObject[,] cells) { int MAP_WIDTH = cells.GetLength(0); int MAP_HEIGHT = cells.GetLength(1); // Grid corner vertices (with slight deform) Vector[,] gridPoints = new Vector[MAP_WIDTH + 1, MAP_HEIGHT + 1]; for (int x = 0; x < MAP_WIDTH + 1; x++) { for (int y = 0; y < MAP_HEIGHT + 1; y++) { gridPoints[x, y] = new Vector(-gridCellSize * (MAP_WIDTH / 2) + x * gridCellSize, gridCellSize * (MAP_HEIGHT / 2) - y * gridCellSize) + RandomGen.NextVector(gridCellSize / 5, gridCellSize / 3); } } IndexTriangle[] idxTriRect = new IndexTriangle[] { new IndexTriangle(0, 2, 1), new IndexTriangle(2, 0, 3) }; for (int x = 0; x < MAP_WIDTH; x++) { for (int y = 0; y < MAP_HEIGHT; y++) { Vector cellPosition = (gridPoints[x, y] + gridPoints[x, y + 1] + gridPoints[x + 1, y] + gridPoints[x + 1, y + 1]) / 4; var polyshape = new Polygon(new ShapeCache( new Vector[] { gridPoints[x, y] - cellPosition, gridPoints[x, y + 1] - cellPosition, gridPoints[x + 1, y + 1] - cellPosition, gridPoints[x + 1, y] - cellPosition }, // corners idxTriRect // triangles ), false); var cell = new GameObject(gridCellSize, gridCellSize, polyshape); cell.Position = cellPosition; //cell.Color = RandomGen.NextColor(); cells[x, y] = cell; } } int freeCellCnt = MAP_WIDTH * MAP_HEIGHT; // 1. Outside is USSR for (int x = 0; x < MAP_WIDTH; x++) { for (int y = 0; y < bigCountryThickness; y++) { cells[x, y].Color = USSR_COLOR; //TODO: Translucient //TODO: Set the contry to the tag cells[x, MAP_HEIGHT - 1 - y].Color = USSR_COLOR; //TODO: Translucient freeCellCnt -= 2; } } for (int y = bigCountryThickness; y < MAP_HEIGHT - bigCountryThickness; y++) { for (int x = 0; x < bigCountryThickness; x++) { cells[x, y].Color = USSR_COLOR; //TODO: Translucient //TODO: Set the contry to the tag cells[MAP_WIDTH - 1 - x, y].Color = USSR_COLOR; //TODO: Translucient freeCellCnt -= 2; } } // 2. You are at the center cells[MAP_WIDTH / 2, MAP_HEIGHT / 2].Color = YOURZISTAN; //TODO: Set tag to point to your country freeCellCnt--; // 3. Other countries are placed randomly for (int i = 0; i < numberOfOtherCountries; i++) { bool foundSpot = false; do { int x = RandomGen.NextInt(1, MAP_WIDTH - 2); int y = RandomGen.NextInt(1, MAP_HEIGHT - 2); if (cells[x, y].Color == Color.White) { freeCellCnt--; cells[x, y].Color = RandomGen.NextColor(); foundSpot = true; //TODO: Set tag to point to a country } } while (!foundSpot); } // Evolve bool foundWhite = false; do { foundWhite = false; List <Tuple <int, int, Color> > toFill = new List <Tuple <int, int, Color> >(); for (int x = 1; x < MAP_WIDTH - 1; x++) { for (int y = 1; y < MAP_HEIGHT - 1; y++) { // Free to fill if (cells[x, y].Color == Color.White) { foundWhite = true; List <Color> nearbyColors = new List <Color>(); for (int dx = -1; dx < 2; dx++) { Color neighbourColor = cells[x + dx, y].Color; if (neighbourColor != Color.White && (neighbourColor != USSR_COLOR || RandomGen.NextInt(10) == 1)) { nearbyColors.Add(neighbourColor); } } for (int dy = -1; dy < 2; dy++) { Color neighbourColor = cells[x, y + dy].Color; if (neighbourColor != Color.White && (neighbourColor != USSR_COLOR || RandomGen.NextInt(10) == 1)) { nearbyColors.Add(neighbourColor); } } if (nearbyColors.Count > 0) { Color mostOccuring = nearbyColors.GroupBy(i => i).OrderByDescending(grp => grp.Count()).Select(grp => grp.Key).First(); // Store into temp list so that for this round it is a level ground toFill.Add(new Tuple <int, int, Color>(x, y, mostOccuring)); } } } } foreach (var tf in toFill) { // Little bit of stochasticity if (RandomGen.NextInt(5) < 4) { cells[tf.Item1, tf.Item2].Color = tf.Item3; freeCellCnt--; } } } while (foundWhite); }
public void Init() { plan = CreateInstance<BuildrPlan>(); rgen = new RandomGen((useSeed) ? (uint)_seed : (uint)Random.Range(0, int.MaxValue)); }
private void MakeCity(ref int XzSpread, string HomeTownName, ref int timesThru, int timeThru) { // The new Town Coord newlocality = new Coord(); // New random choices for the towns coords int newXmaybe = 0; int newZmaybe = 0; int NextValidRandomPatchAmountFromTGOSRange = RandomGen.Next(TownGlobalObjectService.PatchCap, TownGlobalObjectService.PatchFloor); // Get A valid amount for the patch choice int randomPatches = NextValidRandomPatchAmountFromTGOSRange; // For "Distance" comparison float closest = 0; if (timeThru >= TownGlobalObjectService.TownRequests.Count) { newXmaybe = (int)(GetRandomXZrangedInt() * 1) + (RandomGen.FlipACoin() ? (int)MinimumDistance : -(int)MinimumDistance); newZmaybe = (int)(GetRandomXZrangedInt() * 1) + (RandomGen.FlipACoin() ? (int)MinimumDistance : -(int)MinimumDistance); // Test if the hit is closer than we would like, if it is then we need to try again timesThru = 0; while (closest < MinimumDistance + ((RandomGen.FlipACoin()) ? 0 : 1)) { if (timesThru >= ExpandXZsAfterTries) { timesThru = 0; Debug.Log("**********BAILED ON COUNT OUT**************"); XzSpread++; // closest = MinimumDistance +1; // continue; } // ADDED +1! newXmaybe += (RandomGen.FlipACoin() ? (int)MinimumDistance : -(int)MinimumDistance); newZmaybe += (RandomGen.FlipACoin() ? (int)MinimumDistance : -(int)MinimumDistance); // wraps the modulo regardless of sign //newXmaybe = (newXmaybe < 0) ? newXmaybe = -(Mathf.Abs(newXmaybe) % XzSpread) : newXmaybe % XzSpread; //newZmaybe = (newZmaybe < 0) ? newZmaybe = -(Mathf.Abs(newZmaybe) % XzSpread) : newZmaybe % XzSpread; // find a random coord with a magnitude high enough newlocality = new Coord(newXmaybe, newZmaybe); // convert it to 1000* size and 500 Y Vector3 p1 = newlocality.ToTileSizeCeilVector3(); // Debug.LogFormat("{0}", p1); // get hits // Collider[] hitColliders = Physics.OverlapSphere(p1, (MinimumDistance * ratio) * 1000f, layerMask);//, LayerMask.NameToLayer("MAPGEN")); /// Collider[] hitColliders = Physics.OverlapSphere(p1, (MinimumDistance) * 500f, layerMask);//, LayerMask.NameToLayer("MAPGEN")); Coord closetTownFound = TownGlobalObject.GetClosest(newlocality, TownGlobalObject.townsData.Keys.ToList()); //Scale the result based on city size. allow for 1.41 within reason var tinyCityApproxPatchCount = 100; var scalar = (0.002f * CityRatioGrowthApproximationmultiplier * Mathf.Min(TownGlobalObject.townsData[closetTownFound].Patches.Count - tinyCityApproxPatchCount, 10)); closest = Coord.Distance( newlocality, TownGlobalObject.GetClosest( newlocality, TownGlobalObject.townsData.Keys.ToList() ) ) - scalar; //// if we didn't hit at all just place it otherwise check the lengths //if (hitColliders.Length == 0) //{ // // Just skip the next bit and place this directly. // closest = MinimumDistance + 1; // // Debug.LogFormat("{0} is okay as a placement", newlocality); // break; //} //foreach (var hitCollider in hitColliders) //{ // var distance = (p1 - hitCollider.gameObject.transform.position).sqrMagnitude * 0.001f; // if (distance < MinimumDistance) // { // closest = distance; // // Debug.LogFormat(hitCollider.gameObject, "{0} for {1} from {2} at {3}", closest, hitCollider.gameObject.name, "newlocality", p1); // } // // closest = (distance < MinimumDistance) ? distance : closest; //} //// closest = TownGlobalObject.GetClosestMagnitude (newlocality , placesWePlaced); timesThru++; } } else // i < TownGlobalObjectService.TownRequests.Count { //home North etc... newlocality = new Coord( (int)TownGlobalObjectService.TownRequests[timeThru].Coord.x, (int)TownGlobalObjectService.TownRequests[timeThru].Coord.y); // Hometon } TownTileRenderer mrnewlocalityMaker = new TownTileRenderer(); // 0 triggers a random int amount = 0; if (timeThru < TownGlobalObjectService.TownRequests.Count) { if (timeThru == 0) { amount += TownHolder.Instance.MinCitySpreadreq; } else { amount += TownGlobalObjectService.TownRequests[timeThru].PatchesInSize; } } // Fill it with Joy AOTABundle newlocalityBundle = mrnewlocalityMaker.MakeATileBundle(newlocality, true, false, amount); // Debug.Log(TownGlobalObjectService.WorldMultiplier); //Town.Town newlocalitylazyTown; ////Handle the homes case //if (i ==0 ) //{ // newlocalitylazyTown = TownGlobalObject.towns.GetOrAdd(newlocality, k => TownGlobalObject.MakeTown(k, k.x, k.z, 0, 60)); //} //else //{ // newlocalitylazyTown = TownGlobalObject.towns.GetOrAdd(newlocality, k => TownGlobalObject.MakeTown(k, k.x, k.z, 0, randomPatches)); //} // TownGlobalObject.townsData[locality] = TownGlobalObject.MakeTown(locality, locality.x, locality.z); // THIS CONTAINS THE TOWN DATA TownGlobalObject.townsData[newlocality] = newlocalityBundle.town; if (timeThru < TownGlobalObjectService.TownRequests.Count) { TownGlobalObject.townsData[newlocality].name = TownGlobalObjectService.TownRequests[timeThru].Name; newlocalityBundle.town.coord = new Coord( (int)TownGlobalObjectService.TownRequests[timeThru].Coord.x, (int)TownGlobalObjectService.TownRequests[timeThru].Coord.y); } //handle the home case. if (timeThru == 0 && newlocality == new Coord(0)) { TownGlobalObject.townsData[newlocality].name = HomeTownName; TownGlobalObject.homeTown = TownGlobalObject.townsData[newlocality]; } // Debug.Log(TownGlobalObject.townsData[newlocality].name); // Bless it. // TODO: ADD METHOD WERE WE CAN PASS A TOWN newlocalityBundle.MarkisBundledTrue(); newlocalityBundle.MarkIsTileDataInBundleTrue(); TownGlobalObject.bundles[newlocality] = newlocalityBundle; AOTABundle reffedBundle = TownGlobalObject.bundles[newlocality]; //Debug.LogFormat( // "INIT TEST: bundle found for tile {5} town {0}: {7} : {3} with {1} SplineSysBundles and {2} TransitionsListBundles and {4} and {6}", // string.Format("{0}:{1}", newlocality.x, newlocality.z), // reffedBundle.SplineSysBundle.Count(), // reffedBundle.TransitionsListBundle.Count(), // reffedBundle.name, // (reffedBundle.isBundled) ? " is bundled :)" : "is not bundled :(", // newlocality, // (reffedBundle.isTileDataInBundle) ? " Tile Data IS In Bundle :)" : "TILE DATA MISSING!!!!!!!!!!", // reffedBundle.town.name // ); // in here we could then span every X|Z and prerender every likely tile to have it's data float size = CityRatioGrowthApproximationmultiplier * reffedBundle.town.Patches.Count; // rendering 36 tiles by default at max per city int roughTileGuess = (int)Mathf.Max(MinTileRender, Mathf.Min(MaxTileRender, Mathf.Ceil(size * 0.004f))); //return the even above, we will split this in half and use that as out "theoretical middle"; roughTileGuess = (roughTileGuess % 2 == 1) ? roughTileGuess + 1 : roughTileGuess; // Debug.LogFormat("approximate city size is {0} for {2} so roughly a {1} tile square", size , roughTileGuess, reffedBundle.name); // back assign the bundle names from the town for consistency in the editor (manually named and generated cities) reffedBundle.name = reffedBundle.town.name; // assign the non manually assigned cases if (timeThru >= TownGlobalObjectService.TownRequests.Count) { reffedBundle.town.coord = reffedBundle.coord; } if (TownGlobalObject.townsData[reffedBundle.town.coord].TownGameObject == null) { TownGlobalObject.townsData[reffedBundle.town.coord].TownGameObject = new GameObject(reffedBundle.town.name); } //create or use the holder now it has the right name. var go = TownGlobalObject.townsData[reffedBundle.town.coord].TownGameObject; GameObject CityHolder = new GameObject("MAP GEN COLLION HOLDER"); CityHolder.transform.parent = go.transform; CityHolder.transform.localPosition = Vector3.zero; CityHolder.transform.position = new Vector3(newlocality.x * 1000, 400, newlocality.z * 1000); //GameObject CityHolder = Instantiate<GameObject>(Temp, Temp.transform.position, Quaternion.identity); //Debug.LogFormat(CityHolder, "newlocalityBundle is {0} with {1} cells at {2} closest is {3}", // TownGlobalObject.bundles[newlocality].name, // TownGlobalObject.bundles[newlocality].town.Patches.Count, // newlocality, // closest); // add something for every city. float halfsize = size * 0.01f; // Add an item for the HUD // var HUD = Instantiate(TownHolder.Instance.HUDPrefab,CityHolder.transform); // HUD.transform.localPosition = Vector3.zero; var collisionCube = new Cube(reffedBundle.name, TownMeshRendererUtils.GetVertices((int)size, (int)size, -halfsize, -halfsize), halfsize, null, CityHolder.transform, false, false); collisionCube.Transform.localPosition = Vector3.zero; // collisionCube.GameObject.layer = LayerMask.NameToLayer("MAPGEN"); BoxCollider col = collisionCube.GameObject.AddComponent <BoxCollider>(); col.size = new Vector3(size, halfsize, size); // Register our BoxCollider for Disabling later. TownGlobalObject.renderedBoxColliders.Add(col); TownMeshRendererOptions rendererOptions = TownGlobalObjectService.rendererOptions; TownOptions skeletonOptions = TownGlobalObject.bundles[newlocality].town.Options; skeletonOptions.IOC = false; skeletonOptions.Farm = false; skeletonOptions.Roads = false; skeletonOptions.Walls = false; skeletonOptions.CityDetail = false; //TownGlobalObject.MeshRenderer = new TownMeshRenderer ( // reffedBundle.town, // skeletonOptions, // rendererOptions); //// This does the fancy world map colored sections TownGlobalObject.MeshRenderer.GenerateOverlay(); // Debug.LogFormat("{0} {1} ", reffedBundle.name, reffedBundle.town.name); // This does the fancy city overlay over the world map colored sections RenderTownMeshes(ref reffedBundle); // TownGlobalObject.bundles[newlocality].isTileDataInBundle = true; // Destroy(CityHolder); // Assign it back? TownGlobalObject.SetBundle(newlocality, reffedBundle); // TownGlobalObject.bundles[newlocality] = reffedBundle; // UnityEngine.Assertions.Assert.IsTrue( TownGlobalObject.bundles.ContainsKey(newlocality)); // COULD HAVE LOOPED HERE }
/// <summary> /// Generates a random number between min..max inclusive min AND max /// </summary> /// <param name="min"></param> /// <param name="max"></param> /// <returns></returns> public static int Random(int min, int max) { return(RandomGen.Next(min, max + 1)); }
public static int NextValidRandomPatchAmountFromTGOSRange() { return (RandomGen.Next(TownGlobalObjectService.PatchCap, TownGlobalObjectService.PatchFloor)); }
private Vector3 ReturnWigglyVector3(float factor) { return(new Vector3(RandomGen.Next(10, -10) * 0.1f * factor, 0, RandomGen.Next(10, -10) * factor)); }
/// <summary> /// Обработать сообщение. /// </summary> /// <param name="message">Сообщение.</param> /// <returns>Результат обработки. Если будет возрвщено <see langword="null"/>, /// то генератору пока недостаточно данных для генерации нового сообщения.</returns> protected override Message OnProcess(Message message) { DateTimeOffset time; switch (message.Type) { case MessageTypes.Level1Change: { var l1Msg = (Level1ChangeMessage)message; var value = l1Msg.Changes.TryGetValue(Level1Fields.LastTradePrice); if (value != null) { _lastOrderPrice = (decimal)value; } TradeGenerator.Process(message); time = l1Msg.ServerTime; break; } case MessageTypes.Execution: { var execMsg = (ExecutionMessage)message; switch (execMsg.ExecutionType) { case ExecutionTypes.Tick: _lastOrderPrice = execMsg.TradePrice; break; default: return(null); } time = execMsg.ServerTime; break; } case MessageTypes.Time: { var timeMsg = (TimeMessage)message; time = timeMsg.ServerTime; break; } default: return(null); } if (!IsTimeToGenerate(time)) { return(null); } // TODO более реалистичную генерацию, так как сейчас объемы, цены и сделки c потолка var action = RandomGen.GetInt(0, 5); var isNew = action < 3 || _activeOrders.IsEmpty(); ExecutionMessage item; if (isNew) { _lastOrderPrice += RandomGen.GetInt(-MaxPriceStepCount, MaxPriceStepCount) * SecurityDefinition.PriceStep; if (_lastOrderPrice <= 0) { _lastOrderPrice = SecurityDefinition.PriceStep; } item = new ExecutionMessage { OrderId = IdGenerator.GetNextId(), SecurityId = SecurityId, ServerTime = time, OrderState = OrderStates.Active, Volume = Volumes.Next(), Side = RandomGen.GetEnum <Sides>(), Price = _lastOrderPrice, ExecutionType = ExecutionTypes.OrderLog, }; _activeOrders.Enqueue((ExecutionMessage)item.Clone()); } else { var activeOrder = _activeOrders.Peek(); item = (ExecutionMessage)activeOrder.Clone(); item.ServerTime = time; var isMatched = action == 5; ExecutionMessage trade = null; if (isMatched) { trade = (ExecutionMessage)TradeGenerator.Process(message); } if (isMatched && trade != null) { item.Volume = RandomGen.GetInt(1, (int)activeOrder.Volume); item.TradeId = trade.TradeId; item.TradePrice = trade.TradePrice; item.TradeStatus = trade.TradeStatus; // TODO //quote.Trade = TradeGenerator.Generate(time); //item.Volume = activeOrder.Volume; //if (item.Side == Sides.Buy && quote.Trade.Price > quote.Order.Price) // item.TradePrice = item.Price; //else if (item.Side == Sides.Sell && quote.Trade.Price < quote.Order.Price) // item.TradePrice = item.Price; activeOrder.Volume -= item.Volume; if (activeOrder.Volume == 0) { item.OrderState = OrderStates.Done; _activeOrders.Dequeue(); } else { item.OrderState = OrderStates.Active; } } else { item.OrderState = OrderStates.Done; item.IsCancelled = true; _activeOrders.Dequeue(); } } LastGenerationTime = time; return(item); }
/// <summary> /// Aliohjelma aloittaa uuden pelin kutsumalla tarvittavia aliohjelmia ja käynnistämällä laskurit. /// </summary> private void AloitaPeli() { ClearAll(); Level.Background.Image = taustaKuva; //peli käyttää taustakuvaa MediaPlayer.Play("OneMustFall"); MediaPlayer.IsRepeating = true; //KENTTÄ //SetWindowSize(1400, 1000); Level.Width = 900; Level.Height = 800; Gravity = new Vector(0, -600); Camera.ZoomToLevel(); // zoomi on normi lisaaSivut(); Alkuasetelma(); Pelaaja(); AsetaOhjaimet(); LisaaPistelaskuri(); Timer t = new Timer(); t.Interval = 2.22; t.Timeout += delegate { PiirraSuorakulmio(this, RandomGen.NextDouble(Level.Left + 150, Level.Right - 150), RandomGen.NextDouble(Level.Top - 50, Level.Top), RandomGen.NextDouble(130, 220)); }; t.Start(); Timer u = new Timer(); u.Interval = 4.0; u.Timeout += delegate { Pelimerkit(this, RandomGen.NextDouble(Level.Left + 70, Level.Right - 70), RandomGen.NextDouble(Level.Top, Level.Top)); }; u.Start(); Timer v = new Timer(); v.Interval = 10.0; v.Timeout += delegate { Alasimet(this, RandomGen.NextDouble(Level.Left + 100, Level.Right - 100), RandomGen.NextDouble(Level.Top, Level.Top)); }; v.Start(); AddCollisionHandler(player, "alasin", AlasinVsPelaaja); AddCollisionHandler(player, "pelimerkki", Merkinotto); AddCollisionHandler(alaReuna, "alasin", Putoaminen); AddCollisionHandler(alaReuna, "pelimerkki", Putoaminen); AddCollisionHandler(alaReuna, player, PelaajanPutoaminen); AddCollisionHandler(alaReuna, "laatta", Putoaminen); }
private void ChartUpdateTimerOnTick(object sender, EventArgs eventArgs) { if (_historyLoaded && IsRealtime.IsChecked == true) { var nextTick = (ExecutionMessage)_tradeGenerator.Process(new TimeMessage { ServerTime = _lastTime }); if (nextTick != null) { if (_candleTransform.Process(nextTick)) { var candles = _candleBuilder.Process(_mdMsg, _currCandle, _candleTransform); lock (_lock) { foreach (var candle in candles) { _currCandle = candle; _updatedCandles[candle.OpenTime] = Tuple.Create(candle, candle.State == CandleStates.Finished); } } } } _lastTime += TimeSpan.FromSeconds(RandomGen.GetInt(1, 10)); } Tuple <Candle, bool>[] candlesToUpdate; lock (_updatedCandles.SyncRoot) { candlesToUpdate = _updatedCandles.OrderBy(p => p.Key).Select(p => Tuple.Create(p.Value.Item1.ToCandle(_security), p.Value.Item2)).ToArray(); _updatedCandles.Clear(); } var lastCandle = _allCandles.LastOrDefault(); _allCandles.AddRange(candlesToUpdate.Where(c => lastCandle == null || c.Item1.OpenTime != lastCandle.OpenTime).Select(t => t.Item1)); ChartDrawData chartData = null; foreach (var tuple in candlesToUpdate) { var candle = tuple.Item1; var needToFinish = tuple.Item2; if (chartData == null) { chartData = new ChartDrawData(); } if (needToFinish && candle.State != CandleStates.Finished) { candle.State = CandleStates.Finished; } var chartGroup = chartData.Group(candle.OpenTime); lock (_lock) { chartGroup.Add(_candleElement, candle); } foreach (var pair in _indicators.CachedPairs) { chartGroup.Add(pair.Key, pair.Value.Process(candle)); } } if (chartData != null) { Chart.Draw(chartData); } }
void lateInitGauss() { RandomGen.initGauss(-1.0f * bondlength, bondlength, bondlength); }
protected void FinishedMakingNectarCallback() { string msg = null; try { List <Ingredient> fruitsUsed = Inventories.QuickFind <Ingredient>(Target.Inventory); foreach (GameObject obj2 in fruitsUsed) { Target.Inventory.SetNotInUse(obj2); } msg += "1"; if (((fruitsUsed != null) && (fruitsUsed.Count > 0x0)) && (Target.mLastSimToMake != null)) { float num = 0f; float num2 = (((float)RandomGen.NextDouble()) * (NectarMaker.kMaxGlobalValueVariance - NectarMaker.kMinGlobalValueVariance)) + NectarMaker.kMinGlobalValueVariance; int skillLevel = Target.mLastSimToMake.SkillManager.GetSkillLevel(SkillNames.Nectar); float num4 = ((NectarMaker.kLevel10Multiplier - NectarMaker.kLevel0Multiplier) * (((float)skillLevel) / 10f)) + NectarMaker.kLevel0Multiplier; fruitsUsed.Sort(); string str = ""; bool flag = true; Ingredient ingredient = fruitsUsed[0x0]; string key = ""; Dictionary <string, int> ingredients = new Dictionary <string, int>(); if (ingredient != null) { key = ingredient.Data.Key; } msg += "2"; float num5 = 0f; foreach (Ingredient ingredient2 in fruitsUsed) { if (flag && !key.Equals(ingredient2.Data.Key)) { flag = false; } str = str + ingredient2.Data.Key; if (!ingredients.ContainsKey(ingredient2.Data.Key)) { ingredients.Add(ingredient2.Data.Key, 0x1); } else { ingredients[ingredient2.Data.Key]++; } num += ingredient2.Data.NectarValue; num5 += (float)ingredient2.GetQuality(); Target.Inventory.TryToRemove(ingredient2); } msg += "3"; num5 /= (float)fruitsUsed.Count; uint hash = ResourceUtils.HashString32(str); float num7 = 1f; if (!flag) { num7 = NectarMaker.CalculateHashMultiplier(hash); } msg += "4"; float makeStyleValueModifier = Target.GetMakeStyleValueModifier(Target.mLastUsedMakeStyle); int makeStyleBottleModifier = Target.GetMakeStyleBottleModifier(Target.mLastUsedMakeStyle); float baseValue = ((((((num * num2) * num4) * Target.mFlavorMultiplier) * num7) * NectarMaker.kQualityLevelMultiplier[((int)num5) - 0x1]) * Target.mMultiplierFromFeet) * makeStyleValueModifier; int numBottles = (NectarMaker.kNumBottlesPerBatch + Target.mBottleDifference) + makeStyleBottleModifier; NectarSkill skill = Target.mLastSimToMake.SkillManager.GetSkill <NectarSkill>(SkillNames.Nectar); if ((skill != null) && skill.IsNectarMaster()) { numBottles += NectarSkill.kExtraBottlesNectarMaster; } msg += "5"; List <NectarMaker.IngredientNameCount> list2 = new List <NectarMaker.IngredientNameCount>(); foreach (string str3 in ingredients.Keys) { list2.Add(new NectarMaker.IngredientNameCount(str3, ((float)ingredients[str3]) / ((float)fruitsUsed.Count))); } msg += "6"; list2.Sort(); string str4 = ""; string str5 = ""; if (list2.Count > 0x0) { str4 = IngredientData.NameToDataMap[list2[0x0].IngredientName].Name; } if (list2.Count > 0x1) { str5 = IngredientData.NameToDataMap[list2[0x1].IngredientName].Name; } msg += "7"; List <NectarSkill.NectarBottleInfo> topNectarsMade = new List <NectarSkill.NectarBottleInfo>(); if (skill != null) { topNectarsMade = skill.mTopNectarsMade; } msg += "8"; string defaultEntryText = ""; if (string.IsNullOrEmpty(str5)) { defaultEntryText = Common.LocalizeEAString(false, "Gameplay/Objects/CookingObjects/NectarBottle:NectarNameOneFruit", new object[] { str4 }); } else { defaultEntryText = Common.LocalizeEAString(false, "Gameplay/Objects/CookingObjects/NectarBottle:NectarName", new object[] { str4, str5 }); if (defaultEntryText.Length > 0x28) { defaultEntryText = Common.LocalizeEAString(false, "Gameplay/Objects/CookingObjects/NectarBottle:NectarNameOneFruit", new object[] { str4 }); } } msg += "9"; bool nameFound = false; foreach (NectarSkill.NectarBottleInfo info in topNectarsMade) { if (info.mFruitHash == hash) { defaultEntryText = info.mBottleName; nameFound = true; } } msg += "A"; bool promptName = false; string entryKey = "Gameplay/Objects/HobbiesSkills/NectarMaker:"; if (flag) { entryKey = entryKey + "NameBottleDialogJustOneFruit"; } else if (num7 < NectarMaker.kPoorComboThreshold) { entryKey = entryKey + "NameBottleDialogTerribly"; } else if (num7 < NectarMaker.kWellComboThreshold) { entryKey = entryKey + "NameBottleDialogPoor"; } else if (num7 < NectarMaker.kGreatComboThreshold) { entryKey = entryKey + "NameBottleDialogWell"; } else if (num7 < NectarMaker.kAmazingComboThreshold) { entryKey = entryKey + "NameBottleDialogGreat"; promptName = true; } else { entryKey = entryKey + "NameBottleDialogAmazing"; promptName = true; } msg += "B"; string name = defaultEntryText; if (promptName) { if ((!nameFound) && (NRaas.StoryProgression.Main.GetValue <NectarPushScenario.NameGreatNectarOption, bool>())) { name = StringInputDialog.Show(Actor.SimDescription.FullName, Common.LocalizeEAString(entryKey), defaultEntryText, 0x28, StringInputDialog.Validation.ObjectRequireName); } else { List <object> parameters = StoryProgression.Main.Stories.AddGenderNouns(Actor.SimDescription); parameters.Add(defaultEntryText); Common.Notify(Common.Localize("MadeNectar:Results", Actor.IsFemale, parameters.ToArray()), Actor.ObjectId); } } msg += "C"; bool flag2 = false; if (skill != null) { skill.MadeXBottles(numBottles); skill.UsedFruits(fruitsUsed); skill.NectarTypeMade(new NectarSkill.NectarBottleInfo(hash, name, ingredients, (int)baseValue)); flag2 = skill.ReachedMaxLevel(); } msg += "D"; int dateNum = ((int)SimClock.ConvertFromTicks(GameStates.TimeInHomeworld.Ticks, TimeUnit.Weeks)) + 0x1; for (int i = 0x0; i < numBottles; i++) { NectarBottle item = GlobalFunctions.CreateObjectOutOfWorld("NectarBottle", null, new NectarBottleObjectInitParams(hash, name, list2, "Gameplay/Objects/HobbiesSkills/NectarMaker:Weeks", dateNum, baseValue, baseValue, Target.mLastSimToMake, flag2)) as NectarBottle; Target.mBottles.Add(item); EventTracker.SendEvent(EventTypeId.kMadeNectar, Target.mLastSimToMake.CreatedSim, item); } if (Target.mBottles.Count > 0x0) { Target.mCurrentStateMachine.SetActor("nectarBottle", Target.mBottles[0x0]); } msg += "E"; Target.mCurrentStateMachine.RequestState("nectarMaker", "Exit"); Target.mCurrentStateMachine.Dispose(); Target.mCurrentStateMachine = null; Target.mMultiplierFromFeet = 1f; Target.mLastUsedMakeStyle = NectarMaker.MakeNectarStyle.Basic; Target.mLastSimToMake = null; Target.CurrentState = NectarMaker.NectarMakerState.FruitAddable; msg += "F"; } } catch (ResetException) { throw; } catch (Exception e) { Common.Exception(Actor, Target, msg, e); } }
void AloitaPeli() { Vector impulssi = new Vector(RandomGen.NextDouble(100, 500), RandomGen.NextDouble(100, 500)); pallo.Hit(impulssi); }
/// <summary> /// Generates a random number between 0.0 and 1.0. /// </summary> /// <returns> /// A double-precision floating point number greater than /// or equal to 0.0, and less than 1.0. /// </returns> public static double RandomDouble() { return(RandomGen.NextDouble()); }
private void Move_Click(object sender, RoutedEventArgs e) { Chart_OnMoveOrder(SelectedOrder, SelectedOrder.Price + RandomGen.GetInt(-3, 3) * _priceStep); }
protected void TipsFedora() { if (Parent == null) return; var impulssi = new Vector(RandomGen.NextDouble(40, 100) * Poimija.Suunta, RandomGen.NextDouble(40, 100)); this.Hit(impulssi); Mass = double.PositiveInfinity; Game.LoadSoundEffect(AssetsPath + "sound").Play(); Timer.SingleShot(2, Destroy); }
override protected double GetSpeed(ParticleInfo info) { return(RandomGen.NextDouble(min, max)); }
protected override bool OnSendInMessage(Message message) { switch (message.Type) { case MessageTypes.Reset: SendOutMessage(new ResetMessage()); break; case MessageTypes.Connect: SendOutMessage(new ConnectMessage()); break; case MessageTypes.Disconnect: SendOutMessage(new DisconnectMessage()); break; case MessageTypes.SecurityLookup: { var lookupMsg = (SecurityLookupMessage)message; foreach (var id in new[] { "SBER@TQBR" }) { SendOutMessage(new SecurityMessage { SecurityId = id.ToSecurityId(), OriginalTransactionId = lookupMsg.TransactionId, }); } SendSubscriptionResult(lookupMsg); break; } case MessageTypes.MarketData: { var mdMsg = (MarketDataMessage)message; switch (mdMsg.DataType) { case MarketDataTypes.CandleTimeFrame: { if (mdMsg.IsSubscribe) { var start = mdMsg.From.Value; var stop = mdMsg.To.Value; var tf = mdMsg.GetTimeFrame(); // sends subscribed successfully SendSubscriptionReply(mdMsg.TransactionId); const decimal step = 0.01m; for (var curr = start; curr < stop; curr += tf) { var price = RandomGen.GetInt(100, 110); var open = price + RandomGen.GetInt(10) * step; var high = open + RandomGen.GetInt(10) * step; var low = high - RandomGen.GetInt(10) * step; var close = low + RandomGen.GetInt(10) * step; if (high < low) { var d = high; high = low; low = d; } SendOutMessage(new TimeFrameCandleMessage { OriginalTransactionId = mdMsg.TransactionId, OpenPrice = open, HighPrice = high, LowPrice = low, ClosePrice = close, OpenTime = curr, State = CandleStates.Finished, }); } SendSubscriptionResult(mdMsg); } else { // sends unsubscribed successfully SendSubscriptionReply(mdMsg.TransactionId); } break; } default: // not supported other data types SendSubscriptionNotSupported(mdMsg.TransactionId); break; } break; } default: return(false); } return(true); }
private float ReturnWiggly(float factor) { // to simplify changing the random here is an example. // return (((UnityEngine.Random.value - 0.5f) * 2) * factor); return(RandomGen.Next(10, -10) * 0.1f * factor); }
private void StartBtnClick(object sender, RoutedEventArgs e) { if (_batchEmulation != null) { _batchEmulation.Resume(); return; } if (HistoryPath.Folder.IsEmpty() || !Directory.Exists(HistoryPath.Folder)) { MessageBox.Show(this, LocalizedStrings.Str3014); return; } TestingProcess.Value = 0; Curve.Clear(); Stat.Clear(); var logManager = new LogManager(); var fileLogListener = new FileLogListener("sample.log"); logManager.Listeners.Add(fileLogListener); // SMA periods var periods = new List <Tuple <int, int, Color> >(); for (var l = 100; l >= 50; l -= 10) { for (var s = 10; s >= 5; s -= 1) { periods.Add(Tuple.Create(l, s, Color.FromRgb((byte)RandomGen.GetInt(255), (byte)RandomGen.GetInt(255), (byte)RandomGen.GetInt(255)))); } } // storage to historical data var storageRegistry = new StorageRegistry { // set historical path DefaultDrive = new LocalMarketDataDrive(HistoryPath.Folder) }; var timeFrame = TimeSpan.FromMinutes(5); // create test security var security = new Security { Id = "RIZ2@FORTS", // sec id has the same name as folder with historical data Code = "RIZ2", Name = "RTS-12.12", Board = ExchangeBoard.Forts, }; var startTime = new DateTime(2012, 10, 1); var stopTime = new DateTime(2012, 10, 31); var level1Info = new Level1ChangeMessage { SecurityId = security.ToSecurityId(), ServerTime = startTime, } .TryAdd(Level1Fields.PriceStep, 10m) .TryAdd(Level1Fields.StepPrice, 6m) .TryAdd(Level1Fields.MinPrice, 10m) .TryAdd(Level1Fields.MaxPrice, 1000000m) .TryAdd(Level1Fields.MarginBuy, 10000m) .TryAdd(Level1Fields.MarginSell, 10000m); // test portfolio var portfolio = Portfolio.CreateSimulator(); // create backtesting connector _batchEmulation = new BatchEmulation(new[] { security }, new[] { portfolio }, storageRegistry) { EmulationSettings = { MarketTimeChangedInterval = timeFrame, StartTime = startTime, StopTime = stopTime, // count of parallel testing strategies // if not set, then CPU count * 2 //BatchSize = 3, } }; // handle historical time for update ProgressBar _batchEmulation.ProgressChanged += (connector, single, total) => this.GuiAsync(() => TestingProcess.Value = total); _batchEmulation.StateChanged += (oldState, newState) => { var isFinished = _batchEmulation.IsFinished; if (_batchEmulation.State == EmulationStates.Stopped) { _batchEmulation = null; } this.GuiAsync(() => { switch (newState) { case EmulationStates.Stopping: case EmulationStates.Starting: case EmulationStates.Suspending: SetIsEnabled(false, false, false); break; case EmulationStates.Stopped: SetIsEnabled(true, false, false); if (isFinished) { TestingProcess.Value = TestingProcess.Maximum; MessageBox.Show(this, LocalizedStrings.Str3024.Put(DateTime.Now - _startEmulationTime)); } else { MessageBox.Show(this, LocalizedStrings.cancelled); } break; case EmulationStates.Started: SetIsEnabled(false, true, true); break; case EmulationStates.Suspended: SetIsEnabled(true, false, true); break; default: throw new ArgumentOutOfRangeException(newState.ToString()); } }); }; _startEmulationTime = DateTime.Now; var strategies = periods .Select(period => { var series = new CandleSeries(typeof(TimeFrameCandle), security, timeFrame); // create strategy based SMA var strategy = new SampleHistoryTesting.SmaStrategy(series, new SimpleMovingAverage { Length = period.Item1 }, new SimpleMovingAverage { Length = period.Item2 }, null, null, null, null, null) { Volume = 1, Security = security, Portfolio = portfolio, //Connector = connector, // by default interval is 1 min, // it is excessively for time range with several months UnrealizedPnLInterval = ((stopTime - startTime).Ticks / 1000).To <TimeSpan>() }; this.GuiSync(() => { var curveElem = Curve.CreateCurve(LocalizedStrings.Str3026Params.Put(period.Item1, period.Item2), period.Item3, ChartIndicatorDrawStyles.Line); strategy.PnLChanged += () => { var data = new ChartDrawData(); data .Group(strategy.CurrentTime) .Add(curveElem, strategy.PnL); Curve.Draw(data); }; Stat.AddStrategies(new[] { strategy }); }); return(strategy); }); // start emulation _batchEmulation.Start(strategies, periods.Count); }
public static void HandleVisuals() { while (true) { Thread.Sleep(10); lock (LandVehicles) { foreach (Triple <LandVehicle, Point, Point, Zone> landVehicleTriple in LandVehicles) { int speed = 3; LandVehicle vehicle = landVehicleTriple.Item1; if (vehicle.State != EntityState.MOVING) { continue; } Point currentPoint = landVehicleTriple.Item2; Point targetPoint = landVehicleTriple.Item3; int diffX = targetPoint.X - currentPoint.X; int diffY = targetPoint.Y - currentPoint.Y; double length = Math.Sqrt(Math.Pow(diffX, 2) + Math.Pow(diffY, 2)); if (length > speed) { diffX = (int)(diffX / length * speed); diffY = (int)(diffY / length * speed); } landVehicleTriple.Item2 = new Point(currentPoint.X + diffX, currentPoint.Y + diffY); if (landVehicleTriple.Item2.X == targetPoint.X && landVehicleTriple.Item2.Y == targetPoint.Y) { CompleteMove(vehicle.VehicleType, vehicle.Id, landVehicleTriple.Item4); vehicle.CurrentZone = landVehicleTriple.Item4; vehicle.State = EntityState.WAITING_FOR_COMMAND; } } } lock (Passengers) { foreach (Triple <Passenger, Point, Point, Zone> passengerTriple in Passengers) { Passenger passenger = passengerTriple.Item1; Point currentPoint = passengerTriple.Item2; Point targetPoint = passengerTriple.Item3; int diffX = Math.Sign(targetPoint.X - currentPoint.X); int diffY = Math.Sign(targetPoint.Y - currentPoint.Y); if (diffX == 0 && diffY == 0 && passenger.State == EntityState.WAITING_FOR_COMMAND) { int chance = RandomGen.Next(500); if (chance < 1) { passengerTriple.Item3 = GetZonePoint(passengerTriple.Item4); } } passengerTriple.Item2 = new Point(currentPoint.X + diffX, currentPoint.Y + diffY); if (passengerTriple.Item2.X == targetPoint.X && passengerTriple.Item2.Y == targetPoint.Y) { if (passengerTriple.Item1.State == EntityState.MOVING) { CompleteMove(Entity.PASSENGER, passenger.Id, passengerTriple.Item4); } passenger.CurrentZone = passengerTriple.Item4; passenger.State = EntityState.WAITING_FOR_COMMAND; } } } lock (Planes) { foreach (Triple <Plane, Point, Point, Zone> planeTriple in Planes) { int speed = 5; Plane plane = planeTriple.Item1; if (plane.State != EntityState.MOVING) { continue; } Point currentPoint = planeTriple.Item2; Point targetPoint = planeTriple.Item3; int diffX = targetPoint.X - currentPoint.X; int diffY = targetPoint.Y - currentPoint.Y; double length = Math.Sqrt(Math.Pow(diffX, 2) + Math.Pow(diffY, 2)); if (length > speed) { diffX = (int)(diffX / length * speed); diffY = (int)(diffY / length * speed); } planeTriple.Item2 = new Point(currentPoint.X + diffX, currentPoint.Y + diffY); if (planeTriple.Item2.X == targetPoint.X && planeTriple.Item2.Y == targetPoint.Y) { CompleteMove(Entity.PLANE, plane.Id, planeTriple.Item4); plane.CurrentZone = planeTriple.Item4; plane.State = EntityState.WAITING_FOR_COMMAND; } } } } }
private static Security CreateStrike(decimal strike, decimal oi, decimal iv, OptionTypes type, DateTime expiryDate, Security asset, decimal?lastTrade) { var s = new Security { Code = "RI {0} {1}".Put(type == OptionTypes.Call ? 'C' : 'P', strike), Strike = strike, OpenInterest = oi, ImpliedVolatility = iv, HistoricalVolatility = iv, OptionType = type, ExpiryDate = expiryDate, Board = ExchangeBoard.Forts, UnderlyingSecurityId = asset.Id, LastTrade = lastTrade == null ? null : new Trade { Price = lastTrade.Value }, Volume = RandomGen.GetInt(10000), Type = SecurityTypes.Option }; s.BestBid = new Quote(s, s.StepPrice ?? 1m * RandomGen.GetInt(100), s.VolumeStep ?? 1m * RandomGen.GetInt(100), Sides.Buy); s.BestAsk = new Quote(s, s.BestBid.Price.Max(s.StepPrice ?? 1m * RandomGen.GetInt(100)), s.VolumeStep ?? 1m * RandomGen.GetInt(100), Sides.Sell); return(s); }
private int GetRandomXZrangedInt() { return((RandomGen.FlipACoin()) ? -RandomGen.Next(MapSpread - MapMargin) : RandomGen.Next(MapSpread - MapMargin + 1)); }
public void TestMethod1() { IGenerator rGenerate = new RandomGen() }
/// <inheritdoc /> protected override Message OnProcess(Message message) { DateTimeOffset time; switch (message.Type) { case MessageTypes.Board: return(null); case MessageTypes.Level1Change: { var l1Msg = (Level1ChangeMessage)message; var value = l1Msg.TryGetDecimal(Level1Fields.LastTradePrice); if (value != null) { _lastTradePrice = value.Value; } time = l1Msg.ServerTime; break; } case MessageTypes.Execution: { var execMsg = (ExecutionMessage)message; var price = execMsg.TradePrice; if (price != null) { _lastTradePrice = price.Value; } else if (execMsg.ExecutionType != ExecutionTypes.OrderLog) { return(null); } time = execMsg.ServerTime; break; } case MessageTypes.Time: { var timeMsg = (TimeMessage)message; time = timeMsg.ServerTime; break; } default: return(null); } if (!IsTimeToGenerate(time)) { return(null); } var trade = new ExecutionMessage { SecurityId = SecurityId, TradeId = IdGenerator.GetNextId(), ServerTime = time, LocalTime = time, OriginSide = GenerateOriginSide ? RandomGen.GetEnum <Sides>() : (Sides?)null, TradeVolume = Volumes.Next(), ExecutionType = ExecutionTypes.Tick }; var priceStep = SecurityDefinition.PriceStep ?? 0.01m; _lastTradePrice += RandomGen.GetInt(-MaxPriceStepCount, MaxPriceStepCount) * priceStep; if (_lastTradePrice <= 0) { _lastTradePrice = priceStep; } trade.TradePrice = _lastTradePrice; LastGenerationTime = time; return(trade); }
private static Color GetRandomColor() => Color.FromRgb((byte)RandomGen.GetInt(0, 255), (byte)RandomGen.GetInt(0, 255), (byte)RandomGen.GetInt(0, 255));
public void Load(string filename) { try { if (IsLoadForLearning) { TotalDataLines = GetDataLinesCount(filename); } using (var sr = new StreamReader(new FileStream(filename, FileMode.Open, FileAccess.Read), Encoding.GetEncoding(1251))) { int idx = 0; int nrow = 0; string nextline; int classNum = 0; while ((nextline = sr.ReadLine()) != null) { idx++; if (string.IsNullOrWhiteSpace(nextline)) { continue; } string[] blocks = GetStringBlocks(nextline); // header row if (idx == 1) { for (int i = 0; i < blocks.Length; i++) { string cname = blocks[i]; // column name if (!FileColumnByIdx.ContainsKey(i)) { FileColumnByIdx.Add(i, cname); } if (!FileIdxByColumn.ContainsKey(cname)) { FileIdxByColumn.Add(cname, i); } else { Logger.Log("duplicate column name: " + cname + ", exiting"); } } if (TargetName != null) { if (!FileIdxByColumn.ContainsKey(TargetName)) { Logger.Log("Warning: data (" + filename + ") doesn't have a target (" + TargetName + ") column"); //break; } else { TargetIdx = FileIdxByColumn[TargetName]; // target column index } } // id columns foreach (var iname in Ids.Keys) { if (!FileIdxByColumn.ContainsKey(iname)) { throw new InvalidDataException("id column '" + iname + "' not found"); } int sidx = FileIdxByColumn[iname]; if (!_idIdx.ContainsKey(sidx)) { _idIdx.Add(sidx, 1); } } if (Ids.Count > 0) { IdName = GetStringId(Ids.Keys.ToArray()); } // skip columns var toDel = (from t in SkippedColumns.Keys where !FileIdxByColumn.ContainsKey(t) select t).ToList(); toDel.ForEach(c => SkippedColumns.Remove(c)); // count of variables except skipped NVars = FileColumnByIdx.Count - SkippedColumns.Count; continue; } // data row nrow++; if (blocks.Length > FileIdxByColumn.Count) { Logger.Log("error parsing row #" + nrow); continue; } if (RandomGen.GetDouble() >= LoadFactor) { continue; } var row = new DataRow <T>(); // parse target if (TargetName != null && TargetIdx >= 0) { row.Target = ParseValue(blocks[TargetIdx]); } // creating composite id row.Id = GetStringId(blocks); if (string.IsNullOrEmpty(row.Id)) { row.Id = nrow.ToString(); //using row_number if ids not set } // save stats for target value if (!TargetStat.ContainsKey(row.Target)) { TargetStat.Add(row.Target, 0); } TargetStat[row.Target]++; // count by target // class id by target if (!ClassNumByValue.ContainsKey(row.Target)) { ClassNumByValue.Add(row.Target, classNum++); } // target by class id if (!ValueByClassNum.ContainsKey(ClassNumByValue[row.Target])) { ValueByClassNum.Add(ClassNumByValue[row.Target], row.Target); } // --------------------------- loading for learning ------------------------------- if (IsLoadForLearning) { if (LearnRows == null) { LearnRows = new T[TotalDataLines, NVars + 1]; // all variables +1 for target } for (int i = 0, k = 0; i < blocks.Length; i++) { string cval = blocks[i]; string colname = FileColumnByIdx[i]; if (SkippedColumns.ContainsKey(colname)) { continue; } T pval = ParseValue(cval); LearnRows[nrow - 1, k++] = pval; SaveVarDistr(colname, pval); } LearnRows[nrow - 1, NVars] = row.Target; } else { // --------------------------- loading for analyse ----------------------------------- var carray = new T[NVars]; for (int i = 0, k = 0; i < blocks.Length; i++) { string cval = blocks[i]; if (FileColumnByIdx.ContainsKey(i)) { string colname = FileColumnByIdx[i]; if (SkippedColumns.ContainsKey(colname)) { continue; } if (!RowColumnByIdx.ContainsKey(k)) { RowColumnByIdx.Add(k, colname); } if (!RowIdxByColumn.ContainsKey(colname)) { RowIdxByColumn.Add(colname, k); } T pval = ParseValue(cval); carray[k] = pval; k++; SaveVarDistr(colname, pval); } else { Logger.Log("error parsing id=" + row.Id); } } row.Values = carray; if (ProceedRowFunc == null) // don't save row in case of ProceedRowFunc not null { Rows.Add(row); } else { ProceedRowFunc(row); } TotalDataLines++; } if (idx % 12345 == 0) { Logger.Log(idx + " lines loaded"); } if (MaxRowsLoaded != 0 && idx > MaxRowsLoaded) { break; } } GetTargetProbs(); Logger.Log((idx - 1) + " lines loaded;"); } } catch (Exception e) { Logger.Log(e); throw; } }
private void ModifyAnnotation(bool isNew) { Brush RandomBrush() { var b = new SolidColorBrush(Color.FromRgb((byte)RandomGen.GetInt(0, 255), (byte)RandomGen.GetInt(0, 255), (byte)RandomGen.GetInt(0, 255))); b.Freeze(); return(b); } if (_annotation == null) { return; } IComparable x1, x2, y1, y2; var mode = RandomGen.GetDouble() > 0.5 ? AnnotationCoordinateMode.Absolute : AnnotationCoordinateMode.Relative; if (_annotationData == null) { if (mode == AnnotationCoordinateMode.Absolute) { GetMiddle(out var x0, out var y0); x1 = x0 - TimeSpan.FromMinutes(RandomGen.GetInt(10, 60)); x2 = x0 + TimeSpan.FromMinutes(RandomGen.GetInt(10, 60)); y1 = y0 - RandomGen.GetInt(5, 10) * _security.PriceStep ?? 0.01m; y2 = y0 + RandomGen.GetInt(5, 10) * _security.PriceStep ?? 0.01m; } else { x1 = 0.5 - RandomGen.GetDouble() / 10; x2 = 0.5 + RandomGen.GetDouble() / 10; y1 = 0.5 - RandomGen.GetDouble() / 10; y2 = 0.5 - RandomGen.GetDouble() / 10; } } else { mode = _annotationData.CoordinateMode.Value; if (mode == AnnotationCoordinateMode.Absolute) { x1 = (DateTimeOffset)_annotationData.X1 - TimeSpan.FromMinutes(1); x2 = (DateTimeOffset)_annotationData.X2 + TimeSpan.FromMinutes(1); y1 = (decimal)_annotationData.Y1 + _security.PriceStep ?? 0.01m; y2 = (decimal)_annotationData.Y2 - _security.PriceStep ?? 0.01m; } else { x1 = ((double)_annotationData.X1) - 0.05; x2 = ((double)_annotationData.X2) + 0.05; y1 = ((double)_annotationData.Y1) - 0.05; y2 = ((double)_annotationData.Y2) + 0.05; } } _dataThreadActions.Add(() => { var data = new ChartDrawData.AnnotationData { X1 = x1, X2 = x2, Y1 = y1, Y2 = y2, IsVisible = true, Fill = RandomBrush(), Stroke = RandomBrush(), Foreground = RandomBrush(), Thickness = new Thickness(RandomGen.GetInt(1, 5)), }; if (isNew) { data.Text = "random annotation #" + (++_annotationId); data.HorizontalAlignment = HorizontalAlignment.Stretch; data.VerticalAlignment = VerticalAlignment.Stretch; data.LabelPlacement = LabelPlacement.Axis; data.ShowLabel = true; data.CoordinateMode = mode; } var dd = new ChartDrawData(); dd.Add(_annotation, data); Chart.Draw(dd); }); }
public static T Random <T>(this T[] array, RandomGen randomGen) { int randomIndex = randomGen.Range(0, array.Length); return(array[randomIndex]); }
public void UpdateData(Security sec, decimal price) { var ps = sec.PriceStep ?? 1; var list = new List <KeyValuePair <Level1Fields, object> >(); if (RandomGen.GetBool()) { list.Add(new KeyValuePair <Level1Fields, object>(Level1Fields.BestBidPrice, price - RandomGen.GetInt(1, 10) * ps)); } if (RandomGen.GetBool()) { list.Add(new KeyValuePair <Level1Fields, object>(Level1Fields.BestAskPrice, price + RandomGen.GetInt(1, 10) * ps)); } var now = DateTimeOffset.Now; ValuesChanged?.Invoke(sec, list, now, now); }
/// <summary> /// Tehdään taulukko erilaisille karkeille ja luodaan karkit karkkitaulukosta /// </summary> private void LuoKarkki() { string[] karkkitaulukko = { "karkki", "kuva2", "karkki3" }; for (int i = 0; i < KARKKIENMAARA; i++) { PhysicsObject karkki = Olio(this, KARKKIPAIKKA, KARKKIPAIKKA, RandomGen.NextDouble(Level.Left, Level.Right), RandomGen.NextDouble(Level.Bottom, Level.Top), "karkki", false, false, true, 10, RandomGen.SelectOne(karkkitaulukko), RandomGen.NextColor(), Shape.Circle, true); Add(karkki); } }
public Player(string name, ulong seed, int randCount) { playerName = name; ipAddress = string.Empty; randGen = new RandomGen(seed); }