Example #1
1
        public void SetMinMax(IList<Point> points)
        {
            if (_isMaxMinSet)
            {
                var minX = points.Min(point => point.X);
                MinX = minX < MinX ? minX : MinX;

                var maxX = points.Max(point => point.X);
                MaxX = maxX > MaxX ? maxX : MaxX;

                var minY = points.Min(point => point.Y);
                MinY = minY < MinY ? minY : MinY;

                var maxY = points.Max(point => point.Y);
                MaxY = maxY > MaxY ? maxY : MaxY;
            }
            else
            {
                MinX = points.Min(point => point.X);
                MaxX = points.Max(point => point.X);
                MinY = points.Min(point => point.Y);
                MaxY = points.Max(point => point.Y);
                _isMaxMinSet = true;
            }
            SetOriginPoint(GetDelta());
        }
Example #2
1
        /// <summary>
        /// Fill weight and url for each tag.
        /// </summary>
        /// <param name="tagCounts">The tags to fill.</param>
        private void fillTagCounts(IList<TagCount> tagCounts)
        {
            int maxCount = tagCounts.Max(t => t.Total);
            foreach (TagCount tagCount in tagCounts)
            {
                double count = (double)tagCount.Total;
                double percent = (count / maxCount) * 100;

                if (percent < 20)
                {
                    tagCount.Weight = 1;
                }
                else if (percent < 40)
                {
                    tagCount.Weight = 2;
                }
                else if (percent < 60)
                {
                    tagCount.Weight = 3;
                }
                else if (percent < 80)
                {
                    tagCount.Weight = 4;
                }
                else
                {
                    tagCount.Weight = 5;
                }

                tagCount.Url = UrlBuilder.GetTagUrl(tagCount.UrlSlug);
            }
        }
        public void Initialize()
        {
            _data = new List<StoredUser>
            {
                new StoredUser {Id = 1, Name = "William Parker", MetaData = "Researcher"},
                new StoredUser {Id = 2, Name = "Trudy Jones", MetaData = "Researcher"}
            };

            _mockSet = MockUtility.CreateAsyncMockDbSet(_data, u => u.Id);

            var mockContext = new Mock<IAutoSysContext>();
            mockContext.Setup(s => s.Users).Returns(_mockSet.Object);
            mockContext.Setup(s => s.Set<StoredUser>()).Returns(_mockSet.Object);
            mockContext.Setup(s => s.SaveChangesAsync()).Returns(Task.Run(() =>
            {
                // Increment user ids automatically based on existing ids in mock data 
                var max = _data.Max(u => u.Id);
                foreach (var user in _data.Where(u => u.Id == 0))
                {
                    user.Id = ++max;
                }
                return 1; // SaveChangesAsync returns number based on how many times it was called per default 
            }));

            _context = mockContext;
            _repository = new UserRepository(_context.Object);
        }
