public async Task<IEnumerable<ParkingLot>> CreateList(IEnumerable<ParkingLot> items)
        {
            var mainVm = ServiceLocator.Current.GetInstance<MainViewModel>();
            var filter = mainVm.ParkingLotFilterMode;
            var orderAsc = mainVm.ParkingLotFilterAscending;
            var alphabeticalSortingFunc = new Func<ParkingLot, string>(x => x.Name);
            switch (filter)
            {
                case ParkingLotFilterMode.Alphabetically:
                    return orderAsc ? items.OrderBy(alphabeticalSortingFunc) : items.OrderByDescending(alphabeticalSortingFunc);
                case ParkingLotFilterMode.Availability:
                    var availabilitySortingFunc = new Func<ParkingLot, double>(x =>
                    {
                        if (x.TotalLots == 0)
                        {
                            return 2; //they're always last of the list
                        }
                        return 1 - ((double) x.FreeLots / (double)x.TotalLots); //something between 0 and 1
                    });
                    return orderAsc ? items.OrderBy(availabilitySortingFunc).ThenBy(alphabeticalSortingFunc) : items.OrderByDescending(availabilitySortingFunc).ThenBy(alphabeticalSortingFunc);
                case ParkingLotFilterMode.Distance:
                    var userPos = await ServiceLocator.Current.GetInstance<GeolocationService>().GetUserLocation();
                    if (userPos == null)
                    {
                        mainVm.ParkingLotFilterMode = ParkingLotFilterMode.Alphabetically;
                        return await CreateList(items);
                    }

                    var distanceSortingFunc = new Func<ParkingLot, double>(x => x?.Coordinates?.Point == null ? double.MaxValue : userPos.Coordinate.Point.GetDistanceTo(x.Coordinates.Point));
                    return orderAsc ? items.OrderBy(distanceSortingFunc).ThenBy(alphabeticalSortingFunc) : items.OrderByDescending(distanceSortingFunc).ThenBy(alphabeticalSortingFunc);
                default:
                    return orderAsc ? items.OrderBy(alphabeticalSortingFunc) : items.OrderByDescending(alphabeticalSortingFunc);
            }
        }
