public IList <Book> ApplyDiscounts(IList <Book> books) { var discounts = _locator.GetDiscountsFor(books) .OrderBy(x => x.Percentage); var bestDiscountedBooks = books; for (int i = 1; i <= discounts.Count(); i++) { var testDiscountBooks = books.Clone(); foreach (var discount in discounts.Take(i).OrderByDescending(x => x.Percentage)) { while (discount.IsSatisfiedBy(testDiscountBooks)) { discount.Apply(testDiscountBooks); } } if (testDiscountBooks.Sum(x => x.Price) < bestDiscountedBooks.Sum(x => x.Price)) { bestDiscountedBooks = testDiscountBooks; } } return(bestDiscountedBooks); }
public void TestCloneList() { IList <Item> list = GenerateTestList(); IList <Item> clone = list.Clone(); Assert.IsInstanceOfType(clone, typeof(IList <Item>)); }
public IList <IChromosome <T> > Solve <T>(IList <IChromosome <T> > population) { if (population.Count == 0) { return(population); } var currentPopulation = population.Clone(); do { var newPopulation = new List <IChromosome <T> >(); while (newPopulation.Count < _parameters.PopulationSize) { var selected = SelectionMethod.Selection(currentPopulation); var chromozome = CrossoverAlgorithm.RunCrossover(selected.Item1, selected.Item2, _parameters.CrossOverProbability); chromozome = MutationAlgorithm.RunMutation(chromozome, _parameters.MutationProbability); chromozome.FintnessValue = EvaluationMethod.Evaluate(chromozome); newPopulation.Add(chromozome); } currentPopulation = newPopulation; } while (!Convirged()); return(currentPopulation); }
} // CopyTo public static List <TermsAndConditions> Inherit([CanBeNull] List <TermsAndConditions> list, [CanBeNull] IList <TermsAndConditions> from) { if (from == null) { return(null); } if ((list is null) || (list.Count == 0)) { return(from.Clone()); } // if var d = new HashSet <string>(StringComparer.InvariantCultureIgnoreCase); foreach (var terms in list) { d.Add(terms.Language ?? "<null>"); } // foreach foreach (var fromTerms in from) { if (d.Contains(fromTerms.Language ?? "<null>")) { continue; } d.Add(fromTerms.Language ?? "<null>"); list.Add(fromTerms.Clone()); } // foreach return(list); } // if
private void RegisterForRemoval(IList <T> items, IChangeSet <T> changes) { foreach (var change in changes) { switch (change.Reason) { case ListChangeReason.Replace: change.Item.Previous.IfHasValue(t => _callback(t)); break; case ListChangeReason.Remove: _callback(change.Item.Current); break; case ListChangeReason.RemoveRange: change.Range.ForEach(_callback); break; case ListChangeReason.Clear: items.ForEach(_callback); break; } } items.Clone(changes); }
/// <summary> /// Creates a new ParserContext object. /// </summary> /// <param name="productionRules">The list of production rules.</param> /// <param name="tokens">The tokenised input to parse.</param> public ParserContext(IList <ProductionRule> productionRules, IList <Token> tokens) { this.ProductionRules = productionRules; this.Tokens = tokens.Clone(); this.CurrentTokenIndex = 0; this.Results = new Stack <object>(); this.CurrentProductionRule = new Stack <ProductionRule>(); }
public LogItem(ActionType actionType, IList <T> data) { CreateDate = DateTime.Now; ActionType = actionType; if (data != null) { OldData = (T)data.Clone(); } }
public FunctionNode Clone() { return(new FunctionNode() { Identifier = Identifier, Args = Args.Clone(), Metadata = Metadata.Clone(), }); }
public UnitHistory(IList <Feature> ustats) { var lqName = ustats.First(s => s.name == "UnitName").value; var lqId = ustats.First(s => s.name == "UnitID").value; UnitID = lqId; UnitName = lqName; UnitStats = ustats.Clone(); }
public Individual <T> RunGeneticAlgorithm(int maxIterations = 100, Action <string> output = null) { individuals = new List <Individual <T> >(); //Initialize the population with a population that is 1/10th the populationSize var tempPopulation = (int)Math.Floor(populationSize / 10.0); for (var i = 0; i < tempPopulation; ++i) { var copy = initialSolution.Clone(); copy.Shuffle(); var solution = new Individual <T>(copy, mutationRate, fitnessFunction, crossoverPoint); AddIndividual(solution); } if (output != null) { output(string.Format( "Starting optimization. Initial population has been seeded with {0} individuals.", individuals.Count)); individuals.ForEach(t => { if (fittest == null || t.Fitness < fittest.Fitness) { fittest = t; } output((string.Format("Fitness = {0}", t.Fitness))); }); } fittest = individuals[random.Next(0, tempPopulation - 1)]; for (var i = 0; i < maxIterations; ++i) { if (output != null) { output(string.Format("Starting iteration: {0}", i)); } var pre = fittest.Fitness; Evolve(output); if (output != null) { output(string.Format("Iteration: {0}, Average fitness: {1}, Fittest: {2}, Difference: {3}", i, avgFitness, fittest.Fitness, fittest.Fitness - pre)); } } return(fittest); }
public virtual IList <LocalizablePropertyValues> Map(ILanguageEntity languageEntity, IList <LocalizablePropertyValues> entityLocalizableProperties) { Type t = typeof(TCommerceEntity); var commerceEntity = Activator.CreateInstance(t) as TCommerceEntity; ILanguageEntity <TSourceEntity> l = languageEntity as ILanguageEntity <TSourceEntity>; if (l == null) { Context.Abort(Context.CommerceContext.AddMessage(Context.GetPolicy <KnownResultCodes>().Error, "LanguageEntityMissing", null, "Language entity cannot be null").Result, Context); } else { MapLocalizeValues(l.Entity, commerceEntity); if (entityLocalizableProperties == null) { entityLocalizableProperties = LocalizablePropertyListManager.GetEntityProperties(t, Context); entityLocalizableProperties = entityLocalizableProperties?.Clone(); } if (entityLocalizableProperties == null || !entityLocalizableProperties.Any()) { return(new List <LocalizablePropertyValues>()); } var properties = TypePropertyListManager.GetProperties(t); foreach (var localizablePropertyValues in entityLocalizableProperties) { if (!string.IsNullOrEmpty(localizablePropertyValues.PropertyName)) { var propertyInfo = properties.FirstOrDefault(x => x.Name.Equals(localizablePropertyValues.PropertyName, StringComparison.OrdinalIgnoreCase)); if (propertyInfo != null) { var propertyValue = propertyInfo.GetValue(commerceEntity); var parameter = localizablePropertyValues.Parameters.FirstOrDefault(x => x.Key.Equals(languageEntity.Language, StringComparison.OrdinalIgnoreCase)); if (parameter == null) { parameter = new Parameter { Key = languageEntity.Language, Value = null }; localizablePropertyValues.Parameters.Add(parameter); } parameter.Value = propertyValue; } } } } return(entityLocalizableProperties); }
public BlockNode Clone() { return(new BlockNode() { Name = Name.Clone(), Properties = Properties.Clone(), Functions = Functions.Clone(), Children = Children.Clone(), }); }
public static IList <T> RemoveAll <T>(this IList <T> listToRemoveFrom, IList <T> remove) where T : ICloneable { var result = listToRemoveFrom.Clone(); remove.ForEach(value => { listToRemoveFrom.Remove(value); }); return(result); }
public object Clone() { return(new TvHeadendIntegrationInfo { LastEpgUpdate = LastEpgUpdate, LastEpgUpdateSuccessfull = LastEpgUpdateSuccessfull, LastAuthentication = LastAuthentication, AuthenticationSuccessfull = AuthenticationSuccessfull, Channels = Channels.Clone() }); }
private static IChangeSet <T> Virtualise(IList <T> all, ChangeAwareList <T> virtualised, IVirtualRequest request, IChangeSet <T>?changeSet = null) { if (changeSet is not null) { all.Clone(changeSet); } var previous = virtualised; var current = all.Skip(request.StartIndex).Take(request.Size).ToList(); var adds = current.Except(previous); var removes = previous.Except(current); virtualised.RemoveMany(removes); adds.ForEach( t => { var index = current.IndexOf(t); virtualised.Insert(index, t); }); var moves = changeSet.EmptyIfNull().Where(change => change.Reason == ListChangeReason.Moved && change.MovedWithinRange(request.StartIndex, request.StartIndex + request.Size)); foreach (var change in moves) { // check whether an item has moved within the same page var currentIndex = change.Item.CurrentIndex - request.StartIndex; var previousIndex = change.Item.PreviousIndex - request.StartIndex; virtualised.Move(previousIndex, currentIndex); } // find replaces [Is this ever the case that it can be reached] for (var i = 0; i < current.Count; i++) { var currentItem = current[i]; var previousItem = previous[i]; if (ReferenceEquals(currentItem, previousItem)) { continue; } var index = virtualised.IndexOf(currentItem); virtualised.Move(i, index); } return(virtualised.CaptureChanges()); }
public static void Main(String[] args) { IList <int> lst = new ArrayList <int>(); lst.AddAll(new int[] { 2, 3, 5, 7, 11, 13 }); Console.WriteLine(lst); IList <int> v1 = lst.ViewOf(7); Console.WriteLine(v1); IList <int> v2 = (IList <int>)v1.Clone(); v2.Slide(1); Console.WriteLine(v1); Console.WriteLine(v2); }
public static IList <T> Shuffle <T>(this IList <T> list) where T : ICloneable { var clonedList = list.Clone(); int n = clonedList.Count; while (n > 1) { n--; int k = rng.Next(n + 1); T value = clonedList[k]; clonedList[k] = clonedList[n]; clonedList[n] = value; } return(clonedList); }
// Token: 0x0600003D RID: 61 RVA: 0x000029B4 File Offset: 0x00000BB4 public static object TryClone(object obj) { ICloneable cloneable = obj as ICloneable; if (cloneable != null) { return(cloneable.Clone()); } IList list = obj as IList; if (list != null) { return(list.Clone()); } return(obj); }
public static object TryClone(object obj) { ICloneable ic = obj as ICloneable; if (ic != null) { return(ic.Clone()); } IList list = obj as IList; if (list != null) { return(list.Clone()); } return(obj); }
public IList <double[]> SolveSingleThread(int iterationCount = 1000, double bandwidth = 5) { IList <double[]> centroids = Data; int iteration = 0; while (iteration < iterationCount) { IList <double[]> newCentroids = centroids.Clone(); for (int i = 0; i < centroids.Count; i++) { double[] centroid = centroids[i]; IList <int> indexes = new List <int>(); IList <double[]> neighbors = new List <double[]>(); for (int j = 0; j < Data.Count; j++) { double[] sample = Data[j]; if (EuclideanDistance(centroid, sample) < bandwidth) { neighbors.Add(sample); indexes.Add(j); } if (neighbors.Count == 0) { continue; } double[] newCentroid = Average(neighbors); for (int k = 0; k < neighbors.Count; k++) { newCentroids[indexes[k]] = newCentroid; } } } centroids = newCentroids; iteration++; } centroids = GetUnique(centroids); return(centroids); }
private void Execute(int position) { if (position == 0) { Results.Add(list.Clone()); return; } for (var i = 0; i < position; i++) { Execute(position - 1); if (i < position - 1) { var t = list[i]; list[i] = list[position - 1]; list[position - 1] = t; var newList = list.Take(position - 1).Reverse().ToList(); newList.AddRange(list.Skip(position - 1)); list = newList; } } }
public IList<Book> ApplyDiscounts(IList<Book> books) { var discounts = _locator.GetDiscountsFor(books) .OrderBy(x => x.Percentage); var bestDiscountedBooks = books; for(int i = 1; i <= discounts.Count(); i++) { var testDiscountBooks = books.Clone(); foreach(var discount in discounts.Take(i).OrderByDescending(x => x.Percentage)) { while(discount.IsSatisfiedBy(testDiscountBooks)) discount.Apply(testDiscountBooks); } if(testDiscountBooks.Sum(x => x.Price) < bestDiscountedBooks.Sum(x => x.Price)) bestDiscountedBooks = testDiscountBooks; } return bestDiscountedBooks; }
public Hand(IList<ICard> cards) { this.Cards = cards.Clone<ICard>(); }
public void Test_Performance() { Stopwatch sw = new Stopwatch(); IDictionary <string, Person> personDict = new Dictionary <string, Person>(); for (int i = 0; i <= 10000; i++) { Person p = new Person(i, "Horst" + i); personDict.Add(i + p.Name, p); } personDict.Clone(); sw.Start(); personDict.Clone(); sw.Stop(); Console.WriteLine("personDict: " + sw.ElapsedMilliseconds); IList <KeyValuePair <string, Person> > personListKeyValue = personDict.ToList(); personListKeyValue.Clone(); sw.Restart(); personListKeyValue.Clone(); sw.Stop(); Console.WriteLine("personListKeyValue: " + sw.ElapsedMilliseconds); IList <Person> personList = personDict.Values.ToList(); personList.Clone(); sw.Restart(); personList.Clone(); sw.Stop(); Console.WriteLine("personList: " + sw.ElapsedMilliseconds); IList <Tuple <string, Person> > personTupleList = personDict.Select(p => Tuple.Create(p.Key, p.Value)).ToList(); personTupleList.Clone(); sw.Restart(); personTupleList.Clone(); sw.Stop(); Console.WriteLine("personTupleList: " + sw.ElapsedMilliseconds); ICollection <Tuple <string, Person> > personTupleCollection = personDict.Select(p => Tuple.Create(p.Key, p.Value)).ToList(); personTupleCollection.Clone(); sw.Restart(); personTupleCollection.Clone(); sw.Stop(); Console.WriteLine("personTupleCollection: " + sw.ElapsedMilliseconds); CloneableDictionary <string, Person> cDict = new CloneableDictionary <string, Person>(personDict); int count = cDict.Count; Assert.Equal(10001, count); cDict.Clone(); sw.Restart(); cDict.Clone(); sw.Stop(); Console.WriteLine("CloneableDictionary: " + sw.ElapsedMilliseconds); }
public void SetNewData(IList <T> data) { NewData = (T)data.Clone(); }
public Food(IList <Ingredient> ingredients) { this.ingredients = ingredients.Clone(); }
public void SetOldData(IList <T> data) { OldData = (T)data.Clone(); }
public decimal InsertDateRange(CalculationRangeGroup calcDateRangeGroup, IList <CalculationDateRange> defaultDateRanges, IList <CalculationDateRange> dateRanges, IList <decimal> conceptTmpIds) { try { #region validation UIValidationExceptions exception = new UIValidationExceptions(); if (dateRanges == null || dateRanges.Count != 12) { exception.Add(new ValidationException(ExceptionResourceKeys.DateRangesCountNotEqualToTwelve, "تعداد ماههای ارسالی برای ذخیره دوره محاسبات باید برابر 12 باشد", ExceptionSrc)); } if (Utility.IsEmpty(conceptTmpIds)) { exception.Add(new ValidationException(ExceptionResourceKeys.DateRangesMustHaveConcept, "بمنظور بروزرسانی حتما باید یک یا چند مفهوم انتخاب شود", ExceptionSrc)); } if (exception.Count > 0) { throw exception; } #endregion LanguagesName sysLanguage = BLanguage.CurrentSystemLanguage; if (sysLanguage != null) { calcDateRangeGroup.Culture = sysLanguage; } calcDateRangeGroup.DateRangeList = new List <CalculationDateRange>(); foreach (decimal conceptID in conceptTmpIds) { IList <CalculationDateRange> rangeList = dateRanges.Clone <CalculationDateRange>(); for (int i = 0; i < rangeList.Count; i++) { rangeList[i].Concept = new SecondaryConcept() { ID = conceptID }; rangeList[i].RangeGroup = calcDateRangeGroup; SetDateRangeIndex(rangeList[i]); } ((List <CalculationDateRange>)calcDateRangeGroup.DateRangeList).AddRange(rangeList); } //درج دورهای پیشفرض IList <SecondaryConcept> orginConcepts = this.GetAllRanglyConcepts(); foreach (SecondaryConcept cnp in orginConcepts) { if (conceptTmpIds.Where(x => x == cnp.ID).Count() == 0) { IList <CalculationDateRange> rangeList = defaultDateRanges.Clone <CalculationDateRange>(); for (int i = 0; i < rangeList.Count; i++) { rangeList[i].Concept = new SecondaryConcept() { ID = cnp.ID }; rangeList[i].RangeGroup = calcDateRangeGroup; SetDateRangeIndex(rangeList[i]); } ((List <CalculationDateRange>)calcDateRangeGroup.DateRangeList).AddRange(rangeList); } } base.SaveChanges(calcDateRangeGroup, UIActionType.ADD); return(calcDateRangeGroup.ID); } catch (Exception ex) { LogException(ex, "BDateRange", "InsertDateRange"); throw ex; } }
public Bitmap FrequencyPermission(Bitmap bmp, int MaxValue, Color flag) { IList <int>[] m_channelHistogramsTmp = new IList <int> [3]; InitializeChannelHistograms(m_channelHistogramsTmp); //inicijalizovati tmp, ne klonirati vrednosti Bitmap cyantmp = (Bitmap)cyan.Clone(); Bitmap magentatmp = (Bitmap)magenta.Clone(); Bitmap yellowtmp = (Bitmap)yellow.Clone(); Bitmap bmptmp = (Bitmap)bmp.Clone(); BitmapData bmData = bmptmp.LockBits(new Rectangle(0, 0, bmptmp.Width, bmptmp.Height), ImageLockMode.ReadWrite, bmptmp.PixelFormat); BitmapData cyanData = cyantmp.LockBits(new Rectangle(0, 0, cyantmp.Width, cyantmp.Height), ImageLockMode.ReadWrite, cyantmp.PixelFormat); BitmapData magentaData = magentatmp.LockBits(new Rectangle(0, 0, magentatmp.Width, magentatmp.Height), ImageLockMode.ReadWrite, magentatmp.PixelFormat); BitmapData yellowData = yellowtmp.LockBits(new Rectangle(0, 0, yellowtmp.Width, yellowtmp.Height), ImageLockMode.ReadWrite, yellowtmp.PixelFormat); int stride = bmData.Stride; int stridecyan = cyanData.Stride; int stridemagenta = magentaData.Stride; int strideyellow = yellowData.Stride; System.IntPtr Scan0 = bmData.Scan0; System.IntPtr Scan01 = cyanData.Scan0; System.IntPtr Scan02 = magentaData.Scan0; System.IntPtr Scan03 = yellowData.Scan0; unsafe { byte *p = (byte *)(void *)Scan0; byte *c = (byte *)(void *)Scan01; byte *m = (byte *)(void *)Scan02; byte *yell = (byte *)(void *)Scan03; int nOffset = stride - bmptmp.Width * 3; int cOffset = stridecyan - cyantmp.Width * 3; int mOffset = stridemagenta - magentatmp.Width * 3; int yellOffset = strideyellow - yellowtmp.Width * 3; int nWidth = bmptmp.Width * 3; for (int y = 0; y < bmptmp.Height; ++y) { for (int x = 0; x < bmptmp.Width; ++x) { byte Blue = p[0]; if (flag == Color.Blue) //PLAVA { if (m_channelHistogramsTmp[2][Blue] >= MaxValue) { int counter = 1; while (m_channelHistogramsTmp[2][(Blue + counter) % 256] >= MaxValue) { counter++; if (counter >= 255) { return(bmp); } } p[0] = Convert.ToByte((Blue + counter) % 256); m_channelHistogramsTmp[2][(Blue + counter) % 256]++; } else { m_channelHistogramsTmp[2][Blue]++; } } c[0] = (byte)0; m[0] = p[0]; yell[0] = p[0]; ++p; ++c; ++m; ++yell; byte Green = p[0]; if (flag == Color.Green) //ZELENA { if (m_channelHistogramsTmp[1][Green] >= MaxValue) { int counter = 1; while (m_channelHistogramsTmp[1][(Green + counter) % 256] >= MaxValue) { counter++; if (counter >= 255) { return(bmp); } } p[0] = Convert.ToByte((Green + counter) % 256); m_channelHistogramsTmp[1][(Green + counter) % 256]++; } else { m_channelHistogramsTmp[1][Green]++; } } c[0] = p[0]; m[0] = (byte)0; yell[0] = p[0]; ++p; ++c; ++m; ++yell; byte Red = p[0]; if (flag == Color.Red) ///CRVENA { if (m_channelHistogramsTmp[0][Red] >= MaxValue) { int counter = 1; while (m_channelHistogramsTmp[0][(Red + counter) % 256] >= MaxValue) { counter++; if (counter >= 255) { return(bmp); } } p[0] = Convert.ToByte((Red + counter) % 256); m_channelHistogramsTmp[0][(Red + counter) % 256]++; } else { m_channelHistogramsTmp[0][Red]++; } m_channelHistogramsTmp[1][Convert.ToByte(Green)]++; m_channelHistogramsTmp[2][Convert.ToByte(Blue)]++; } c[0] = p[0]; m[0] = p[0]; yell[0] = (byte)0; ++p; ++c; ++m; ++yell; if (flag == Color.Green) { m_channelHistogramsTmp[0][Convert.ToByte(Red)]++; m_channelHistogramsTmp[2][Convert.ToByte(Blue)]++; } if (flag == Color.Blue) { m_channelHistogramsTmp[1][Convert.ToByte(Green)]++; m_channelHistogramsTmp[0][Convert.ToByte(Red)]++; } } p += nOffset; c += cOffset; m += mOffset; yell += yellOffset; } } m_channelHistograms = (IList <int>[])m_channelHistogramsTmp.Clone(); bmptmp.UnlockBits(bmData); if (!bmptmp.Equals(bmp)) { bmp = (Bitmap)bmptmp.Clone(); } cyantmp.UnlockBits(cyanData); cyan = (Bitmap)cyantmp.Clone(); magentatmp.UnlockBits(magentaData); magenta = (Bitmap)magentatmp.Clone(); yellowtmp.UnlockBits(yellowData); yellow = (Bitmap)yellowtmp.Clone(); return(bmptmp); }