Example #4
1
 /// <summary>
 /// Converts a List of string arrays to a string where each element in each line is correctly padded.
 /// Make sure that each array contains the same amount of elements!
 /// - Example without:
 /// Title Name Street
 /// Mr. Roman Sesamstreet
 /// Mrs. Claudia Abbey Road
 /// - Example with:
 /// Title   Name      Street
 /// Mr.     Roman     Sesamstreet
 /// Mrs.    Claudia   Abbey Road
 /// <param name="lines">List lines, where each line is an array of elements for that line.</param>
 /// <param name="padding">Additional padding between each element (default = 1)</param>
 /// </summary>
 /// <see cref="http://stackoverflow.com/questions/4449021/how-can-i-align-text-in-columns-using-console-writeline"/> 
 public static string PadElementsInLines(IList<string[]> lines, int padding = 1)
 {
     // Calculate maximum numbers for each element accross all lines
     var numElements = lines[0].Length;
     var maxValues = new int[numElements];
     for (int i = 0; i < numElements; i++)
     {
         maxValues[i] = lines.Max(x => x[i].Length) + padding;
     }
     var sb = new StringBuilder();
     // Build the output
     bool isFirst = true;
     foreach (var line in lines)
     {
         if (!isFirst)
         {
             sb.AppendLine();
         }
         isFirst = false;
         for (int i = 0; i < line.Length; i++)
         {
             var value = line[i];
             // Append the value with padding of the maximum length of any value for this element
             sb.Append(value.PadRight(maxValues[i]));
         }
     }
     return sb.ToString();
 }
        private FeedResult FeedResult(IList<SyndicationItem> items)
        {
            var settings = Settings.GetSettings<FunnelWebSettings>();

            Debug.Assert(Request.GetOriginalUrl() != null, "Request.GetOriginalUrl() != null");

            var baseUri = Request.GetOriginalUrl();
            var feedUrl = new Uri(baseUri, Url.Action("Recent", "Wiki"));
            return new FeedResult(
                new Atom10FeedFormatter(
                    new SyndicationFeed(settings.SiteTitle, settings.SearchDescription, feedUrl, items)
                    {
                        Id = baseUri.ToString(),
                        Links =
                        {
                            new SyndicationLink(baseUri)
                            {
                                RelationshipType = "self"
                            }
                        },
                        LastUpdatedTime = items.Count() == 0 ? DateTime.Now : items.First().LastUpdatedTime
                    }), items.Max(i => i.LastUpdatedTime.LocalDateTime))
            {
                ContentType = "application/atom+xml"
            };
        }
        public void Initialize()
        {
            _data = new List<StoredProtocol>
            {
                new StoredProtocol {Id = 1, StudyName = "StudyName" }, // TODO add pseudo data 
                new StoredProtocol {Id = 2,  StudyName = "StudyName" }
            };

            _mockSet = MockUtility.CreateAsyncMockDbSet(_data, u => u.Id);

            var mockContext = new Mock<IAutoSysContext>();
            mockContext.Setup(s => s.Protocols).Returns(_mockSet.Object);
            mockContext.Setup(s => s.Set<StoredProtocol>()).Returns(_mockSet.Object);
            mockContext.Setup(s => s.SaveChangesAsync()).Returns(Task.Run(() =>
            {
                // Increment protocol ids automatically based on existing ids in mock data 
                var max = _data.Max(u => u.Id);
                foreach (var protocol in _data.Where(u => u.Id == 0))
                {
                    protocol.Id = ++max;
                }
                return 1; // SaveChangesAsync returns number based on how many times it was called per default 
            }));

            _context = mockContext;
            _repository = new ProtocolRepository(_context.Object);
        }
        /// <summary>
        /// I feel like this way is a little bit more optimized since it saves space
        /// there is still the possibility of empty space beetwen min,max 
        /// but atleast it gets rid of the space from 0 to min
        /// 
        /// This will also work with negative numbers.
        /// </summary>
        public static int[] Sort(IList<int> data, int min, int max)
        {
            Contract.Ensures(data != null, "data cannot be a null pointer");
            Contract.Ensures(min == data.Min(), "wrong min submitted");
            Contract.Ensures(max == data.Max(), "wrong max submitted");

            int[] count = new int[(max - min) + 1];
            int[] sorted = new int[data.Count];

            // Add the elements in reverse order big --> small
            // NOTE: Could do key - min instead for order small --> big
            foreach (int key in data)
            {
                count[max - key] += 1;
            }

            // Transfer the temp array to the sorted array from small --> big
            int sortedIndex = data.Count - 1;
            for (int i = 0; i < count.Length; i++)
            {
                // How often did we have this number in the input?
                int number = max - i;
                for (int j = 0; j < count[i]; j++)
                {
                    sorted[sortedIndex--] = number;
                }
            }

            return sorted;
        }
        public IEnumerable<MatchModel> GetMatchesForNextRound(IList<PlayerModel> players, IList<MatchModel> previousMatches)
        {
            var matchesForNextRound = new List<MatchModel>();

            int round = previousMatches.Count == 0 ? 1 : previousMatches.Max(p => p.Round) + 1;

            List<PlayerModel> playerModels = _playersHelper.GetPlayersWithCalculatedRating(players, previousMatches)
                                                    .OrderByDescending(p => p.Rate)
                                                    .ToList();

            while (playerModels.Count > 0)
            {
                PlayerModel player = playerModels.First();
                playerModels.Remove(player);

                MatchModel matchModel = _matchesHelper.GetMatchModelForNextRound(player, playerModels, previousMatches);
                matchModel.Round = round;
                matchModel.Player1PlaysWhite = _playersHelper.PlayerCanPlayWithDefinedColor(player, ChessColor.White, previousMatches);
                matchModel.MatchStartTime = DateTime.Now;
                matchModel.Winner = new PlayerModel { PlayerId = SpecialPlayerIds.WinnerIdForGameWithUndefinedResult };

                playerModels.Remove(matchModel.Player2);
                matchesForNextRound.Add(matchModel);
            }

            return matchesForNextRound;
        }