Example #2
0
		private Player GetClosestBy(IEnumerable<Player> queue)
		{
			var sorted = queue.OrderBy(q => GetDistanceToGoalSquared(q.Position)).ToList();
			return queue
				.OrderBy(q => GetDistanceToGoalSquared(q.Position))
				.FirstOrDefault();
		}
 //Check the Sort Order to sort with corresponding column
 public void CheckSortOrder(string sortOrder, ref IEnumerable<Comment> comment)
 {
     switch (sortOrder)
     {
         case "Date_desc":
             comment = comment.OrderByDescending(u => u.PostedDate);
             break;
         case "PatientName":
             comment = comment.OrderBy(u => u.Patient.FullName);
             break;
         case "PatientName_desc":
             comment = comment.OrderByDescending(u => u.Patient.FullName);
             break;
         case "DoctorName":
             comment = comment.OrderBy(u => u.Doctor.FullName);
             break;
         case "DoctorName_desc":
             comment = comment.OrderByDescending(u => u.Doctor.FullName);
             break;
         case "Content":
             comment = comment.OrderBy(u => u.Content);
             break;
         case "Content_desc":
             comment = comment.OrderByDescending(u => u.Content);
             break;
         default:
             comment = comment.OrderBy(u => u.PostedDate);
             break;
     }
 }
		private IEnumerable<SourceModel> FilterModel(IEnumerable<SourceModel> model)
        {
            var ret = model;
            var order = _content.Filter.OrderBy;
            if (order == SourceFilterModel.Order.Alphabetical)
                ret = model.OrderBy(x => x.Name);
            else if (order == SourceFilterModel.Order.FoldersThenFiles)
                ret = model.OrderBy(x => x.Type).ThenBy(x => x.Name);
            return _content.Filter.Ascending ? ret : ret.Reverse();
        }
 public static IEnumerable<Country> OrderAscending(IEnumerable<Country> countries, Culture culture)
 {
     switch (culture)
     {
         case Culture.Ru:
             return countries.OrderBy(x => x.Translation.Ru);
         default:
             return countries.OrderBy(x => x.Translation.En);
     }
 }
        public IPagedList<Facility> getList(string sortOrder, string currentFilter, int? page, IEnumerable<Facility> data)
        {
            ViewBag.CurrentSort = sortOrder;
            ViewBag.Name = String.IsNullOrEmpty(sortOrder) ? "Name_desc" : "";
            ViewBag.IsFree = sortOrder == "IsFree" ? "IsFree_desc" : "IsFree";
            ViewBag.Enabled = sortOrder == "Enabled" ? "Enabled_desc" : "Enabled";
            ViewBag.SO_RateTypeId = sortOrder == "RateTypeId" ? "RateTypeId_desc" : "RateTypeId";
            ViewBag.Rate = sortOrder == "Rate" ? "Rate_desc" : "Rate";
            ViewBag.IsGST = sortOrder == "IsGST" ? "IsGST_desc" : "IsGST";
            switch (sortOrder)
            {
                case "Name_desc":
                    data = data.OrderByDescending(s => s.Name );
                    break;
                case "IsFree":
                    data = data.OrderBy(s => s.IsFree);
                    break;
                case "IsFree_desc":
                    data = data.OrderByDescending(s => s.IsFree);
                    break;
                case "Enabled":
                    data = data.OrderBy(s => s.Enabled);
                    break;
                case "Enabled_desc":
                    data = data.OrderByDescending(s => s.Enabled);
                    break;
                case "RateTypeId":
                    data = data.OrderBy(s => s.RateTypeId);
                    break;
                case "RateTypeId_desc":
                    data = data.OrderByDescending(s => s.RateTypeId);
                    break;
                case "Rate":
                    data = data.OrderBy(s => s.Rate);
                    break;
                case "Rate_desc":
                    data = data.OrderByDescending(s => s.Rate);
                    break;
                case "IsGST":
                    data = data.OrderBy(s => s.IsGST);
                    break;
                case "IsGST_desc":
                    data = data.OrderByDescending(s => s.IsGST);
                    break;
                case "":
                default:
                    data = data.OrderBy(s => s.Name);
                    break;
            }

            int pageSize = Configurations.PageSize(); 
            int pageNumber = (page ?? 1);
            return data.ToPagedList(pageNumber, pageSize);
        }
Example #7
0
 private static string[] Order(IEnumerable<string> fileSystemEntries)
 {
     try
     {
         // take in account that "2-someMigration" should go before "11-someOtherMigration"
         return fileSystemEntries.OrderBy(x => MigrationManager.GetMigrationId(Path.GetFileNameWithoutExtension(x))).ToArray();
     }
     catch (FormatException)
     {
         return fileSystemEntries.OrderBy(x => x).ToArray();
     }
 }
Example #8
0
        public static double Median(IEnumerable<double> myNumbers)
        {
            if (myNumbers.Count() == 0)
                throw new InvalidOperationException("Invalid count of numbers... must be greater that zero!");

            if (myNumbers.Count() % 2 == 0)
            {
                return myNumbers.OrderBy(_ => _).Skip(myNumbers.Count() / 2 - 1).Take(2).Sum() / 2;
            }
            else
            {
                return myNumbers.OrderBy(_ => _).ElementAt((int)Math.Floor((decimal)(myNumbers.Count() / 2)));
            }
        }
Example #9
0
        private Queue<Message> SetMessageOrder(IEnumerable<Message> unorderedMessages)
        {
            var messages = new Queue<Message>(
                unorderedMessages.OrderBy(x => x.MessengerOrderId));

            return messages;
        }
