Esempio n. 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());
        }
Esempio n. 2
1
        public SeasonWeek AddWeekToSeason(int seasonId, IList<RealWorldFixture> fixtures)
        {
            var season = LoadSeason(seasonId);

            var currentFinalWeek = season.Weeks.Any() ? season.Weeks.Max(w => w.WeekNumber) : 0;

            if (currentFinalWeek == season.NumberOfWeeks)
                throw new InvalidOperationException("Season has full complement of weeks already");

            var predsCutoffDate = fixtures.Min(f => f.KickOff).AddHours(-1);

            var addedWeek = new SeasonWeek
            {
                WeekNumber = currentFinalWeek + 1,
                RealWorldFixtures = fixtures,
                PredsCutOffDate = predsCutoffDate,
                Season = season,
            };

            foreach (var fixture in fixtures)
            {
                fixture.SeasonWeek = addedWeek;
            }

            season.Weeks.Add(addedWeek);
            _seasonRepository.Save(season);

            return addedWeek;
        }
Esempio n. 3
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;
        }
        public List<Point> ConvexHull(IList<Point> points)
        {
            if (points.Count < 3)
            {
                throw new ArgumentException("At least 3 points reqired", "points");
            }

            List<Point> hull = new List<Point>();

            // get leftmost point
            Point vPointOnHull = points.Where(p => p.X == points.Min(min => min.X)).First();

            Point vEndpoint;
            do
            {
                hull.Add(vPointOnHull);
                vEndpoint = points[0];

                for (int i = 1; i < points.Count; i++)
                {
                    if ((vPointOnHull.IsTheSame(vEndpoint)) || (Orientation(vPointOnHull, vEndpoint, points[i]) == -1))
                    {
                        vEndpoint = points[i];
                    }
                }

                vPointOnHull = vEndpoint;

            }
            while (!vEndpoint.IsTheSame(hull[0]));

            return hull;
        }
        /// <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;
        }
Esempio n. 6
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));
        }
Esempio n. 7
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);
        }
Esempio n. 8
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;
        }
Esempio n. 9
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);
        }
        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);
                }
            }
        }
 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.Min,input.Min());
 }
Esempio n. 12
1
        private static Department FindDepartmentWithMinSortOrder(IList<Department> departments)
        {
            int firstSortOrder = departments.Min(d => d.SortOrder);

            return (from d in departments
                    where d.SortOrder == firstSortOrder
                    select d).First();
        }
 public AggregationOperationResult Do(IList<UniversalValue> input)
 {
     if (input == null)
         throw new ArgumentNullException("input");
     AggregationOperationResult result = new AggregationOperationResult();
     result.Add("min", input.Min());
     return result;
 }
Esempio n. 14
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();
 }
Esempio n. 15
1
 private int GetTheta(int current, IList<int> sortedCardinalities)
 {
     var result = sortedCardinalities.Count(i => i >= current);
     if (current != sortedCardinalities.Min())
     {
         result = result + 1;
     }
     return result;
 }
        public RelatorioJogosDisponiveisModel(IList<Jogo> jogosDisponiveis)
        {
            this.Jogos = new List<JogoDisponivelModel>();

            if(jogosDisponiveis != null && jogosDisponiveis.Count > 0)
            {
                foreach (Jogo jogo in jogosDisponiveis)
                {
                    var jogoModel = new JogoDisponivelModel(jogo);
                    this.Jogos.Add(jogoModel);
                }

                this.QuantidadeTotalDeJogos = jogosDisponiveis.Count;
                this.ValorMedio = jogosDisponiveis.Average(j => j.Preco);
                decimal maiorPreco = jogosDisponiveis.Max(j => j.Preco);
                decimal menorPreco = jogosDisponiveis.Min(j => j.Preco);

                this.JogoMaisCaro = this.Jogos.First(j => j.Preco == maiorPreco);
                this.JogoMaisBarato = this.Jogos.First(j => j.Preco == menorPreco);
            }
        }
Esempio n. 17
0
        /// <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);
        }
Esempio n. 18
0
    public override IEnumerable <WeightedTop> CalculateRule(Top agent, Top previousTarget, IList <Top> others)
    {
        // FIXME: use spin here instead of float
        float minSpin = others.Min(t => (float)t.CurrentSpin);

        return(others.Select(t => new WeightedTop(t, t.CurrentSpin == minSpin ? 1 : 0)));
    }
Esempio n. 19
0
            public AND(SemanticContext a, SemanticContext b)
            {
                HashSet <SemanticContext> operands = new HashSet <SemanticContext>();

                if (a is SemanticContext.AND)
                {
                    operands.UnionWith(((AND)a).opnds);
                }
                else
                {
                    operands.Add(a);
                }
                if (b is SemanticContext.AND)
                {
                    operands.UnionWith(((AND)b).opnds);
                }
                else
                {
                    operands.Add(b);
                }
                IList <SemanticContext.PrecedencePredicate> precedencePredicates = FilterPrecedencePredicates(operands);

                if (precedencePredicates.Count > 0)
                {
                    // interested in the transition with the lowest precedence
                    SemanticContext.PrecedencePredicate reduced = precedencePredicates.Min();
                    operands.Add(reduced);
                }
                opnds = operands.ToArray();
            }
Esempio n. 20
0
        /// <summary>
        /// Sets the values for this segment. This method is not
        /// intended to be called explicitly outside the Chart but it can be overriden by
        /// any derived class.
        /// </summary>
        /// <param name="x1Values"></param>
        /// <param name="y1Values"></param>
        /// <param name="x2Values"></param>
        /// <param name="y2Values"></param>
        public override void SetData(IList <double> x1Values, IList <double> y1Values, IList <double> x2Values, IList <double> y2Values)
        {
            this.x1ChartVals = x1Values;
            this.y1ChartVals = y1Values;
            this.x2ChartVals = x2Values;
            this.y2ChartVals = y2Values;
            double X_MAX = x2Values.Max();
            double Y_MAX = y1Values.Max();
            double X_MIN = x1Values.Min();

            double _Min = y1ChartVals.Min();
            double Y_MIN;

            if (double.IsNaN(_Min))
            {
                var yVal = y1ChartVals.Where(e => !double.IsNaN(e));
                Y_MIN = (!yVal.Any()) ? 0 : yVal.Min();
            }
            else
            {
                Y_MIN = _Min;
            }
            double Y2_Min = y2ChartVals.Min();

            XRange = new DoubleRange(X_MIN, X_MAX);
            YRange = new DoubleRange((Y_MIN <Y2_Min && Y_MAX> Y2_Min) ? Y_MIN : Y2_Min, Y2_Min < Y_MAX ? Y_MAX : Y_MIN);
        }
