public virtual void Act() { RaycastHit hit; if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, damageDistance)) { var aimAt = hit.collider.gameObject.GetComponent <IBreakable>(); if (aimAt != null) { EventHandler <EventArgs> handler = Used; if (handler != null) { handler(this, EventArgs.Empty); } aimAt.HitBy(this); var isMonoBehavior = aimAt as MonoBehaviour; if (isMonoBehavior != null) { selectorComponent.Select(isMonoBehavior.gameObject); } } } if (_animation != null) { _animation.Play(); } }
public List <Diet> GetDiet(List <Food> foods, DietSummary targetDiet, Configuration configuration) { var currentPopulation = _populationInitializer.InitializePopulation(foods, configuration); var numberOfIndividualsToSelect = (int)(configuration.PopulationSize * configuration.SelectionFactor); var iteration = 0; while (iteration < configuration.MaxIterations) { var ahpSolver = new AhpSolver(); var ahpEvaluations = ahpSolver.Evaluate(currentPopulation, targetDiet); var evaluations = Evaluate(currentPopulation, targetDiet); OutputEvaluation(evaluations, iteration); currentPopulation = _selector.Select(evaluations, numberOfIndividualsToSelect); CrossOver(configuration, currentPopulation, numberOfIndividualsToSelect); Mutate(currentPopulation, foods, configuration); iteration++; } var endEvaluations = Evaluate(currentPopulation, targetDiet); return(currentPopulation.OrderBy(diet => _evaluator.Evaluate(diet, targetDiet)).ToList()); }
protected void PutInSlot(Button slot, IHoldable holdable) { if (slot != null) { var trigger = slot.GetComponent <EventTrigger>(); EventTrigger.Entry entry = new EventTrigger.Entry(); entry.eventID = EventTriggerType.PointerUp; entry.callback.AddListener((data) => { player.TakeInHand(holdable); foreach (var item in AllSlots) { slotSelector.Deselect(item.gameObject); } slotSelector.Select(data.selectedObject); }); trigger.triggers.Add(entry); // set name to slot var text = slot.GetComponentInChildren <Text>(); if (text != null) { text.text = holdable == null ? "Empty" : holdable.ToString(); } } }
public void Select(ModifierKeys modifierKey, ICollection <ITreeItem> rootTreeItems, ITreeItem newSelectedItem, ITreeItem oldSelectedItem) { switch (modifierKey) { case ModifierKeys.Shift: if (_previousSelectionWasShift) { _rangeSelector.Select(rootTreeItems, newSelectedItem, _previousShiftSelection); } else { _rangeSelector.Select(rootTreeItems, newSelectedItem, oldSelectedItem); _previousShiftSelection = oldSelectedItem; } _previousSelectionWasShift = true; break; case ModifierKeys.Control: _previousSelectionWasShift = false; _inverseSelector.Select(rootTreeItems, newSelectedItem); break; default: _previousSelectionWasShift = false; _nullSelector.Select(rootTreeItems, newSelectedItem); break; } }
public string SelectDocument(ISelector selector) { IElementSelector elementSelector = selector as IElementSelector; if (elementSelector != null) { return(elementSelector.Select(Document)); } return(selector?.Select(GetFirstSourceText())); }
public GroupEnumerator(IEnumerable <T1> secuencia, ISelector <T1, K1> selector) { this.elementos = new Dictionary <K1, List <T1> >(); this.selector = selector; foreach (var el in secuencia) { if (this.elementos.ContainsKey(selector.Select(el))) { this.elementos[selector.Select(el)].Add(el); } else { this.elementos.Add(selector.Select(el), new List <T1>()); this.elementos[selector.Select(el)].Add(el); } } this.llaves = this.elementos.Keys.GetEnumerator(); }
public List <NeuralNetwork> NextPopulation(List <NeuralNetwork> currentPopulation) { List <List <double> > genotypes = converter.ToGenotypes(selector.Select(currentPopulation)); List <List <double> > afterCrossGenotypes = mixer.Cross(genotypes, currentPopulation.Count); mutator.Mutate(afterCrossGenotypes); return(converter.ToNetworks(afterCrossGenotypes, currentPopulation[0].Topology)); }
/** * @param selector selector * @return result */ public String SelectDocument(ISelector selector) { if (selector is IElementSelector elementSelector) { return(elementSelector.Select(GetDocument())); } else { return(selector.Select(FirstSourceText)); } }
public bool Select(ISelector <Vector3> selector) { var changed = false; for (var i = 0; i < pointCount; ++i) { changed |= selection.Select(i, selector.Select(GetPoint(i).position)); } return(changed); }
protected override IEnumerator ExecuteState() { while (IsActive.Value) { var state = _stateSelector.Select(); _stateManager.SetState(state); yield return(null); } }
static void Main(String[] args) { while (true) { String tweet = _tweetFactorySelector.Select().SendTweet(); DateTime nextTweetTime = _timingHandler.GetNextTweetTime(); OutputToConsole(tweet, nextTweetTime); Thread.Sleep(nextTweetTime - DateTime.Now); } }
public virtual ISelector Select(Message message) { var iselectors = Selectors.Clone(); ISelector iselector = iselectors.Dequeue(); while (iselectors != null) { if (iselector.Select(message)) { return(iselector); } } return(null); }
public override void Refresh() { var sb = new StringBuilder(); sb.Append("You rule: ").Append(Game.Player.FullName); if (!Game.Player.IsAlive) { sb.Append(" (destroyed by enemies, but could rise again)"); } sb.Append(" Month: ").Append(Date.Today); if (Game.Player.IsAlive) { sb.Append(" Population: ").Append(Game.Player.Provinces.getFamilyPopulation().ToString("N0")) .Append(" (") .Append(Game.Player.Provinces.AllPopsChanges.Where(y => y.Key == null || y.Key is Staff || (y.Key is Province && (y.Key as Province).Country != Game.Player)) .Sum(x => x.Value).ToString("+0;-0;0")) .Append(")"); } sb.Append("\nMoney: ").Append(Game.Player.Cash) .Append(" Tech points: ").Append(Game.Player.Science.Points.ToString("F0")); if (Game.Player.IsAlive) { sb.Append(" Loyalty: ").Append(Game.Player.Provinces.AllPops.GetAverageProcent(x => x.loyalty)) .Append(" Education: ").Append(Game.Player.Provinces.AllPops.GetAverageProcent(x => x.Education)); } if (Game.Player != null) { if (Game.Player.FailedPayments.Income.isNotZero()) { buttonSelector.Select(financeButton.gameObject); financeButton.GetComponent <ToolTipHandler>().RemoveTextStartingWith("\nCan't"); financeButton.GetComponent <ToolTipHandler>().AddText("\nCan't pay for:" + Game.Player.FailedPayments.GetIncomeText()); } else { buttonSelector.Deselect(financeButton.gameObject); financeButton.GetComponent <ToolTipHandler>().RemoveTextStartingWith("\nCan't"); } } generalText.text = sb.ToString(); }
public override ISelectable Select(ISelector selector) { if (selector != null) { List <dynamic> resluts = new List <dynamic>(); foreach (var selectedNode in Elements) { var result = selector.Select(selectedNode); if (result != null) { resluts.Add(result); } } return(new Selectable(resluts)); } throw new SpiderException("Selector is null."); }
public void SelectionPerformance(int size, int count, Optimize opt) { Func <Genotype <DoubleGene>, double> ff = g => g.Gene.Allele; Func <Phenotype <DoubleGene, double> > F = delegate() { return(Phenotype.Of(Genotype.Of(DoubleChromosome.Of(0.0, 100.0)), 1, ff)); }; RandomRegistry.Using(new Random(543455), r => { var population = Enumerable.Range(0, size) .Select(i => F()) .ToPopulation(); ISelector <DoubleGene, double> selector = Selector(); if (!(selector is MonteCarloSelector <DoubleGene, double>)) { var monteCarloSelectionSum = new MonteCarloSelector <DoubleGene, double>() .Select(population, count, opt) .Select(p => p.GetFitness()) .Sum(); var selectionSum = selector .Select(population, count, opt) .Select(p => p.GetFitness()) .Sum(); if (opt == Optimize.Maximum) { Assert.True( selectionSum > monteCarloSelectionSum, $"{selectionSum} <= {monteCarloSelectionSum}"); } else { Assert.True( selectionSum < monteCarloSelectionSum, $"{selectionSum} >= {monteCarloSelectionSum}"); } } }); }
/// <summary> /// updates block held by player - rotates, changes color if building is not allowed, etc /// </summary> public virtual void UpdateBlock() { RaycastHit hit; if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit)) { Vector3 lookingPosition = World.AdjustCoords(hit.point); Vector3 blockPlacingPosition = World.GetIntegerCoords(hit.point); // allow block to sticks to 1 of 4 side of a cell if (allowsXZSnapping && allowsYSnapping) { sideSnapping = World.GetClosestSideXYZ(lookingPosition, blockPlacingPosition); blockPlacingPosition = AdjustSnappingXZ(blockPlacingPosition); blockPlacingPosition = AdjustSnappingY(blockPlacingPosition); } else if (allowsXZSnapping) { sideSnapping = World.GetClosestSideXZ(lookingPosition, blockPlacingPosition); blockPlacingPosition = AdjustSnappingXZ(blockPlacingPosition); } else if (allowsYSnapping) { sideSnapping = World.GetClosestSideY(lookingPosition, blockPlacingPosition); blockPlacingPosition = AdjustSnappingY(blockPlacingPosition); } AdjustSnappingRotation(); this.block.transform.position = blockPlacingPosition; Debug.Log("Looking at (x,y,z)" + lookingPosition + " side is " + sideSnapping); // updates holding block color if (CanBePlaced(World.Get)) { placingAllowedSelector.Select(block); } else { placingDeniedSelector.Select(block); } } }
public static void selectProvince(int number) { if (number < 0 || World.FindProvince(number) == Game.selectedProvince)// same province clicked, hide selection { var lastSelected = Game.selectedProvince; Game.selectedProvince = null; if (lastSelected != null) { //lastSelected.setBorderMaterial(LinksManager.Get.defaultProvinceBorderMaterial); //lastSelected.setBorderMaterials(true); provinceSelector.Deselect(lastSelected.GameObject); } if (provincePanel.isActiveAndEnabled) { provincePanel.Hide(); } } else // new province selected { if (Game.selectedProvince != null)//deal with previous selection { //Game.selectedProvince.setBorderMaterial(LinksManager.Get.defaultProvinceBorderMaterial); //Game.selectedProvince.setBorderMaterials(true); provinceSelector.Deselect(Game.selectedProvince.GameObject); } // freshly selected province Game.selectedProvince = World.FindProvince(number); provinceSelector.Select(Game.selectedProvince.GameObject); //Game.selectedProvince.setBorderMaterial(LinksManager.Get.selectedProvinceBorderMaterial); provincePanel.Show(); if (Game.MapMode == Game.MapModes.Cores) //core map mode { Game.redrawMapAccordingToMapMode(); } } if (buildPanel != null && buildPanel.isActiveAndEnabled) { buildPanel.Refresh(); } }
public Population Replace(Population population) { var newPopulation = new Population(population.Sequence + 1); while (newPopulation.Individuals.Count < Population.Limit) { // Get individuals selected ordered desc by fitness var selected = _selector.Select(population); var firstParent = selected.ElementAt(0).Clone(); var secondParent = selected.ElementAt(1).Clone(); var firstChild = _crossoverOperator.Cross(firstParent, secondParent); var secondChild = _crossoverOperator.Cross(secondParent, firstParent); newPopulation.Individuals.Add(firstParent); newPopulation.Individuals.Add(secondParent); newPopulation.Individuals.Add(firstChild); newPopulation.Individuals.Add(secondChild); } return(newPopulation); }
public override void Body() { try { UIControlBase c = UIControlBase.FindControlByPath(control); if (!c.Exists) { ActualResult = QAliber.RemotingModel.TestCaseResult.Failed; throw new InvalidOperationException("Control not found"); } ISelector selectorPattern = c.GetControlInterface <ISelector>(); if (selectorPattern != null) { selectorPattern.Select(index); ActualResult = QAliber.RemotingModel.TestCaseResult.Passed; } else if (c is HTMLSelect) { ((HTMLSelect)c).SelectItem(index); ActualResult = QAliber.RemotingModel.TestCaseResult.Passed; } else { ActualResult = QAliber.RemotingModel.TestCaseResult.Failed; throw new InvalidOperationException("Control is not list type control"); } } catch (Exception ex) { ActualResult = QAliber.RemotingModel.TestCaseResult.Failed; throw ex; } }
private void SelectionHandler(int index) { _selector.Select(index); }
public IEnumerable<Pair<string, long>> Project(IEnumerable<GraphItem> graphItems, ISelector selector) { if (graphItems.Count() == 0) return new List<Pair<string, long>>(); List<Pair<string, long>> result = new List<Pair<string, long>>(); foreach (var team in graphItems.Select(p => p.Team).Distinct()) { result.Add(new Pair<string, long>(team.Name, graphItems.Where(p => p.Team.Equals(team)).Sum(q => selector.Select(q)))); } return result; }
public IEnumerable<Pair<string, long>> Project(IEnumerable<GraphItem> graphItems, ISelector selector) { if (graphItems.Count() == 0) return new List<Pair<string, long>>(); DateTime start = graphItems.Min(p => p.ProductionDate); DateTime end = graphItems.Max(p => p.ProductionDate); List<Pair<string, long>> result = new List<Pair<string, long>>(); for (DateTime s = start.Date; s <= end.Date; s = s.AddDays(1) ) { result.Add(new Pair<string, long>(s.ToShortDateString(), graphItems.Where(p => p.ProductionDate.Date.Equals(s)).Sum(q => selector.Select(q)))); } return result; }
public void Select(GameObject someObject) { selectorComponent.Select(someObject); }
/// <summary> /// Calculates/generates a next generation based on the given one. /// </summary> /// <param name="population"></param> /// <returns></returns> private Population <GenomeType, ProblemType, WeightType> NextGeneration(Population <GenomeType, ProblemType, WeightType> population) { Population <GenomeType, ProblemType, WeightType> next_population = new Population <GenomeType, ProblemType, WeightType>(true); // do elitims selection. int elitism_count = (int)(population.Count * (_settings.ElitismPercentage / 100f)); next_population.AddRange( population.GetRange( 0, elitism_count)); // do selection/cross-over. //Tools.Core.Output.OutputTextStreamHost.Write(" C:"); int cross_over_count = (int)(population.Count * (_settings.CrossOverPercentage / 100f)) + elitism_count; while (next_population.Count < cross_over_count && next_population.Count < population.Count) { // select two individuals. Individual <GenomeType, ProblemType, WeightType> individual1 = _selector.Select( this, population, null); Individual <GenomeType, ProblemType, WeightType> individual2 = _selector.Select( this, population, new HashSet <Individual <GenomeType, ProblemType, WeightType> >( new Individual <GenomeType, ProblemType, WeightType>[] { individual1 })); // cross-over. Individual <GenomeType, ProblemType, WeightType> new_individual = _crossOverOperation.CrossOver( this, individual1, individual2); new_individual.CalculateFitness(_problem, _fitness_calculator); if (_accept_only_better_on_cross_over) { if (new_individual.Fitness.CompareTo(individual1.Fitness) < 0 && new_individual.Fitness.CompareTo(individual2.Fitness) < 0) { // add to the new population. next_population.Add(new_individual); } else { //next_population.Add(individual1); if (individual2.Fitness.CompareTo(individual1.Fitness) < 0) { // add to the new population. next_population.Add(individual2); } else { next_population.Add(individual1); } } } else { // add to the new population. next_population.Add(new_individual); } //this.ReportNew("Crossing over population!", next_population.Count, population.Count); //Tools.Core.Output.OutputTextStreamHost.Write("."); } // do mutation to generate the rest of the population. int mutation_count = (int)(population.Count * (_settings.MutationPercentage / 100f)) + cross_over_count; int mutation_count_max_tries = mutation_count * 2; // try mutation 10 times more. int mutation_idx_absolute = 0; //Tools.Core.Output.OutputTextStreamHost.Write(" m:"); while (next_population.Count < mutation_count && next_population.Count < population.Count) { // get random individual. int individual_to_mutate_idx = this.Random.Next(population.Count); Individual <GenomeType, ProblemType, WeightType> individual_to_mutate = population[individual_to_mutate_idx]; // mutate. Individual <GenomeType, ProblemType, WeightType> mutation = _mutation_operation.Mutate( this, individual_to_mutate); //if (!mutation.Equals(individual_to_mutate)) //{ // do not add indentical ones. // add to population. if (_accept_only_better_on_mutation) { mutation.CalculateFitness(_problem, _fitness_calculator); if (mutation.Fitness.CompareTo(individual_to_mutate.Fitness) < 0) { next_population.Add(mutation); } } else { next_population.Add(mutation); } // //Tools.Core.Output.OutputTextStreamHost.Write("."); // this.ReportNew("Mutating population!", next_population.Count, population.Count); //} // increase the absolute count. mutation_idx_absolute++; if (mutation_idx_absolute > mutation_count_max_tries) { // stop trying to mutate not new individuals could be found. break; } } while (next_population.Count < population.Count) { // get random individual. int individual_to_mutate_idx = this.Random.Next(population.Count); Individual <GenomeType, ProblemType, WeightType> individual = population[individual_to_mutate_idx]; // place in the new population. next_population.Add(individual); this.ReportNew("Filling population!", next_population.Count, population.Count); } return(next_population); }
/// <summary> /// 通过查询器查找结果 /// </summary> /// <param name="selector">查询器</param> /// <returns>查询接口</returns> public override ISelectable Select(ISelector selector) { selector.NotNull(nameof(selector)); return(selector.Select(_text)); }
public static IQueryable <TResult> Select <TSource, TResult>( this IQueryable <TSource> query, ISelector selector) { return(query.Select(selector.Select <TSource, TResult>())); }
public void Solve(BionicModel model, BionicSolverSettings settings) { if (model == null) { throw new ArgumentNullException("model"); } if (settings == null) { throw new ArgumentNullException("settings"); } OnSolverStarting(new EventArgs()); IInitialPopulationGenerator initializer = InitialPopulationGeneratorFactory.CreateInitialPopulationGenerator(); ISelector selector = SelectorFactory.CreateSelector(); IBreeder breeder = BreederFactory.CreateBreeder(); // 1. Zeroing generation number model.CurrentGeneration = 0; OnSolverStarted(new EventArgs()); // 2. Creating initial population CopyIndividuals(initializer.GenerateInitialPopulation(settings.InitialPopulationSize, model.Attributes), model.CurrentPopulation); CalculateFitness(model, model.CurrentPopulation, settings); model.ApplyFunctionalConstraints(); OnPopulationUpdated(new EventArgs()); while (model.CurrentGeneration < settings.MaxGenerations) { // 3. Selecting most fit individuals IEnumerable <Individual> fitIndividuals = selector.Select(model.CurrentPopulation, model.FitnessCriterion, settings.SelectionCap); if (fitIndividuals.Count() == 0) { OnSolverFinished(new SolverFinishedEventArgs("All individuals are inactive")); return; } // Selected subpopulation will contain only selected active individuals Population selectedSubPopulation = new Population(fitIndividuals.Count()); foreach (Individual fitIndividual in fitIndividuals) { selectedSubPopulation.Add(fitIndividual); } // 4. Breeding the selected ones IEnumerable <Individual> descendants = breeder.Breed(selectedSubPopulation, model.Attributes, settings.DescendantsRangePercent, settings.DescendantsNum, model.CurrentGeneration + 1); if (descendants.Count() == 0) { OnSolverFinished(new SolverFinishedEventArgs("No descendants was created")); return; } // Descendants subpopulation will contain only new individuals Population descendantsSubPopulation = new Population(descendants.Count()); foreach (Individual descendant in descendants) { descendantsSubPopulation.Add(descendant); } // 5. Calculating fitness of the descendants CalculateFitness(model, descendantsSubPopulation, settings); // At this point, all descendants are still active, although // there may be individuals that don't fit f. c. // 6. Forming new population if (settings.ApplyElitism) { // First unite descendants with their parents (elitism) // We can do this without fear of ID collision because this // was taken into account on the breeding step CopyIndividuals(descendantsSubPopulation, selectedSubPopulation); // Now this united population becomes current, we just // throw away old individuals model.CurrentPopulation.Clear(); CopyIndividuals(selectedSubPopulation, model.CurrentPopulation); } else { // We throw away parents and old individuals, // descendants are taking over the place model.CurrentPopulation.Clear(); CopyIndividuals(descendantsSubPopulation, model.CurrentPopulation); } model.ApplyFunctionalConstraints(); // 7. Updating current generation number model.CurrentGeneration = model.CurrentPopulation.Max(ind => ind.Value.GenerationNumber); OnPopulationUpdated(new EventArgs()); } OnSolverFinished(new SolverFinishedEventArgs()); }
/// <summary> /// 通过查询器查找结果 /// </summary> /// <param name="selector">查询器</param> /// <returns>查询接口</returns> public override ISelectable Select(ISelector selector) { selector.NotNull(nameof(selector)); return(selector.Select(_token.ToString())); }
/// <summary> /// 通过查询器查找结果 /// </summary> /// <param name="selector">查询器</param> /// <returns>查询接口</returns> public override ISelectable Select(ISelector selector) { selector.NotNull(nameof(selector)); return(selector.Select(_node.OuterHtml)); }
public IList <JsonElement> Select(JsonElement root, JsonSelectorOptions?options = null) { DynamicResources resources; ProcessingFlags flags = _requiredFlags; if (options != null) { if (options.NoDuplicates) { flags |= ProcessingFlags.NoDups; } if (options.Sort) { flags |= ProcessingFlags.SortByPath; } resources = new DynamicResources(options); } else { resources = new DynamicResources(JsonSelectorOptions.Default); } var values = new List <JsonElement>(); if ((flags & ProcessingFlags.SortByPath | flags & ProcessingFlags.NoDups) != 0) { var nodes = new List <PathValuePair>(); INodeReceiver receiver = new NodeReceiver(nodes); if (resources.Options.ExecutionMode == PathExecutionMode.Parallel) { receiver = new SynchronizedNodeReceiver(receiver); } _selector.Select(resources, new JsonElementValue(root), JsonLocationNode.Root, new JsonElementValue(root), receiver, flags, 0); if (nodes.Count > 1) { if ((flags & ProcessingFlags.SortByPath) != 0) { nodes.Sort(); } if ((flags & ProcessingFlags.NoDups) != 0) { var index = new HashSet <PathValuePair>(nodes); foreach (var node in nodes) { if (index.Contains(node)) { values.Add(node.Value); index.Remove(node); } } } else { foreach (var node in nodes) { values.Add(node.Value); } } } else { foreach (var node in nodes) { values.Add(node.Value); } } } else { INodeReceiver receiver = new JsonElementReceiver(values); if (resources.Options.ExecutionMode == PathExecutionMode.Parallel) { receiver = new SynchronizedNodeReceiver(receiver); } _selector.Select(resources, new JsonElementValue(root), JsonLocationNode.Root, new JsonElementValue(root), receiver, flags, 0); } return(values); }
public override ISelectable Select(ISelector selector) { if (selector != null) { List<dynamic> resluts = new List<dynamic>(); foreach (var selectedNode in Elements) { var result = selector.Select(selectedNode); if (result != null) { resluts.Add(result); } } return new Selectable(resluts); } throw new SpiderExceptoin("Selector is null."); }