Example #10
0
        public void LoadWidgets(IEnumerable<Widget> widgetModels, Control placeholder, TemplateControl page)
        {
            if (placeholder == null)
            {
                return;
            }

            if (page == null)
            {
                return;
            }

            if (widgetModels == null)
            {
                return;
            }

            var groups = widgetModels.OrderBy(x => x.RowNumber).ThenBy(x => x.ColumnNumber).GroupBy(x => new {x.RowNumber});

            foreach (var group in groups)
            {
                foreach (Widget item in group)
                {
                    using (MixERPWidgetBase widget = page.LoadControl(item.WidgetSource) as MixERPWidgetBase)
                    {
                        if (widget != null)
                        {
                            placeholder.Controls.Add(widget);
                            widget.OnControlLoad(widget, new EventArgs());
                        }
                    }
                }
            }
        }
Example #11
0
        internal RepoConfig(
            IEnumerable<NuGetPackage> fixedPackages, 
            IEnumerable<string> toolsetPackages, 
            IEnumerable<Regex> nuspecExcludes,
            IEnumerable<Regex> projectJsonExcludes,
            GenerateData? msbuildGenerateData)
        {
            Debug.Assert(toolsetPackages.Distinct().Count() == toolsetPackages.Count());
            MSBuildGenerateData = msbuildGenerateData;
            FixedPackages = fixedPackages.OrderBy(x => x.Name).ToImmutableArray();
            NuSpecExcludes = nuspecExcludes.ToImmutableArray();
            ProjectJsonExcludes = projectJsonExcludes.ToImmutableArray();
            ToolsetPackages = toolsetPackages.OrderBy(x => x).ToImmutableArray();

            var map = new Dictionary<string, List<string>>();
            foreach (var nugetRef in fixedPackages)
            {
                List<string> list;
                if (!map.TryGetValue(nugetRef.Name, out list))
                {
                    list = new List<string>(capacity: 1);
                    map[nugetRef.Name] = list;
                }

                list.Add(nugetRef.Version);
            }
        }
		private static string GetContent(IEnumerable<Notification> notifications)
		{
			return notifications
				.OrderBy(x => x.Date)
				.Aggregate(new StringBuilder(), (s, notification) => s.AppendLine(notification.Content).AppendLine().AppendLine("----------").AppendLine())
				.ToString();
		}
Example #13
0
        public IEnumerable<PromotionMatch> MatchApplicablePromotions(PriceCalculationContext context, IEnumerable<Promotion> candidatePromotions)
        {
            var matches = new List<PromotionMatch>();

            // Lower priority promotions check first
            candidatePromotions = candidatePromotions.OrderBy(x => x.Priority).ThenBy(x => x.Id);

            foreach (var promotion in candidatePromotions)
            {
                var match = TryMatchPromotion(promotion, context);
                if (match != null)
                {
                    matches.Add(match);
                }
            }

            if (matches.Count > 0)
            {
                // Higher priority check first
                matches.Reverse();
                CheckOverlappingUsage(matches);
            }

            return matches;
        }
Example #14
0
 private void ParseMethods(IEnumerable<SDMethod> methods)
 {
     foreach (var method in methods.OrderBy(o => o.Name))
     {
         _classDiagram.MethodRows.Add(new ClassDiagramRow(method.Identifier, "Method", method.Accessibility, method.Name));
     }
 }
Example #15
0
        public override string Visit(IEnumerable<Item> items, string current)
        {
            if(current.IndexOf(TOKEN) < 0)
                return current;

            return current.Replace(TOKEN, runFilter<ProphecyFilter>(items.OrderBy(i => i.H)));
        }
Example #16
0
 public static MarketPrices ReadData(IEnumerable<string> symbols,
                                             string dataItem, TimeSeries timeSeries)
 {
     List<string> symbolsList = symbols.OrderBy(x => x).ToList();
     MarketPrices allData2 = For(symbolsList, dataItem, timeSeries);
     return allData2;
 }
Example #17
0
 private void ParseFields(IEnumerable<SDField> fields)
 {
     foreach (var field in fields.OrderBy(o => o.Name))
     {
         _classDiagram.FieldRows.Add(new ClassDiagramRow(field.Identifier, "Field", field.Accessibility, field.Name));
     }
 }
        public PackageDependencyProcessor(IEnumerable<IPackageInfo> packages)
        {
            _packages = packages;

            _graph = new DependencyGraph<IPackageInfo>(pak => pak.Name, pak => pak.GetDependencies().Select(x => x.Name));
            _packages.OrderBy(p => p.Name).Each(p => _graph.RegisterItem(p));
        }