Example #9
1
        private static int ResolveSpecial(IList<int> pancakes)
        {
            IList<int> newpancakes = new List<int>();

            int maxvalue = pancakes.Max();

            if (maxvalue == 1)
                return 1;

            int split = maxvalue / 2;
            int steps = pancakes.Count(n => n == maxvalue);

            foreach (int value in pancakes)
                if (value == maxvalue)
                    newpancakes.Add(value - split);
                else
                    newpancakes.Add(value);

            for (int k = 0; k < steps; k++)
                newpancakes.Add(split);

            int ncount1 = Resolve(newpancakes);

            return steps + Resolve(newpancakes);
        }
Example #10
1
        public ProjectRepository(IList<Project> projects)
        {
            this.projects = projects;

            if (projects.Count > 0)
                this.maxid = projects.Max(p => p.Id);
        }
        /// <summary>
        /// The default implementation which creates a work array from 0 to max
        /// Only works with positive numbers
        /// </summary>
        public static int[] Sort(IList<int> data, int max)
        {
            Contract.Requires(data != null && Contract.ForAll(data, i => i >= 0));
            Contract.Requires(max >= 0 && max == data.Max());

            int[] count = new int[max + 1];
            int[] sorted = new int[data.Count];

            // Add the elements in order small --> big
            foreach (int key in data)
            {
                count[key] += 1;
            }

            // Transfer the temp array to the sorted array from small --> big
            int sortedIndex = 0;
            for (int number = 0; number < count.Length; number++)
            {
                // How often did we have this number in the input?
                for (int j = 0; j < count[number]; j++)
                {
                    sorted[sortedIndex++] = number;
                }
            }

            return sorted;
        }
Example #12
1
        public int CalculateDeceitfulWar(IList<double> first, IList<double> second)
        {
            if (first.Count == 0)
                return 0;

            double min1 = first.Min();
            double min2 = second.Min();
            bool win = false;

            double play1;
            double play2;

            if (min1 < min2)
            {
                play1 = min1;
                play2 = second.Max();
            }
            else
            {
                play1 = min1;
                play2 = min2;
                win = true;
            }

            var newfirst = first.Where(n => n != play1).ToList();
            var newsecond = second.Where(n => n != play2).ToList();

            return CalculateDeceitfulWar(newfirst, newsecond) + (win ? 1 : 0);
        }
Example #13
1
        /// <summary>
        /// Convert numbers to spark chart strings.
        /// </summary>
        /// <param name="data">List or Array of numbers</param>
        /// <returns>empty string if <paramref name="data"/>is <code>null</code> or empty.</returns>
        public static String Render(IList<double> data)
        {
            var ticks = TickProvider.Ticks;

            if (data == null || data.Count == 0)
                return string.Empty;

            char[] res = new char[data.Count()];

            double min = data.Min();
            double max = data.Max();
            double step = (max - min) / (ticks.Length - 1);
            if (step.Equals(0d)) step = 1;

            for (var i = 0; i < data.Count(); i++)
            {
                var val = data[i];
                double d = (val - min)/step;

                // if it's 10^-10 close to its rounded, round; floor otherwise
                int tick = (int) ((Math.Abs(Math.Round(d) - d) < 1e-10) ? Math.Round(d) : Math.Floor((val - min) / step));
                res[i] = ticks[tick];
            }
            return new string(res);
        }