Esempio n. 21
0
File: XPath.cs Progetto: yxddxs/Hawk
        /// <summary>
        ///     获取从头开始的最大公共子串
        /// </summary>
        /// <returns></returns>
        public static XPath GetMaxCompareXPath(IList <XPath> items)
        {
            int minlen = items.Min(d => d.Count);

            string c = null;
            int    i = 0;

            for (i = 0; i < minlen; i++)
            {
                for (int index = 0; index < items.Count; index++)
                {
                    XPath path = items[index];
                    if (index == 0)
                    {
                        c = path[i];
                    }
                    else
                    {
                        if (c != path[i])
                        {
                            goto OVER;
                        }
                    }
                }
            }
OVER:
            XPath first = items.First().SubXPath(i + 1);

            first.RemoveFinalNum();
            return(first);
        }
Esempio n. 22
0
        public void Min_ArrEmpty_Exc()
        {
            IList list = ConvertToListType(TestContext.DataRow["List Type"].ToString());

            list.Init(new int[] { });
            list.Min();
        }
Esempio n. 23
0
        private void DrawDebugInformation(GameTime time)
        {
            _fps.Add(1 / time.ElapsedGameTime.TotalSeconds);
            _gbfps.Add(GameBoy.Cpu.FramesPerSecond);

            var difference = time.TotalGameTime - _last;

            if (difference.TotalSeconds > 1)
            {
                _minGbFps     = _gbfps.Min();
                _averageGbFps = _gbfps.Average();
                _maxGbFps     = _gbfps.Max();

                _minFps     = _fps.Min();
                _averageFps = _fps.Average();
                _maxFps     = _fps.Max();

                _speedFactor = _averageGbFps / 60f;

                _last = time.TotalGameTime;
                _gbfps.Clear();
                _fps.Clear();
            }

            string info = $"GameBoy FPS: {_averageGbFps:0.00} (Min: {_minGbFps:0.00}, Max: {_maxGbFps:0.00})\n" +
                          $"Clock FPS: {_averageFps:0.00} (Min: {_minFps:0.00}, Max: {_maxFps:0.00})\n" +
                          $"Speed Factor: {_speedFactor:0.00}\n" +
                          $"GBC Mode: {(GameBoy.Cpu.DoubleSpeed ? "Double speed" : "Normal speed")}\n" +
                          $"LY: {GameBoy.Gpu.LY}\n" +
                          $"LYC: {GameBoy.Gpu.LYC}\n";

            _spriteBatch.DrawString(_font, info, new Vector2(1, 1), Color.Black);
            _spriteBatch.DrawString(_font, info, new Vector2(0, 0), Color.Cyan);
        }
Esempio n. 24
0
        public Axis InferYAxis(IList <Tuple <StandardUnit, double> > dataRanges)
        {
            double highest = dataRanges.Any() ? dataRanges.Max(x => x.Item2) : 0d;
            double lowest  = dataRanges.Any() ? dataRanges.Min(x => x.Item2) : 0d;

            var yAxis = new LinearAxis
            {
                Position           = AxisPosition.Left,
                Minimum            = lowest,
                IntervalLength     = 30,
                Maximum            = highest,
                TicklineColor      = OxyColor.FromArgb(0, 0, 0, 0),
                MajorGridlineStyle = LineStyle.Solid,
                MajorGridlineColor = OxyColor.FromRgb(230, 230, 230),
                MinorGridlineStyle = LineStyle.Solid,
                MinorGridlineColor = OxyColor.FromRgb(244, 244, 244)
            };

            if (!dataRanges.Any())
            {
                return(yAxis);
            }

            StandardUnit unit = dataRanges.First().Item1;

            // Only apply formatting for specific unit
            // if all data points are using the same
            if (dataRanges.All(x => x.Item1 == unit))
            {
                yAxis.LabelFormatter = unit.GetLabelFormatter();
            }

            return(yAxis);
        }
Esempio n. 25
0
        private IEnumerable <Tuple <ShipType, CellPosition, bool> > GenerateContinuesForDamagedShip(
            IList <CellPosition> damagedShipCells, IGameFieldBuilder builder, bool vertical, ShipType ship)
        {
            if (builder.ShipsLeft[ship] == 0)
            {
                yield break;
            }

            var topLeftCell = damagedShipCells.Min();
            var delta       = vertical ? CellPosition.DeltaDown : CellPosition.DeltaRight;

            var start = vertical
                ? new CellPosition(0, topLeftCell.Column)
                : new CellPosition(topLeftCell.Row, 0);

            for (; builder.Contains(start); start += delta)
            {
                if (!builder.CanBeAddedSafely(ship, start, vertical, x => OpponentFieldKnowledge[x] != false))
                {
                    continue;
                }
                var newShipCells = Enumerable.Range(0, ship.GetLength()).Select(x => start + delta * x).ToList();
                if (damagedShipCells.Any(x => !newShipCells.Contains(x)))
                {
                    continue;
                }
                yield return(Tuple.Create(ship, start, vertical));
            }
        }
        private LeagueResult FindWinningTeam(IList <LeagueResult> leagueResults)
        {
            var minDiffBetweenForAndAgainst = leagueResults.Min(league => Math.Abs(league.GoalsFor - league.GoalsAgainst));
            var winningTeam = leagueResults.First(league => minDiffBetweenForAndAgainst == Math.Abs(league.GoalsFor - league.GoalsAgainst));

            return(winningTeam);
        }