Example #19
0
 private void ParseEvents(IEnumerable<SDEvent> events)
 {
     foreach (var ev in events.OrderBy(o => o.Name))
     {
         _classDiagram.EventRows.Add(new ClassDiagramRow(ev.Identifier, "Event", ev.Accessibility, ev.Name));
     }
 }
        /// <summary>
        /// Calculates the truncated mean of the specified collection of numbers
        /// regarding the specified percentage of elements to be discarded.
        /// </summary>
        /// <param name="numbers">The numbers whose truncated mean is to be calculated.</param>
        /// <param name="percentageToDiscard">The percentage of elements that
        /// are to be discarded at both sides of the collection in each case.</param>
        /// <returns>The truncated mean of the specified collection of numbers.</returns>
        /// <exception cref="System.InvalidOperationException">
        /// The specified collection must not be empty.
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// The specified collection must not be null.
        /// </exception>
        public static double TruncatedMean(IEnumerable<double> numbers,
            double percentageToDiscard)
        {
            if (numbers == null)
            {
                throw ArgumentNullException;
            }

            if (!numbers.Any())
            {
                throw EmptyNumbersCollectionException;
            }

            // The percentage to discard needs to be greater than 0 and smaller than 50% as
            // it makes no sense to both discard nothing and discard all (50% on both sides).
            if (percentageToDiscard <= 0 ||
                percentageToDiscard >= 0.5)
            {
                throw new ArgumentException(
                    "percentageToDiscard must be greater than 0 and smaller than 0.5!");
            }

            var orderedNumbers = numbers.OrderBy(n => n);

            IEnumerable<double> truncatedNumbers =
                TruncationHelper<double>.Truncate(orderedNumbers, percentageToDiscard);

            double truncatedMean = truncatedNumbers.ArithmeticMean();

            return truncatedMean;
        }
Example #21
0
        /// <summary>
        /// Calculates the median of the given numbers.
        /// </summary>
        /// <param name="numbers">The numbers whose median is to be calculated.</param>
        /// <returns>The median of the given numbers.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// The specified collection must not be null.
        /// </exception>
        /// <exception cref="System.InvalidOperationException">
        /// The arguments must not be empty.
        /// </exception>
        public static double Median(IEnumerable<double> numbers)
        {
            if (numbers == null)
            {
                throw ArgumentNullException;
            }

            if (!numbers.Any())
            {
                throw EmptyNumbersCollectionException;
            }

            List<double> sortedNumbers = numbers.OrderBy(number => number).ToList();

            double median = 0;

            if (sortedNumbers.Count % 2 == 0)
            {
                double lowerMedian = sortedNumbers[sortedNumbers.Count / 2 - 1];
                double upperMedian = sortedNumbers[sortedNumbers.Count / 2];

                median = ArithmeticMeanCalculator.ArithmeticMean(lowerMedian, upperMedian);
            }
            else
            {
                median = sortedNumbers[sortedNumbers.Count / 2];
            }

            return median;
        }
Example #22
0
        private static IEnumerable<TimeSpan> GetDelta(IEnumerable<DateTime> target)
        {
            var orderTarget = target.OrderBy(x => x.ToUniversalTime());

            var deltas = orderTarget.Zip(orderTarget.Skip(1), (current, next) => next - current);
            return deltas;
        }