Example #14
1
        /// <summary>
        /// Initializes a new instance of the <see cref="Hull"/> class.
        /// </summary>
        /// <param name="points">The points.</param>
        public Hull(IList<Vector2> points)
        {
            var numVertices = points.Count * 2;
            var numTris = numVertices - 2;
            var numIndicies = numTris * 3;

            this.vertices = new HullVertex[numVertices];
            this.indices = new int[numIndicies];
            this.scale = Vector2.One;

            for (var i = 0; i < points.Count; i++)
            {
                var p1 = points[i];
                var p2 = points[(i + 1) % points.Count];

                var normal = (p2 - p1).Clockwise();

                normal.Normalize();

                this.vertices[i * 2] = new HullVertex(p1, normal, new Color(0, 0, 0, 0.1f));
                this.vertices[(i * 2) + 1] = new HullVertex(p2, normal, new Color(0, 0, 0, 0.1f));
            }

            for (var i = 0; i < numTris; i++)
            {
                this.indices[i * 3] = 0;
                this.indices[(i * 3) + 1] = i + 1;
                this.indices[(i * 3) + 2] = i + 2;
            }

            this.RadiusSquared = points.Max(x => x.LengthSquared());
        }
Example #15
1
        /// <summary>
        /// Generates intervals based on type, numberOfClasses and values.
        /// </summary>
        /// <param name="values"></param>
        /// <param name="type"></param>
        /// <param name="numberOfClasses"></param>
        /// <returns></returns>
        public static IList<Interval> GetIntervalsForNumberOfClasses(IList<Single> values, QuantityThemeIntervalType type, int numberOfClasses)
        {
            int index = 0;
            var intervals = new List<Interval>();
            var lowValue = values.Min();
            var highValue = values.Max();
            if (type == QuantityThemeIntervalType.NaturalBreaks)
            {
                ArrayList.Adapter((IList)values).Sort(); // performance, works 20% faster than layerAttribute.AttributeValues.Sort();
            }

            for (int i = 0; i < numberOfClasses; i++)
            {
                float intervalMin;
                float intervalMax;

                if (type == QuantityThemeIntervalType.EqualIntervals)
                {

                    intervalMin = lowValue + i * ((highValue - lowValue) / numberOfClasses);
                    intervalMax = lowValue + (i + 1) * ((highValue - lowValue) / numberOfClasses);
                }
                else
                {
                    intervalMin = Convert.ToSingle(values[index]);
                    index = (int)Math.Ceiling((double)(i + 1) / numberOfClasses * (values.Count - 1));
                    intervalMax = Convert.ToSingle(values[index]);
                }

                var interval = new Interval(intervalMin, intervalMax);
                intervals.Add(interval);
            }

            return intervals;
        }
Example #16
1
        static void DisplayStats(IList<Response> responses)
        {
            if (!responses.Any())
            {
                return;
            }

            var average = responses.Average(x => (x.EndUtc - x.StartUtc).TotalMilliseconds);
            ClearLine();
            Console.WriteLine("Average time: {0} ms", Convert.ToInt32(average));

            var min = responses.Min(x => x.StartUtc);
            var max = responses.Max(x => x.EndUtc);
            var count = responses.Count;
            var timespan = Convert.ToInt32((max - min).TotalMilliseconds);
            timespan = timespan == 0 ? 0 : timespan / 1000;
            var rps = timespan == 0 ? 0 : count / timespan;

            ClearLine();
            Console.WriteLine("Performance: {0} rps ({1} reqs in {2})", Convert.ToInt32(rps), responses.Count, timespan);

            ClearLine();
            Console.WriteLine("Threads: {0}", responses.Select(x => x.TaskId).Distinct().Count());

            ClearLine();
            Console.WriteLine("Errors: {0}", responses.Count(x => !x.Success));
        }