Esempio n. 27
0
        private static StageSummary Summarize(IList <RequestSummary> requests)
        {
            var durations = requests.Select(x => x.DurationMs).OrderBy(_ => _).ToArray();

            var statusCodes = requests
                              .GroupBy(x => x.RoundStatusCode())
                              .ToDictionary(x => x.Key, x => x.ToList().Count);

            return(new StageSummary
            {
                Stage = requests.First().Stage,
                Url = requests.First().Url,
                Http2xx = statusCodes.TryGetValue(200, out var count2xx) ? count2xx : 0,
                Http3xx = statusCodes.TryGetValue(300, out var count3xx) ? count3xx : 0,
                Http4xx = statusCodes.TryGetValue(400, out var count4xx) ? count4xx : 0,
                Http5xx = statusCodes.TryGetValue(500, out var count5xx) ? count5xx : 0,
                Average = Math.Round(requests.Average(x => x.DurationMs), 2),
                Minimum = requests.Min(x => x.DurationMs),
                Maximum = requests.Max(x => x.DurationMs),
                StdDev = durations.CalculateStandardDeviation(),
                Percentile50 = durations.CalculatePercentile(0.5),
                Percentile66 = durations.CalculatePercentile(0.66),
                Percentile75 = durations.CalculatePercentile(0.75),
                Percentile80 = durations.CalculatePercentile(0.8),
                Percentile90 = durations.CalculatePercentile(0.9),
                Percentile95 = durations.CalculatePercentile(0.95),
                Percentile98 = durations.CalculatePercentile(0.98),
                Percentile99 = durations.CalculatePercentile(0.99)
            });
        /// <summary>
        /// Adds the value for selected characters.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="item">The item.</param>
        /// <param name="labels">The labels.</param>
        /// <param name="values">The values.</param>
        private void AddValueForSelectedCharacters <T>(ListViewItem item, IList <string> labels, IList <T> values)
        {
            T    min      = values.Any() ? values.Min() : default(T);
            T    max      = values.Any() ? values.Max() : default(T);
            bool allEqual = !values.Any() || values.All(value => value.Equals(min));

            // Add the value for every selected item
            for (int index = 0; index < m_selectedCharacters.Count(); index++)
            {
                // Create the subitem and choose its forecolor
                var subItem = new ListViewItem.ListViewSubItem(item, labels[index]);
                if (!allEqual)
                {
                    if (values[index].Equals(max))
                    {
                        subItem.ForeColor = Color.DarkGreen;
                    }
                    else if (values[index].Equals(min))
                    {
                        subItem.ForeColor = Color.DarkRed;
                    }

                    item.UseItemStyleForSubItems = false;
                }
                else if (m_selectedCharacters.Count() > 1)
                {
                    subItem.ForeColor            = Color.DarkGray;
                    item.UseItemStyleForSubItems = false;
                }

                item.SubItems.Add(subItem);
            }
        }
Esempio n. 29
0
        private TransitionResult SwitchState(IList <CashinState> expectedStates, CashinState nextState)
        {
            if (expectedStates.Contains(State))
            {
                State = nextState;

                return(TransitionResult.Switched);
            }

            if (State < expectedStates.Max())
            {
                // Throws to retry and wait until aggregate will be in the required state
                throw new InvalidAggregateStateException(State, expectedStates, nextState);
            }

            if (State > expectedStates.Min())
            {
                // Aggregate already in the next state, so this event can be just ignored
                return(State == nextState
                    ? TransitionResult.AlreadyInTargetState
                    : TransitionResult.AlreadyInFutureState);
            }

            throw new InvalidOperationException("This shouldn't be happened");
        }
Esempio n. 30
0
        /// <summary>
        /// Public API: Sorts ascending
        /// </summary>
        public static void BucketSortAscending(this IList <int> collection)
        {
            int maxValue = collection.Max();
            int minValue = collection.Min();

            List <int>[] bucket = new List <int> [maxValue - minValue + 1];

            for (int i = 0; i < bucket.Length; i++)
            {
                bucket[i] = new List <int>();
            }

            foreach (int i in collection)
            {
                bucket[i - minValue].Add(i);
            }

            int k = 0;

            foreach (List <int> i in bucket)
            {
                if (i.Count > 0)
                {
                    foreach (int j in i)
                    {
                        collection[k] = j;
                        k++;
                    }
                }
            }
        }
        public int GetNextBusIdMultipliedByWaitTime()
        {
            int nextDepartureTimestamp = _buses.Min(b => b.NextDepartureTimestamp);
            Bus nextBus = _buses.SingleOrDefault(b => b.NextDepartureTimestamp == nextDepartureTimestamp);

            return(nextBus.Id * (nextDepartureTimestamp - _timestamp));
        }
Esempio n. 32
0
        public static DateTime getEarliestDeliverByDate(IList <Delivery> deliveries)
        {
            var earliestDate = deliveries
                               .Min(r => r.DeliverBy);

            return(earliestDate.Value);
        }
Esempio n. 33
0
        private double[] GetWeightingFactor(IList <DeconvolutedPeak> peakSet)
        {
            var maxCharge = peakSet.Max(p => p.Charge);
            var minCharge = peakSet.Min(p => p.Charge);
            var weights   = new double[peakSet.Count];

            if (maxCharge == minCharge)
            {
                for (var i = 0; i < peakSet.Count; i++)
                {
                    weights[i] = 1;
                }
                return(weights);
            }

            for (var i = 0; i < peakSet.Count; i++)
            {
                var iPeak = peakSet[i];
                for (var j = 0; j < peakSet.Count; j++)
                {
                    var jPeak = peakSet[j];
                    if (iPeak.Charge == jPeak.Charge)
                    {
                        continue;
                    }
                    var denominator = (double)iPeak.Charge / jPeak.Charge;
                    var numerator   = Math.Abs(denominator - jPeak.MzWithoutAdductIonMass / iPeak.MzWithoutAdductIonMass);
                    weights[i] += Math.Pow(numerator / denominator, WeightingIndex);
                }
                weights[i] *= (maxCharge - minCharge);
            }

            return(weights);
        }
Esempio n. 34
0
        // wypisanie parametrow na konsole
        private static void SaveResults(Configuration config, Bitmap bitmap, IDictionary <int, IList <TimeSpan> > results, string implIdentifier)
        {
            string resultPath = $"{config.InputPath}_{implIdentifier}.txt";

            //tworzenie wyniku
            StringBuilder builder = new StringBuilder();

            builder.AppendLine($"File: {config.InputPath}, size: {bitmap.Width}x{bitmap.Height} (width x height).");
            builder.AppendLine($"Iterations: {config.IterationCount}, sigma: {config.Sigma}.");

            builder.AppendLine();
            builder.AppendLine("Threads;Min [ms];Max [ms];Average [ms]; StDev [ms]");

            for (int i = 1; i <= config.MaxThreadsCount; i++)
            {
                IList <TimeSpan> timeSpans = results[i];

                TimeSpan min               = timeSpans.Min();
                TimeSpan max               = timeSpans.Max();
                TimeSpan average           = new TimeSpan((long)timeSpans.Average(t => t.Ticks));
                TimeSpan standardDeviation = CalculateStandardDeviation(timeSpans);
                builder.AppendLine($"{i};{min.TotalMilliseconds};{max.TotalMilliseconds};{average.TotalMilliseconds};{standardDeviation.TotalMilliseconds}");
            }

            File.WriteAllText(resultPath, builder.ToString());
        }
Esempio n. 35
0
        public PointPairList getDensityCurve(IList <double> data, double bandwidth)
        {
            int intervals = 1000;
            var result    = new PointPairList {
                Capacity = intervals
            };

            //generate a base line
            var    statistics = new DescriptiveStatistics(data);
            double minValue   = data.Min() - (2 * statistics.StandardDeviation);
            double maxValue   = data.Max() + (2 * statistics.StandardDeviation);
            double interval   = (maxValue - minValue) / intervals * 1.0;

            for (int i = 0; i < intervals; i++)
            {
                result.Add(minValue + i * interval, 0);
            }

            if (bandwidth == 0)
            {
                bandwidth = 1.06 * statistics.StandardDeviation * Math.Pow(data.Count, -1.0 / 5);
            }

            var orderedData = data.OrderBy(o => o);

            foreach (var value in orderedData)
            {
                Normal nD = new Normal(0, 1);
                for (int q = 0; q < intervals; q++)
                {
                    result[q].Y += (1 / (data.Count * bandwidth)) * nD.Density((value - result[q].X) / bandwidth);
                }
            }
            return(result);
        }
        /// <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);
        }