Example #23
0
        public static CUFsListViewModel BuildPage(int pagenr, int itemsnr, String order,
            IEnumerable<CufRepoModel> repository, String title, String method, Boolean hasVersion)
        {
            int amountPages = ((repository.Count() + itemsnr - 1) / itemsnr);
            CUFsListModel clm = new CUFsListModel(title);

            repository = (order == "Asc") ? repository.OrderBy(cuf => cuf.Name) : repository.OrderByDescending(cuf => cuf.Name);

            foreach (var cuf in repository.Skip(pagenr * itemsnr).Take(itemsnr))
            {
                if (hasVersion)
                    clm.AddURIParams(cuf.Name + " [ V: " + cuf.Version + " ]", method, cuf.Acr, cuf.Version); //proposal-version
                else
                    clm.AddURIParams(cuf.Name, method, cuf.Acr);

            }

            CUFsListViewModel clvm = new CUFsListViewModel();
            clvm.CUFList = clm.GetCUFsListModel();
            clvm.PageNumber = pagenr;
            clvm.ItemsNumber = itemsnr;
            clvm.Order = order;
            clvm.AmountPage = amountPages;
            clvm.LastPage = false;
            clvm.ItemsPerPage = itemsPerPage;
            clvm.OrderPage = orderOptions;

            clvm.Method = hasVersion ? "PageVersion" : "Page";

            if (clvm.CUFList.Count() < itemsnr ||
                repository.Skip((pagenr + 1) * itemsnr).Take(itemsnr).Count() == 0)
                clvm.LastPage = true;

            return clvm;
        }
Example #24
0
        public static bool Validate(IEnumerable<AlarmDisplayRange> alarmDisplayOptions)
        {//This should be refactored to make use of System.ComponentModel.DataAnnotations
            int lastUpperLimit = -1;

            foreach (var x in alarmDisplayOptions.OrderBy(x=>x.LowerLimit))
            {
                //Validate Limits
                if(x.LowerLimit != lastUpperLimit+1)//Validate LowerLimit
                {
                    return false;
                }
                if(x.UpperLimit< x.LowerLimit)
                {
                    return false;
                }
                lastUpperLimit = x.UpperLimit;
                //Validate color (This one is most important because it could be an arbitrary string)
                if(x.Color == null)
                {
                    return false;
                }
                if (x.Color.Length > 0 && !HexColorRegex.IsMatch(x.Color))//if a string is present by not a color
                {
                    return false;
                }
            }
            return true;
        }
        internal EffectParameterUpdaterDefinition(IEnumerable<ParameterKey> keys, IEnumerable<ParameterDependency> dependencies)
        {
            SortedKeys = keys.OrderBy(x => x.HashCode).ToArray();
            SortedKeyHashes = SortedKeys.Select(x => x.HashCode).ToArray();

            // Sort dependencies
            dependencies = BuildDependencies(dependencies).ToArray();

            // Build dependencies (with indices instead of keys)
            var dependenciesIndex = new List<ParameterDependencyIndex>();
            foreach (var dependency in dependencies)
            {
                var destinationIndex = Array.IndexOf(SortedKeys, dependency.Destination);
                if (destinationIndex == -1)
                    throw new InvalidOperationException();
                var sourceIndices = dependency.Sources.Select(x => Array.IndexOf(SortedKeys, x)).ToArray();
                if (sourceIndices.Any(x => x == -1))
                    throw new InvalidOperationException();
                dependenciesIndex.Add(new ParameterDependencyIndex
                {
                    Destination = destinationIndex,
                    Sources = sourceIndices,
                    Dynamic = dependency.Dynamic,
                    //Parameters = new ParameterCollection.InternalValueReference[dependency.Sources.Length],
                });
            }

            this.Dependencies = dependenciesIndex.ToArray();

            ThreadLocalDynamicValues = new ParameterCollection.InternalValue[GraphicsDevice.ThreadCount][];
            for (int i = 0; i < ThreadLocalDynamicValues.Length; ++i)
            {
                ThreadLocalDynamicValues[i] = Dependencies.Select(x => ParameterCollection.CreateInternalValue(SortedKeys[x.Destination])).ToArray();
            }
        }
        public IEnumerable<IStory> Solve(int capacity, IEnumerable<IStory> candidates)
        {
            if (capacity < 0)
                throw new ArgumentException("Argument must be greater than zero", "capacity");

            if (candidates == null)
                throw new ArgumentNullException("candidates");

            var candidateList = new LinkedList<IStory>(candidates.OrderBy(x => x.Priority).ThenByDescending(x => x.Points));

            int capacityLeft = capacity;
            bool candidateFound = true;
            List<IStory> solution = new List<IStory>();

            while (capacityLeft > 0 && candidateFound)
            {
                candidateFound = false;

                foreach (var candidate in candidateList)
                {
                    if (capacityLeft >= candidate.Points)
                    {
                        solution.Add(candidate);
                        capacityLeft -= candidate.Points;
                        candidateList.Remove(candidate);
                        candidateFound = true;
                        break;
                    }
                }
            }

            return solution;
        }