Example #17
1
        private static int ResolveNormal(IList<int> pancakes)
        {
            int maxvalue = pancakes.Max();
            int minvalue = pancakes.Min();

            if (minvalue == maxvalue)
                return maxvalue;

            int secondmaxvalue = pancakes.Where(n => n != maxvalue).Max();

            IList<int> newpancakes = new List<int>();
            int steps = maxvalue - secondmaxvalue;

            foreach (int value in pancakes)
            {
                if (value == maxvalue)
                    newpancakes.Add(secondmaxvalue);
                else if (value > steps)
                    newpancakes.Add(value - steps);
            }

            if (newpancakes.Count == 0)
                return 1;

            return Resolve(newpancakes) + steps;
        }
        public override void Draw(
			IList<Point> points,
			double thickness,
			int miterLimit,
			ILogicalToScreenMapper logicalToScreenMapper)
        {
            var pointsCount = points.Count;
            var firstPoint = points[0];
            var lastPoint = points[pointsCount - 1];
            var highestValue = _useHighest ? points.Max(it => it.Y) : 0;
            var lowestValue = _useLowest ? points.Min(it => it.Y) : 0;
            double baselineValue;

            // Auf gleiche Höhe bringen
            if (_useBaseline)
                baselineValue = logicalToScreenMapper.MapY(_baselineValue);
            else if (_useHighest)
                baselineValue = highestValue;
            else if (_useLowest)
                baselineValue = lowestValue;
            else
            {
                baselineValue = firstPoint.Y > lastPoint.Y
                    ? lastPoint.Y
                    : firstPoint.Y;
            }

            using (var dc = RenderOpen())
            {
                for (var i = 1; i < points.Count; i++)
                {
                    var previousPoint = points[i - 1];
                    var currentPoint = points[i];
                    var previousY = previousPoint.Y;
                    // -1 weil: 1 Pixel nach links verschieben bewirkt, dass die Löcher zwischen den Rechtecken nicht mehr auftauchen
                    // nicht mehr nach 1 verschieben, weil der Fall bei Kriko (kleine Löcher in den Kurven) sowieso nicht vorkommt
                    // var previousX = previousPoint.X - 1;
                    var previousX = previousPoint.X;
                    // Rect kann mit negativen Höhen nicht umgehen, deshalb die komischen Expressions
                    var height = previousY > baselineValue ? previousY - baselineValue : baselineValue - previousY;
                    var y = previousY > baselineValue ? baselineValue : previousY;
                    var rectangle = new Rect(
                        previousX,
                        height == 0 ? y - 1 : y, // Linie um 1 nach oben verschieben, damit die Linien nicht optisch nach unten versetzt sind
                        currentPoint.X - previousX,
                        height == 0d ? 1 : height);
                    dc.DrawRectangle(
                        Brushes.White,
                        new Pen(
                            Brushes.White,
                            0)
                        // brauchen wir nicht mehr (siehe oben - height == 0): thickness == 1 ? 0.25 : thickness)
                        {
                            MiterLimit = miterLimit
                        },
                        rectangle);
                }
            }
        }
Example #19
1
 public IList<WordIntPair> GetFontSizes(IList<WordIntPair> wordsAndFreqs, InputOptions options)
 {
     int minCount = wordsAndFreqs.Min(t => t.Number);
     int maxCount = wordsAndFreqs.Max(t => t.Number);
     return wordsAndFreqs.Select(tuple => new WordIntPair(
         tuple.Word,
         CountFont(tuple.Number, options.MaxFont, options.MinFont, minCount, maxCount)))
         .ToList();
 }
Example #20
0
 private void AdjustSize(IList<Img> imgs)
 {
     var maxWidht = imgs.Max(x => x.Image.Width);
     var maxHeight = imgs.Max(x => x.Image.Height);
     foreach (var bitmap in imgs)
     {
         if (bitmap.Image.Width < maxHeight || bitmap.Image.Height < maxHeight)
         {
             var dw = maxWidht - bitmap.Image.Width;
             var dh = maxHeight - bitmap.Image.Height;
             var wo = GetOffsets(dw);
             var ho = GetOffsets(dh);
             bitmap.Resize(maxWidht, maxHeight, wo, ho);
         }
     }
 }
Example #21
0
        public IList<Department> RotatetDepartmentList(IList<Department> departments)
        {
            if (departments == null)
            {
                return new List<Department>();
            }

            if (departments.Count == 0)
            {
                return departments;
            }

            int lastSortOrder = departments.Max(d => d.SortOrder);

            Department department = FindDepartmentWithMinSortOrder(departments);

            if (department != null)
            {
                department.SortOrder = lastSortOrder + 1;
            }

            departments = (from d in departments orderby d.SortOrder select d).ToList();

            int sortOrder = 1;

            foreach (Department dep in departments)
            {
                dep.SortOrder = sortOrder;
                sortOrder++;
            }

            return departments;
        }
 public AggregationOperationResult Do(IList<double> input)
 {
     if (input == null)
         throw new ArgumentNullException("input");
     if (!input.Any())
         throw new InvalidOperationException("No elements to aggregate");
     return new AggregationOperationResult(AggregationType.Max, input.Max());
 }
 public AggregationOperationResult Do(IList<UniversalValue> input)
 {
     if (input == null)
         throw new ArgumentNullException("input");
     AggregationOperationResult result = new AggregationOperationResult();
     result.Add("max", input.Max());
     return result;
 }