Esempio n. 37
0
        public virtual IList <TKLineToday> GetStockClosePrices(IList <DateTime> queryDates, IList <string> stockFullCodes)
        {
            var result = new List <TKLineToday>();

            if (queryDates == null || !queryDates.Any())
            {
                return(result);
            }

            string stockCodeConditionString = string.Empty;
            string sql = @" SELECT [Id] , [StockCode] , [TradeDate] , [Close]  FROM  [dbo].[TKLineToday] WHERE [TradeDate] BETWEEN '{0}' AND '{1}' ";

            if (stockFullCodes != null && stockFullCodes.Any())
            {
                sql += @" AND [StockCode] IN ({2}) ";
                stockCodeConditionString = CommonHelper.ArrayListToSqlConditionString(stockFullCodes);
            }

            var commandText = stockFullCodes == null?string.Format(sql, queryDates.Min(), queryDates.Max()) : string.Format(sql, queryDates.Min(), queryDates.Max(), stockCodeConditionString);

            var query = _dbContext.SqlQuery <TKLineToday>(commandText);

            result.AddRange(query.ToList());

            return(result);
        }
Esempio n. 38
0
        /// <summary>
        /// 获取最低水平线
        /// </summary>
        /// <returns></returns>
        public IList <OutLine> getLowestOutline()
        {
            //最低水平线
            float minY = outLineList.Min(m => m.Y);

            return(new List <OutLine>(outLineList.Where(m => m.Y == minY)));
        }
Esempio n. 39
0
        // Минимальное значение
        public int MinValueIntegerToListInt(IList list)
        {
            IList <int> listInt = list.Cast <int>().
                                  Select(r => Convert.ToInt32(r)).ToList();

            return(listInt.Min());
        }
Esempio n. 40
0
        private double choosePrice(IList <double> prices)
        {
            double median = this.getMedian(prices);

            prices = prices.Where(price => median * 0.2 < price).ToList();
            return(prices.Min());
        }
        private double CalculateOptimalBinWidth(IList <double> sequence)
        {
            double xMax = sequence.Max(), xMin = sequence.Min();
            int    minBins = 4, maxBins = 16;

            double[] N = Enumerable.Range(minBins, maxBins - minBins)
                         .Select(v => (double)v).ToArray();
            double[] D = N.Select(v => (xMax - xMin) / v).ToArray();
            double[] C = new double[D.Length];

            for (int i = 0; i < N.Length; i++)
            {
                double[] binIntervals = LinearSpace(xMin, xMax, (int)N[i] + 1);
                int[]    ki           = Histogram(sequence, binIntervals);
                ki = ki.Skip(1).Take(ki.Length - 2).ToArray();

                double mean     = ki.Average();
                double variance = ki.Select(v => Math.Pow(v - mean, 2)).Sum() / N[i];

                C[i] = (2 * mean - variance) / (Math.Pow(D[i], 2));
            }

            double minC  = C.Min();
            int    index = C.Select((c, ix) => new { Value = c, Index = ix })
                           .Where(c => c.Value == minC).First().Index;

            // optimal bin width
            return(D[index]);
        }
Esempio n. 42
0
    private static IList <Point> MakeHullNaive(IList <Point> points)
    {
        if (points.Count <= 1)
        {
            return(new List <Point>(points));
        }
        IList <Point> result = new List <Point>();

        // Jarvis march / gift wrapping algorithm
        Point point = points.Min();

        do
        {
            result.Add(point);
            Point next = points[0];
            foreach (Point p in points)
            {
                double ax    = next.x - point.x;
                double ay    = next.y - point.y;
                double bx    = p.x - point.x;
                double by    = p.y - point.y;
                double cross = ax * by - ay * bx;
                if (cross > 0 || cross == 0 && bx * bx + by * by > ax * ax + ay * ay)
                {
                    next = p;
                }
            }
            point = next;
        } while (point.CompareTo(result[0]) != 0);
        return(result);
    }
Esempio n. 43
0
        /// <summary>
        /// Generate the tag clound using a template provided by caller.
        /// e.g. ( span id="weight${weight}" ${name} ${urlLink} ).
        /// </summary>
        /// <param name="tagData"></param>
        /// <param name="template"></param>
        /// <returns></returns>
        public static string BuildTagCloud(IList <TagSummary> tagData, string template)
        {
            // Need to get min/max.
            StringBuilder buffer = new StringBuilder();

            if (tagData == null || tagData.Count == 0)
            {
                return(string.Empty);
            }

            double min = tagData.Min(t => t.Count);
            double max = tagData.Max(t => t.Count);

            foreach (var tag in tagData)
            {
                // Get ratio of 1 tag in relation to max
                double ratio = ((double)tag.Count / max) * 100;
                int    size  = 0;

                if (ratio >= 98)
                {
                    size = 1;
                }
                else if (ratio >= 80)
                {
                    size = 2;
                }
                else if (ratio >= 60)
                {
                    size = 3;
                }
                else if (ratio >= 40)
                {
                    size = 4;
                }
                else if (ratio >= 20)
                {
                    size = 5;
                }
                else if (ratio >= 5)
                {
                    size = 6;
                }
                else
                {
                    size = 0;
                }

                // Exclude very low weights.
                if (size > 0)
                {
                    string output = template.Replace("${size}", size.ToString());
                    string urltag = System.Web.HttpUtility.UrlEncode(tag.Name);
                    output = output.Replace("${urltagname}", urltag);
                    output = output.Replace("${tagname}", tag.Name);
                    buffer.Append(output);
                }
            }
            return(buffer.ToString());
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                // build start/end year
                IList <AnnualSalesData> rawData = GetAnnualSalesData();
                int minYear = 1900;
                int maxYear = LocaleHelper.LocalNow.Year;

                if (rawData.Count > 0)
                {
                    minYear = rawData.Min(x => x.SalesYear);
                    maxYear = rawData.Max(x => x.SalesYear);
                }

                // set up dropdown choices
                for (int year = minYear; year <= maxYear; year++)
                {
                    list_StartYear.Items.Add(new ListItem(year.ToString()));
                    list_EndYear.Items.Add(new ListItem(year.ToString()));
                }

                // default to most recent 3 years
                int startYear = Math.Max(minYear, LocaleHelper.LocalNow.Year - 2);
                list_StartYear.SelectedValue = startYear.ToString();
                list_EndYear.SelectedValue   = maxYear.ToString();

                // bind report
                ProcessButton_Click(null, null);
            }
        }
        private void UpdateCandlesInfo(string assetPairId, IList <Candle> candles, List <MarketSlice> marketData)
        {
            var firstCandle = candles.First();
            var lastCandle  = candles.Last();

            var marketSlice = new MarketSlice
            {
                AssetPairId = assetPairId,
                VolumeBase  = candles.Sum(c => c.TradingVolume).ToString(CultureInfo.InvariantCulture),
                VolumeQuote = candles.Sum(c => c.TradingOppositeVolume).ToString(CultureInfo.InvariantCulture),
                PriceChange = firstCandle.Open > 0
                    ? ((lastCandle.Close - firstCandle.Open) / firstCandle.Open).ToString(CultureInfo.InvariantCulture)
                    : "0",
                High = candles.Max(c => c.High).ToString(CultureInfo.InvariantCulture),
                Low  = candles.Min(c => c.Low).ToString(CultureInfo.InvariantCulture),
            };

            var existingRecord = marketData.FirstOrDefault(x => x.AssetPairId == assetPairId);

            if (existingRecord != null)
            {
                existingRecord.VolumeBase  = marketSlice.VolumeBase;
                existingRecord.VolumeQuote = marketSlice.VolumeQuote;
                existingRecord.PriceChange = marketSlice.PriceChange;
                existingRecord.High        = marketSlice.High;
                existingRecord.Low         = marketSlice.Low;
            }
            else
            {
                marketData.Add(marketSlice);
            }
        }