Example #27
0
        public void LoadWidgets(IEnumerable<DefaultWidgetSetupView> widgetModels, Control placeholder, TemplateControl page)
        {
            if (placeholder == null)
            {
                return;
            }

            if (page == null)
            {
                return;
            }

            if (widgetModels == null)
            {
                return;
            }

            foreach (DefaultWidgetSetupView item in widgetModels.OrderBy(x => x.WidgetOrder))
            {
                using (MixERPWidget widget = page.LoadControl(item.WidgetSource) as MixERPWidget)
                {
                    if (widget != null)
                    {
                        placeholder.Controls.Add(widget);
                        widget.OnControlLoad(widget, new EventArgs());
                    }
                }
            }
        }
 public Assembly(string name, IEnumerable<Concern> concerns) : base(concerns.Cast<SpecificationContainer>())
 {
   _name = name;
   _concerns = concerns.OrderBy(x => x.Name).ToList();
   _totalConerns = concerns.Count();
   _totalContexts = concerns.Sum(x => x.TotalContexts);
 }
Example #29
0
 /// <inheritdoc />
 public IEnumerable<Offer> GetTheBestAvailableOffersFromLenders(IEnumerable<Lender> lenders, decimal requestedLoadAmount)
 {
     //order the lenders by best rate
     lenders = lenders.OrderBy(x => x.Rate).ToList();
     //container to store offers
     var offers = new List<Offer>();
     //loop through the lenders
     foreach (var lender in lenders)
     {
         //get the total already offered.
         var totalOffered = offers.Sum(item => item.Amount);
         //if the total offered is less than the requested amount
         if (totalOffered < requestedLoadAmount)
         {
             //add a new offer which will be either the full amount the lender has available or
             //the amount that the system needs to make up the requested loan amount.
             offers.Add(new Offer(Math.Min(lender.Available, requestedLoadAmount - totalOffered),
                 lender.Rate));
         }
         //we have enough offers
         else
         {
             //end the loop
             break;
         }
     }
     //return the offers to the caller.
     return offers;
 }
Example #30
0
		/// <summary>
		/// Imports the specified set of authority tokens.
		/// </summary>
		/// <param name="tokenDefs"></param>
		/// <param name="addToGroups"></param>
		/// <param name="context"></param>
		/// <returns></returns>
		public IList<AuthorityToken> Import(IEnumerable<AuthorityTokenDefinition> tokenDefs,
			IList<string> addToGroups, IUpdateContext context)
		{
			// first load all the existing tokens into memory
			// there should not be that many tokens ( < 500), so this should not be a problem
			var broker = context.GetBroker<IAuthorityTokenBroker>();
			var existingTokens = broker.FindAll();

			// if there are groups to add to, load the groups
			var groups = addToGroups != null && addToGroups.Count > 0 ? LoadGroups(addToGroups, context) : new List<AuthorityGroup>();

			// order the input such that the renames are processed first
			// otherwise there may be a corner case where a newly imported token is immediately renamed
			tokenDefs = tokenDefs.OrderBy(t => t.FormerIdentities.Length > 0);

			foreach (var tokenDef in tokenDefs)
			{
				var token = ProcessToken(tokenDef, existingTokens, context);

				// add to groups
				CollectionUtils.ForEach(groups, g => g.AuthorityTokens.Add(token));
			}

			return existingTokens;
		}