Example #24
0
        public CarCalculatorSummary(IList<FuelEntryModel> fuelEntries)
        {
            HasData = fuelEntries != null && fuelEntries.Any();
            if (!HasData) return;

            MinAmountOf100Km = fuelEntries.Min(i => i.AmountOfFuelPer100Km);
            MaxAmountOf100Km = fuelEntries.Max(i => i.AmountOfFuelPer100Km);

            MinCost1Km = fuelEntries.Min(i => i.CostOf1Km);
            MaxCost1Km = fuelEntries.Max(i => i.CostOf1Km);

            SumDistance = fuelEntries.Sum(i => i.CurrentDistance);
            SumAmountOfFuel = fuelEntries.Sum(i => i.AmountOfFuel);
            SumTotalCost = fuelEntries.Sum(i => i.GasPrice * i.AmountOfFuel);

            var minDate = fuelEntries.Min(i => i.Date);
            var maxDate = fuelEntries.Max(i => i.Date);
            AverageFuel = (decimal)((maxDate - minDate).TotalDays/fuelEntries.Count);
        }
        public ContentExpectationWriter(IList<string> expectations, IList<string> actuals)
        {
            _expectations = expectations;
            _actuals = actuals;

            _leftLength = actuals.Max(x => x.Length);
            _startOfRightColumn = _leftLength + 10;

            _rightLength = _expectations.Max(x => x.Length);
        }
 private double GetMaxRightFromChildren(IList<ICanvasItem> items)
 {
     if (!items.Any())
     {
         return double.NaN;
     }
     var right = items.Max(item => item.Left + item.Width);
     var width = right;
     return width;
 }
Example #27
0
		///
		public IList<string> ToOriginalID(IList<int> internal_id_list)
		{
			MaxEntityID = Math.Max(MaxEntityID, internal_id_list.Max());

			var original_ids = new string[internal_id_list.Count];
			for (int i = 0; i < internal_id_list.Count; i++)
				original_ids[i] = internal_id_list[i].ToString();

			return original_ids;
		}
Example #28
0
		public double Score(IList<Tuple<double, double>> spectrumPeaks, IEnumerable<Tuple<double, double, double>> matchedFragments, double compoundTotalBondEnergy)
		{
			if (!spectrumPeaks.Any())
			{
				return 0;
			}

			var maxSpectrumIntensity = spectrumPeaks.Max(p => p.Item2);

			var matchedTotalWeightedIntensity = matchedFragments.Sum(f => WeightedIntensity(f.Item1, f.Item2, f.Item3, compoundTotalBondEnergy, maxSpectrumIntensity));
			var spectrumTotalWeightedIntensity = spectrumPeaks.Sum(t => WeightedIntensity(t.Item1, t.Item2, 0, compoundTotalBondEnergy, maxSpectrumIntensity));

			var score = spectrumTotalWeightedIntensity > 0 ? matchedTotalWeightedIntensity / spectrumTotalWeightedIntensity * 100 : 0;
			return score;
		}
        public static string GetDispatcherParameters(IList<MethodDeclaration> methodDeclarations, string argumentPrefix)
        {
            var argumentNumber = 0;

            if (methodDeclarations.Count == 0 || methodDeclarations.Max(x => x.Arguments.Count) == 0)
            {
                return string.Format("{0}{1}?: any", argumentPrefix, argumentNumber);
            }

            return methodDeclarations
                .First(x => x.Arguments.Count == methodDeclarations.Max(y => y.Arguments.Count))
                .Arguments
                .Select(x => string.Format("{0}{1}?: any", argumentPrefix, argumentNumber++))
                .Aggregate((x, y) => x + ", " + y);
        }
 public LineData(IList<double> x, IList<double> y)
 {
     m_x = x;
     m_y = y;
     Count = x.Count;
     if (x.Count > 0)
     {
         MaxValueX = x.Max();
         MinValueX = x.Min();
     }
     if (y.Count > 0)
     {
         MaxValueY = y.Max();
         MinValueY = y.Min();
     }
 }