Esempio n. 46
0
        // The idea is to have a page dictionary in memory that holds SinceId and MaxId for every page
        // and use them as page borders so we can tell the twitter API
        // form which to which Id to load the tweets for the specific page
        private void SetPageTweetBorders(int pageIndex, IList <TweetDto> tweetsResult)
        {
            var pages = new Dictionary <int, PageTweetBorders>();

            string pagesKey = $"tweet-pages";

            if (TempData.ContainsKey(pagesKey))
            {
                pages =
                    JsonConvert.DeserializeObject <Dictionary <int, PageTweetBorders> >(TempData[pagesKey].ToString());
            }

            if (!pages.ContainsKey(pageIndex))
            {
                pages.Add(pageIndex, new PageTweetBorders()
                {
                    Page    = pageIndex,
                    MaxId   = tweetsResult?.Max(tweet => tweet.Id) ?? 0,
                    SinceId = tweetsResult?.Min(tweet => tweet.Id) ?? 0
                });
            }

            string pagesJson = JsonConvert.SerializeObject(pages);

            if (TempData.ContainsKey(pagesKey))
            {
                TempData[pagesKey] = pagesJson;
            }
            else
            {
                TempData.Add(pagesKey, pagesJson);
            }
        }
Esempio n. 47
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);
        }
Esempio n. 48
0
        private static void CalculatePickList(IList<Product> allProducts,
            int columnSize, bool[,] pickList)
        {
            var valueList = new int[columnSize];
            var minVolumeIdx = allProducts.Min(x => x.Dimension.Volume) - 1;

            for (var idx = 0; idx < allProducts.Count; idx++)
            {
                var product = allProducts[idx];
                var tempValueList = new int[columnSize];

                for (var volIdx = minVolumeIdx; volIdx < columnSize; volIdx++)
                {
                    var chosenVal = 0;
                    var keep = false;

                    var isWithin = product.Dimension.Volume <= volIdx;

                    var valueOfCellAbove = valueList[volIdx];

                    if (isWithin)
                    {
                        var remainingSpace = volIdx - product.Dimension.Volume;
                        var otherPossibleVal = valueList[remainingSpace];

                        var finalPossibleVal = product.Price + otherPossibleVal;

                        if (valueOfCellAbove <= finalPossibleVal)
                        {
                            chosenVal = finalPossibleVal;
                            keep = true;
                        }
                        else
                        {
                            chosenVal = valueOfCellAbove;
                            keep = false;
                        }
                    }
                    else
                    {
                        chosenVal = valueOfCellAbove;
                        keep = false;
                    }

                    pickList[idx, volIdx] = keep;
                    tempValueList[volIdx] = chosenVal;
                }

                for (var i = 0; i < columnSize; i++)
                {
                    valueList[i] = tempValueList[i];
                }
            }
        }
Esempio n. 49
0
		private void ExecuteIndexingInternal(IList<IndexToWorkOn> indexesToWorkOn, Action<IEnumerable<Tuple<IndexToWorkOn, IEnumerable<JsonDocument>>>> indexingOp)
		{
			var lastIndexedGuidForAllIndexes = indexesToWorkOn.Min(x => new ComparableByteArray(x.LastIndexedEtag.ToByteArray())).ToGuid();

			JsonDocument[] jsonDocs = null;
			try
			{
				transactionalStorage.Batch(actions =>
				{
					jsonDocs = actions.Documents.GetDocumentsAfter(lastIndexedGuidForAllIndexes)
						.Where(x => x != null)
						.Select(doc =>
						{
							DocumentRetriever.EnsureIdInMetadata(doc);
							return doc;
						})
						.Take(context.Configuration.MaxNumberOfItemsToIndexInSingleBatch) // ensure that we won't go overboard with reading and blow up with OOM
						.ToArray();
				});

				if (jsonDocs.Length > 0)
				{
					var result = FilterIndexes(indexesToWorkOn, jsonDocs).ToList();
					indexesToWorkOn = result.Select(x => x.Item1).ToList();
					indexingOp(result);
				}
			}
			finally
			{
				if (jsonDocs != null && jsonDocs.Length > 0)
				{
					var last = jsonDocs.Last();
					
					Debug.Assert(last.Etag != null);
					Debug.Assert(last.LastModified != null);

					var lastEtag = last.Etag.Value;
					var lastModified = last.LastModified.Value;

					var lastIndexedEtag = new ComparableByteArray(lastEtag.ToByteArray());
					// whatever we succeeded in indexing or not, we have to update this
					// because otherwise we keep trying to re-index failed documents
					transactionalStorage.Batch(actions =>
					{
						foreach (var indexToWorkOn in indexesToWorkOn)
						{
							MarkIndexes(indexToWorkOn, lastIndexedEtag, actions, lastEtag, lastModified);
						}
					});
				}
			}
		}
 public static IList<Team> CalcSmallestDiff(IList<Team> teams)
 {
     // use LinQ to find the minimum difference
     var smallest = teams.Min(team => team.Diff);
     // Need to cater for multiple teams having the minimum diff
     var smallestTeams = new List<Team>();
     foreach (var team in teams)
     {
         if (team.Diff == smallest)
         {
             smallestTeams.Add(team);
             team.SmallestDiff = true;
         }
     }
     return smallestTeams;
 }
 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();
     }
 }
Esempio n. 52
0
        private int MinimalMoves(IList<Group> groups)
        {
            int result = Int32.MaxValue;

            int minlength = groups.Min(gr => gr.Count);
            int maxlength = groups.Max(gr => gr.Count);

            for (int k = minlength; k <= maxlength; k++)
            {
                int moves = DistanceTo(groups, k);
                if (moves < result)
                    result = moves;
            }

            return result;
        }
Esempio n. 53
0
		protected override void ExecuteIndexingWork(IList<IndexToWorkOn> indexesToWorkOn)
		{
			indexesToWorkOn = context.Configuration.IndexingScheduler.FilterMapIndexes(indexesToWorkOn);

			var lastIndexedGuidForAllIndexes = indexesToWorkOn.Min(x => new ComparableByteArray(x.LastIndexedEtag.ToByteArray())).ToGuid();

			context.CancellationToken.ThrowIfCancellationRequested();

			var operationCancelled = false;
			TimeSpan indexingDuration = TimeSpan.Zero;
			List<JsonDocument> jsonDocs = null;
			var lastEtag = Guid.Empty;
			try
			{
				jsonDocs = prefetchingBehavior.GetDocumentsBatchFrom(lastIndexedGuidForAllIndexes);

				if (Log.IsDebugEnabled)
				{
					Log.Debug("Found a total of {0} documents that requires indexing since etag: {1}: ({2})",
							  jsonDocs.Count, lastIndexedGuidForAllIndexes, string.Join(", ", jsonDocs.Select(x => x.Key)));
				}

				context.ReportIndexingActualBatchSize(jsonDocs.Count);
				context.CancellationToken.ThrowIfCancellationRequested();

				if (jsonDocs.Count <= 0)
					return;

				var sw = Stopwatch.StartNew();
				lastEtag = DoActualIndexing(indexesToWorkOn, jsonDocs);
				indexingDuration = sw.Elapsed;
			}
			catch (OperationCanceledException)
			{
				operationCancelled = true;
			}
			finally
			{
				if (operationCancelled == false && jsonDocs != null && jsonDocs.Count > 0)
				{
					prefetchingBehavior.CleanupDocumentsToRemove(lastEtag);
					UpdateAutoThrottler(jsonDocs, indexingDuration);
				}

				prefetchingBehavior.BatchProcessingComplete();
			}
		}
Esempio n. 54
0
 private ReportsViewModel BuildReportsModel(IList<UserReport> reports, int pageSize = int.MaxValue)
 {
     var model = new ReportsViewModel
     {
         Reports = reports
     };
     if (reports.Any())
     {
         model.FirstDate = (DateTime?)reports.Max(r => r.CreationDate);
         model.LastDate = (DateTime?)reports.Min(r => r.CreationDate);
     }
     foreach (var report in reports)
     {
         InitUserReport(report);
     }
     return model;
 }
Esempio n. 55
0
        //public static void CleanTitles(this Chart chart)
        //{
        //    foreach (var series in chart.Data.Series)
        //    {
        //        series.Name = RemovePrefixes(series.Name);
        //        foreach (var value in series.Values)
        //        {
        //            value.Label = RemovePrefixes(value.Label);
        //        }
        //    }
        //}
        public static IList<int> ParseYears(string yearsConfig, IList<int> yearsFromDb)
        {
            var result = new List<int>();
            var max = yearsFromDb.Max();
            var min = yearsFromDb.Min();
            var periods = yearsConfig.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);
            foreach (var period in periods)
            {
                int val;
                // if value
                if (Int32.TryParse(period, out val) && yearsFromDb.Contains(val))
                {
                    result.Add(val);
                }
                else
                {
                    // if actual period
                    if (period.Contains("-"))
                    {
                        var bounds = period.Split(new[] {'-'}, StringSplitOptions.RemoveEmptyEntries);
                        if (bounds.Length != 2)
                        {
                            throw new ApplicationException("Incorrect period " + period);
                        }
                        var start = ParseYearConstant(bounds[0], min, max, yearsFromDb);
                        var end = ParseYearConstant(bounds[1], min, max, yearsFromDb);

                        for (var i = start; i <= end; i++)
                        {
                            result.Add(i);
                        }
                    }
                    // if year constant
                    else
                    {
                        result.Add(ParseYearConstant(period, min, max, yearsFromDb));
                    }
                }
            }

            return result;
        }
        private void ReadWellPoints()
        {
            _points = DataReader.ReadWells(@"Draw\B2-HO.txt");
            _xMin = _points.Min(p => p.X);
            _xMax = _points.Max(p => p.X);
            _yMin = _points.Min(p => p.Y);
            _yMax = _points.Max(p => p.Y);

            foreach (var point in _points)
            {
                var ellipse = new Ellipse();
                ellipse.Width = 10;
                ellipse.Height = 10;
                ellipse.Stroke = new SolidColorBrush(Colors.Black);
                drawCanvas.Children.Add(ellipse);

                _drawObjects.Add(point, new DrawObject()
                    {
                        Shape = ellipse
                    });
            }
        }
Esempio n. 57
0
        public int CalculateWar(IList<double> first, IList<double> second)
        {
            if (first.Count == 0)
                return 0;

            double play1 = first.Max();
            double play2;
            bool win = false;

            var greater = second.Where(n => n > play1).ToList();

            if (greater.Count > 0)
                play2 = greater.Min();
            else
            {
                play2 = second.Min();
                win = true;
            }

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

            return CalculateWar(newfirst, newsecond) + (win ? 1 : 0);
        }
Esempio n. 58
0
        private BinaryGeneration CreateNextGeneration(BinaryGeneration generation, IList<BinaryEntity> children)
        {
            if (children.Any())
            {
                var bestChild = children.First(x => Math.Abs(x.Value - children.Min(c => c.Value)) < 0.01);
                bestChild.Function = EntityFunction.BestChild;
                var nextGeneration = new List<Entity<BinaryGenom>>(generation.Winners());
                nextGeneration.Add(bestChild);
                return new BinaryGeneration(nextGeneration
                    .OfType<BinaryEntity>()
                    .Select(x => new BinaryEntity(x))
                    .OfType<Entity<BinaryGenom>>()
                    .ToList())
                    .MarkUpGenereation();
            }

            return generation;
        }
 private bool StraightInHand(IList<Card> cards)
 {
     // theres probably a better way to do this whole thing with linq... but I can't figure it out.
     int maxSequenceLength = 1;
     CardFigure minCard = cards.Min<Card, CardFigure>(key => key.Figure);
     CardFigure maxCard = cards.Max<Card, CardFigure>(key => key.Figure);
     CardFigure lastCard = minCard;
     int totalCardFigures = 0;
     // go through the cards except the lowest card - we've already handled it in variable assignment
     foreach (Card card in cards.OrderBy<Card, CardFigure>(key => key.Figure).Skip<Card>(1))
     {
         // if this card is one higher than the last one was
         maxSequenceLength += ((lastCard + 1) == card.Figure) ? 1 : 0;
         lastCard = card.Figure;
         // theres got to be a better way then summing all cards A,2,3,4,5 == 22
         totalCardFigures += (int)card.Figure;
     }
     // Either you have to have 5 cards in a row
     // or it is also valid to have 4 cards in a row, if your min card is a two and your max card is an ace
     // this handles the problematic ace wraparound where an ace can be at either end of a straight
     return (maxSequenceLength >= 5) ||
           ((maxSequenceLength == 4) && (maxCard == CardFigure.Ace) && (totalCardFigures == 22)); // A,2,3,4,5 == 22
 }
Esempio n. 60
0
    private void ListTable(IList<ProductionPlanDet> productionPlanDetList)
    {
        if (productionPlanDetList == null || productionPlanDetList.Count == 0)
        {
            this.list.InnerHtml = "没有查到符合条件的记录";
            return;
        }

        var minStartTime = productionPlanDetList.Min(s => s.StartTime).AddDays(13);
        productionPlanDetList = productionPlanDetList.Where(s => s.StartTime <= minStartTime).ToList();

        #region   trace
        List<ProductionPlanDetTrace> traceList = new List<ProductionPlanDetTrace>();
        int len = 0;
        int j = productionPlanDetList.Count % 2000 == 0 ? productionPlanDetList.Count / 2000 : productionPlanDetList.Count / 2000 + 1;
        while (true)
        {
            var cList = this.TheGenericMgr.FindAllWithCustomQuery<ProductionPlanDetTrace>(string.Format(" select l from ProductionPlanDetTrace as l where l.Type='{0}' and  l.UUID in ('{1}') ", this.rbType.SelectedValue, string.Join("','", productionPlanDetList.Skip(len * 2000).Take((len + 1) * 2000).Select(d => d.UUID).Distinct().ToArray())));
            if (cList != null && cList.Count > 0) { traceList.AddRange(cList); }
            len++;
            if (len == j) break;
        }
        traceList = traceList == null ? new List<ProductionPlanDetTrace>() : traceList;
        if (traceList != null && traceList.Count > 0)
        {
            foreach (var sd in productionPlanDetList)
            {
                var currentLogs = traceList.Where(d => d.UUID == sd.UUID).OrderBy(d => d.ReqDate).ToList();
                var showText = string.Empty;
                if (currentLogs != null && currentLogs.Count > 0)
                {
                    showText = "<table><thead><tr><th>发运路线</th><th>物料</th><th>Bom</th><th>需求日期</th><th>需求数</th></tr></thead><tbody><tr>";
                    foreach (var c in currentLogs)
                    {
                        showText += "<td>" + c.Flow + "</td><td>" + c.Item + "</td><td>" + c.Bom + "</td><td>" + c.ReqDate.ToShortDateString() + "</td><td>" + c.ReqQty.ToString("0.##") + "</td></tr><tr>";
                    }
                    showText += " </tr></tbody></table> ";
                }
                sd.Logs = showText;
            }
        }
        #endregion

        #region  orderQty
        List<ProductionPlanOpenOrder> productionPlanOpenOrderList = new List<ProductionPlanOpenOrder>();
        len = 0;
        while (true)
        {
            var cList = this.TheGenericMgr.FindAllWithCustomQuery<ProductionPlanOpenOrder>(string.Format(" select l from ProductionPlanOpenOrder as l where l.Type='{0}' and  l.UUID in ('{1}') ", this.rbType.SelectedValue, string.Join("','", productionPlanDetList.Skip(len * 2000).Take((len + 1) * 2000).Select(d => d.UUID).Distinct().ToArray())));
            if (cList != null && cList.Count > 0) { productionPlanOpenOrderList.AddRange(cList); }
            len++;
            if (len == j) break;
        }
        // productionPlanOpenOrderList = this.TheGenericMgr.FindAllWithCustomQuery<ProductionPlanOpenOrder>(string.Format(" select l from ProductionPlanOpenOrder as l where l.Type='{0}' and l.UUID in ('{1}') ", this.rbType.SelectedValue, string.Join("','", productionPlanDetList.Select(d => d.UUID).Distinct().ToArray())));
        productionPlanOpenOrderList = productionPlanOpenOrderList == null ? new List<ProductionPlanOpenOrder>() : productionPlanOpenOrderList;
        if (productionPlanOpenOrderList != null && productionPlanOpenOrderList.Count > 0)
        {
            foreach (var sd in productionPlanDetList)
            {
                var currentOrders = productionPlanOpenOrderList.Where(d => d.UUID == sd.UUID).OrderBy(d=>d.WindowTime).ToList();
                var showText = string.Empty;
                if (currentOrders != null && currentOrders.Count > 0)
                {
                    showText = "<table><thead><tr><th>路线</th><th>订单号</th><th>物料</th><th>订单数</th><th>收货数</th><th>开始时间</th><th>窗口时间</th></tr></thead><tbody><tr>";
                    foreach (var c in currentOrders)
                    {
                        showText += "<td>" + c.Flow + "</td><td>" + c.OrderNo + "</td><td>" + c.Item + "</td><td>" + c.OrderQty.ToString("0.##") + "</td><td>" + c.RecQty.ToString("0.##") + "</td><td>" + c.StartTime.ToShortDateString() + "</td><td>" + c.WindowTime.ToShortDateString() + "</td></tr><tr>";
                    }
                    showText += " </tr></tbody></table> ";
                }
                sd.OrderDets = showText;
            }
        }
        #endregion

        var planByDateIndexs = productionPlanDetList.GroupBy(p => p.StartTime).OrderBy(p => p.Key);
        var planByItems = productionPlanDetList.GroupBy(p => p.Item);

        StringBuilder str = new StringBuilder();
        //str.Append(CopyString());
        //head
        string headStr = string.Empty;
        str.Append("<thead><tr class='GVHeader'><th rowspan='2'>序号</th><th rowspan='2'>物料号</th><th rowspan='2'>物料描述</th><th rowspan='2'>客户零件号</th><th rowspan='2'>包装量</th><th rowspan='2'>经济批量</th><th rowspan='2'>安全库存</th><th rowspan='2'>最大库存</th><th rowspan='2'>期初库存</th><th rowspan='2'>报验</th><th rowspan='2'>库存倒数</th>");
        int ii = 0;
        foreach (var planByDateIndex in planByDateIndexs)
        {
            ii++;
            str.Append("<th colspan='4'>");
            //if (productionPlanDetList.First().Status == BusinessConstants.CODE_MASTER_STATUS_VALUE_SUBMIT && planByDateIndex.Key.Date == System.DateTime.Now.Date)
            //{
            //    str.Append("<input type='checkbox' id='CheckAll' name='CheckAll'  onclick='doCheckAllClick()' />");
            //}
            str.Append(planByDateIndex.Key.ToString("yyyy-MM-dd"));
            str.Append("</th>");
        }
        str.Append("</tr><tr class='GVHeader'>");
        foreach (var planByDateIndex in planByDateIndexs)
        {
            str.Append("<th >需求</th><th >订单数</th><th >计划数</th><th >期末</th>");
        }
        str.Append("</tr></thead>");
        str.Append("<tbody>");

        #region  通过长度控制table的宽度
        string widths = "100%";
        if (ii > 14)
        {
            widths = "260%";
        }
        else if (ii > 10)
        {
            widths = "210%";
        }
        else if (ii > 6)
        {
            widths = "160%";
        }
        else if (ii > 4)
        {
            widths = "120%";
        }

        headStr += string.Format("<table id='tt' runat='server' border='1' class='GV' style='width:{0};border-collapse:collapse;'>", widths);
        #endregion
        int l = 0;
        int seq = 0;
        foreach (var planByItem in planByItems)
        {
            var firstPlan = planByItem.First();
            var planDic = planByItem.GroupBy(d => d.StartTime).ToDictionary(d => d.Key, d => d.Sum(q => q.Qty));
            l++;
            if (l % 2 == 0)
            {
                str.Append("<tr class='GVAlternatingRow'>");
            }
            else
            {
                str.Append("<tr class='GVRow'>");
            }
            str.Append("<td>");
            str.Append(l);
            str.Append("</td>");
            str.Append("<td>");
            str.Append(planByItem.Key);
            str.Append("</td>");
            str.Append("<td>");
            str.Append(firstPlan.ItemDesc);
            str.Append("</td>");
            str.Append("<td>");
            str.Append(firstPlan.RefItemCode);
            str.Append("</td>");
            str.Append("<td>");
            str.Append(firstPlan.UnitCount.ToString("0.##"));
            str.Append("</td>");
            str.Append("<td>");
            str.Append(firstPlan.MinLotSize.ToString("0.##"));
            str.Append("</td>");
            str.Append("<td>");
            str.Append(firstPlan.SafeStock.ToString("0.##"));
            str.Append("</td>");
            str.Append("<td>");
            str.Append(firstPlan.MaxStock.ToString("0.##"));
            str.Append("</td>");
            var InitStockQty = firstPlan.InitStock + firstPlan.InspectQty;
            if (InitStockQty < firstPlan.SafeStock)
            {
                str.Append("<td style='background:red;color:white'>");
            }
            else if (InitStockQty >= firstPlan.SafeStock && InitStockQty <= firstPlan.MaxStock)
            {
                str.Append("<td style='background:green;color:white'>");
            }
            else if (InitStockQty > firstPlan.MaxStock)
            {
                str.Append("<td style='background:orange'>");
            }
            str.Append((firstPlan.InitStock).ToString("0.##"));
            str.Append("</td>");
            //str.Append("<td>");
            //str.Append((firstPlan.InTransitQty).ToString("0.##"));
            //str.Append("</td>");
            if (InitStockQty < firstPlan.SafeStock)
            {
                str.Append("<td style='background:red;color:white'>");
            }
            else if (InitStockQty >= firstPlan.SafeStock && InitStockQty <= firstPlan.MaxStock)
            {
                str.Append("<td style='background:green;color:white'>");
            }
            else if (InitStockQty > firstPlan.MaxStock)
            {
                str.Append("<td style='background:orange'>");
            }
            str.Append((firstPlan.InspectQty).ToString("0.##"));
            str.Append("</td>");
            str.Append("<td>");
            str.Append(firstPlan.InventoryCountDown.HasValue?firstPlan.InventoryCountDown.Value.ToString("0.##"):"");
            str.Append("</td>");
            foreach (var planByDateIndex in planByDateIndexs)
            {
                var curenPlan = planByItem.Where(p => p.StartTime == planByDateIndex.Key);
                var pdPlan = curenPlan.Count() > 0 ? curenPlan.First() : new ProductionPlanDet();
                str.Append(string.Format("<td tital='{0}'  onclick='doTdClick(this)'>", pdPlan.Logs));
                str.Append(pdPlan.ReqQty.ToString("0.##"));
                str.Append("</td>");
                str.Append(string.Format("<td tital='{0}'  onclick='doShowDetsClick(this)'>", pdPlan.OrderDets));
                str.Append(pdPlan.OrderQty.ToString("0.##"));
                str.Append("</td>");

                //str.Append("<td>");
                //str.Append(pdPlan.Qty.ToString("0.##"));
                //str.Append("</td>");

                if (firstPlan.Status == BusinessConstants.CODE_MASTER_STATUS_VALUE_CREATE)
                {
                    seq++;
                    str.Append("<td width='30px'>");
                    str.Append("<input  type='text'  item='" + firstPlan.Item + "'  name='UpQty' id='" + pdPlan.Id + "'value='" + pdPlan.Qty.ToString("0.##") + "' releaseNo='" + firstPlan.ReleaseNo + "'  dateFrom='" + planByDateIndex.Key + "' style='width:70px' onblur='doFocusClick(this)' seq='" + seq + "' />");
                    str.Append("</td>");
                }
                else
                {
                    str.Append("<td>");
                    //if (planByDateIndex.Key.Date == System.DateTime.Now.Date)
                    //{
                    //    str.Append("<input type='checkbox' id='CheckBoxGroup' name='CheckBoxGroup' value='" + pdPlan.Id + "' runat='' onclick='doCheckClick()' />");
                    //}
                    str.Append(pdPlan.Qty.ToString("0.##"));
                    str.Append("</td>");
                }

                InitStockQty = InitStockQty + pdPlan.Qty-pdPlan.ReqQty+pdPlan.OrderQty;
                if (InitStockQty < firstPlan.SafeStock)
                {
                    str.Append("<td style='background:red;color:white'>");
                }
                else if (InitStockQty >= firstPlan.SafeStock && InitStockQty <= firstPlan.MaxStock)
                {
                    str.Append("<td style='background:green;color:white'>");
                }
                else if (InitStockQty > firstPlan.MaxStock)
                {
                    str.Append("<td style='background:orange'>");
                }
                str.Append(InitStockQty.ToString("0.##"));
                str.Append("</td>");
            }
            str.Append("</tr>");
        }
        str.Append("</tbody></table>");
        this.list.InnerHtml = headStr + str.ToString();
    }