Example #1
0
        private void frmMeasuresEdit_Load(object sender, EventArgs e)
        {
            if (_mid == null)
            {
                ms = _db.Measures.Add(new Measures
                {
                    Deleted   = 0,
                    Def       = _db.Measures.Any(a => a.Def == 1) ? 0 : 1,
                    Name      = "",
                    ShortName = ""
                });
            }
            else
            {
                ms = _db.Measures.Find(_mid);
            }

            MeasuresDS.DataSource = ms;
        }
Example #2
0
        public void MatrixModeTest3()
        {
            double[][] matrix =
            {
                new double[] { 6, 4, 9 },
                new double[] { 3, 1, 3 },
                new double[] { 1, 3, 8 },
                new double[] { 1, 5, 4 },
                new double[] { 7, 4, 1 },
                new double[] { 4, 4, 3 },
            };

            double[] expected = { 1, 4, 3 };
            double[] actual   = Measures.Mode(matrix);

            Assert.AreEqual(expected[0], actual[0]);
            Assert.AreEqual(expected[1], actual[1]);
            Assert.AreEqual(expected[2], actual[2]);
        }
        public IndependentComponentAnalysis(double[,] data, AnalysisMethod method,
                                            IndependentComponentAlgorithm algorithm)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            this.sourceMatrix   = data;
            this.algorithm      = algorithm;
            this.analysisMethod = method;

            // Calculate common measures to speedup other calculations
            this.columnMeans  = Measures.Mean(sourceMatrix, dimension: 0);
            this.columnStdDev = Measures.StandardDeviation(sourceMatrix, columnMeans);

            this.NumberOfInputs  = data.Columns();
            this.NumberOfOutputs = data.Columns();
        }
Example #4
0
        public SalesOrderDetailList SearchSalesOrderDetail(out Measures pTimes)
        {
            double sqlCallTime;
            double mappingTime;
            Hashtable htStats;
            SalesOrderDetailList wSalesOrderDetailList = SampleDAC.Search(base.CompanyId, out mappingTime, out sqlCallTime, out htStats);

            pTimes = new Measures();
            // StringBuilder s = new StringBuilder();
            foreach (string stat in htStats.Keys)
            {
                //s.AppendLine("- " + stat + " = " + htStats[stat].ToString());
                pTimes.Add(stat, Convert.ToDecimal(htStats[stat]));
            }
            pTimes.Add("Sql_Exec_Query_Time", Convert.ToDecimal(sqlCallTime));
            pTimes.Add("Sql_To_Entity_Mapping_Time", Convert.ToDecimal(mappingTime));

            return wSalesOrderDetailList;
        }
Example #5
0
        public void QuartileMatrixTest()
        {
            double[][] values =
            {
                new [] { 52.0 },
                new [] { 42.0 }
            };

            double[] q1, q3, actual;
            actual = Measures.Quartiles(values, out q1, out q3);

            // quantile(c(52, 42), type = 6)
            //   0 % 25 % 50 % 75 % 100 %
            //   42   42   47   52   52

            Assert.AreEqual(47, actual[0]);
            Assert.AreEqual(42, q1[0]);
            Assert.AreEqual(52, q3[0]);
        }
        /// <summary>
        ///   Computes one pass of the pruning algorithm.
        /// </summary>
        ///
        public double Run()
        {
            // Compute misclassifications at each node
            foreach (var node in tree)
            {
                info[node].error = computeError(node);
            }

            // Compute the gain at each node
            foreach (var node in tree)
            {
                info[node].gain = computeGain(node);
            }

            // Get maximum violating node
            double       maxGain = Double.NegativeInfinity;
            DecisionNode maxNode = null;

            foreach (var node in tree)
            {
                double gain = info[node].gain;

                if (gain > maxGain)
                {
                    maxGain = gain;
                    maxNode = node;
                }
            }

            if (maxGain >= 0 && maxNode != null)
            {
                int[] o = outputs.Get(info[maxNode].subset.ToArray());

                // prune the maximum gain node
                int common = Measures.Mode(o);

                maxNode.Branches = null;
                maxNode.Output   = common;
            }

            return(computeError());
        }
        public void covariance_new_interface()
        {
            double[]   mean = Measures.Mean(data, dimension: 0);
            double[][] cov  = Measures.Covariance(data.ToJagged());

            var target = new PrincipalComponentAnalysis(PrincipalComponentMethod.CovarianceMatrix)
            {
                Means = mean
            };

            // Compute
            target.Learn(cov);

            // Transform
            double[,] actual = target.Transform(data);

            double[,] expected = new double[, ]
            {
                { 0.827970186, -0.175115307 },
                { -1.77758033, 0.142857227 },
                { 0.992197494, 0.384374989 },
                { 0.274210416, 0.130417207 },
                { 1.67580142, -0.209498461 },
                { 0.912949103, 0.175282444 },
                { -0.099109437, -0.349824698 },
                { -1.14457216, 0.046417258 },
                { -0.438046137, 0.017764629 },
                { -1.22382056, -0.162675287 },
            };

            // Verify both are equal with 0.01 tolerance value
            Assert.IsTrue(Matrix.IsEqual(actual, expected, 0.01));

            // Transform
            double[,] image = target.Transform(data);

            // Reverse
            double[,] reverse = target.Revert(image);

            // Verify both are equal with 0.01 tolerance value
            Assert.IsTrue(Matrix.IsEqual(reverse, data, 0.01));
        }
Example #8
0
        // See http://qusma.com/2013/01/22/doing-the-jaffray-woodriff-thing/
        public static decimal TRASYCODRAVOPFACOM(List <Trade> trades, TimeSpan backTestPeriod)
        {
            var tradeStatistics    = new TradeStatistics(trades);
            var equityChangePerDay = EquityChangePerDay(trades).Select((ec) => (double)ec.Value).ToArray();
            var equityCurve        = equityChangePerDay.Rollup(0d, (acc, val) => acc + val);
            var expectedCurve      = Enumerable.Repeat(tradeStatistics.AverageProfitLoss, equityCurve.Count()).Rollup(0m, (acc, val) => acc + val);

            var rSquared             = RSquared(trades);
            var dailyReturnsStdDev   = Measures.StandardDeviation(equityChangePerDay);
            var dailyReturnsSkewness = Measures.Skewness(equityChangePerDay);
            var cagr = CompoundAnnualGrowthRate(trades, backTestPeriod);

            var consistency     = (1m - 2m * (1m - rSquared));
            var drawdown        = (cagr / tradeStatistics.MaximumClosedTradeDrawdown) - 1;
            var returnAsymmetry = (decimal)Math.Min(1, dailyReturnsSkewness) / 10m;
            var volatility      = (cagr - 0.05m) / (decimal)(dailyReturnsStdDev * Math.Sqrt(252));
            var profitFactor    = ((tradeStatistics.ProfitLossRatio - 1m) / 2m);

            return(consistency + drawdown + returnAsymmetry + volatility + profitFactor);
        }
Example #9
0
        /// <summary>
        ///   Fits the underlying distribution to a given set of observations.
        /// </summary>
        ///
        /// <param name="observations">The array of observations to fit the model against. The array
        ///   elements can be either of type double (for univariate data) or
        ///   type double[] (for multivariate data).</param>
        /// <param name="weights">The weight vector containing the weight for each of the samples.</param>
        /// <param name="options">Optional arguments which may be used during fitting, such
        ///   as regularization constants and additional parameters.</param>
        ///
        /// <remarks>
        ///   Although both double[] and double[][] arrays are supported,
        ///   providing a double[] for a multivariate distribution or a
        ///   double[][] for a univariate distribution may have a negative
        ///   impact in performance.
        /// </remarks>
        ///
        public override void Fit(double[] observations, double[] weights, IFittingOptions options)
        {
            if (options != null)
            {
                throw new ArgumentException("No options may be specified.");
            }

            double mean;

            if (weights == null)
            {
                mean = Measures.Mean(observations);
            }
            else
            {
                mean = Measures.WeightedMean(observations, weights);
            }

            p = 1.0 / (1.0 - mean);
        }
        public virtual void MapToServerObject(Server.Application.MemberCaseCarePlanAssessment serverObject)
        {
            base.MapToServerObject((Server.Application.CoreObject)serverObject);


            serverObject.MemberCaseCarePlanId = MemberCaseCarePlanId;

            serverObject.AssessmentDate = AssessmentDate;

            serverObject.Measures = new Server.Application.MemberCaseCarePlanAssessmentCareMeasure[Measures.Count];

            foreach (MemberCaseCarePlanAssessmentCareMeasure currentAssessmentMeasure in Measures)
            {
                Server.Application.MemberCaseCarePlanAssessmentCareMeasure serverAssessmentMeasure = (Server.Application.MemberCaseCarePlanAssessmentCareMeasure)currentAssessmentMeasure.ToServerObject();

                serverObject.Measures[Measures.IndexOf(currentAssessmentMeasure)] = serverAssessmentMeasure;
            }

            return;
        }
        public ActionResult GetMeasuresByRange(string id, DateTime start_date, DateTime end_date)
        {
            try
            {
                var plant   = plantCollection.AsQueryable <PlantModel>().SingleOrDefault(x => x.Id == ObjectId.Parse(id));
                var measure = new Measures();
                //measure.Temp     = plant.Temperature.FindAll(d => DateTime.Parse(d.Date) >= start_date && DateTime.Parse(d.Date) <= end_date);
                measure.Light    = plant.Light.FindAll(d => DateTime.Parse(d.Date) >= start_date && DateTime.Parse(d.Date) <= end_date);
                measure.Humidity = plant.Humidity.FindAll(d => DateTime.Parse(d.Date) >= start_date && DateTime.Parse(d.Date) <= end_date);
                measure.Water    = plant.WaterAmount.FindAll(d => DateTime.Parse(d.Date) >= start_date && DateTime.Parse(d.Date) <= end_date);
                measure.Power    = plant.PowerConsumption.FindAll(d => DateTime.Parse(d.Date) >= start_date && DateTime.Parse(d.Date) <= end_date);

                return(Content(JsonConvert.SerializeObject(measure)));
            }

            catch (Exception e)
            {
                return(Content(JsonConvert.SerializeObject(e.Message)));
            }
        }
Example #12
0
        public static double[,] GetHalfBetweenClassScatter(double[,] input, int[] rowClasses, double[] totalMeans)
        {
            double[,] Hb = new double[input.GetLength(0), input.GetLength(1)];
            for (int i = 0; i < rowClasses.DistinctCount(); i++)
            {
                // Get the class subset
                double[,] subset = Subset(input, rowClasses, i);
                int count = subset.GetLength(0);

                // Get the class mean
                double[] classMean = Measures.Mean(subset, dimension: 0);
                double[] meanDif   = classMean.Subtract(totalMeans);

                for (int j = 0; j < input.GetLength(1); j++)
                {
                    Hb[i, j] = meanDif[j] * Math.Sqrt(count);
                }
            }
            return(Hb.Multiply(1.0 / Math.Sqrt(input.GetLength(0))));
        }
Example #13
0
            /// <summary>
            /// Adds a new indicator to the report.
            /// </summary>
            /// <param name="name">The name of the indicator for which the statistic is created.</param>
            /// <param name="statistics">The statistics instance for the indicator that contains the values.</param>
            /// <param name="measure">The measure(s) that should be reported.</param>
            /// <exception cref="ArgumentException">Thrown when <paramref name="name"/> is null or empty,
            /// or when <paramref name="measure"/> is not valid.</exception>
            /// <exception cref="ArgumentNullException">Thrown when <paramref name="statistics"/> is null.</exception>
            /// <returns>This builder instance.</returns>
            public Builder Add(string name, INumericMonitor statistics, Measures measure = Measures.All)
            {
                if (string.IsNullOrEmpty(name))
                {
                    throw new ArgumentException("Name must be a non-empty string", "name");
                }
                if (statistics == null)
                {
                    throw new ArgumentNullException("statistics");
                }
                if (measure == 0 || measure > Measures.All)
                {
                    throw new ArgumentException("No measures have been selected.", "measure");
                }

                instance.keys.Add(new Key {
                    Name = name, Statistics = statistics, Measure = measure, TotalMeasures = CountSetBits((int)measure)
                });
                return(this);
            }
Example #14
0
 public UnitRatio RatioFor(Guid unitId, Guid productId)
 {
     try
     {
         Unit unit = Measures.First(u => u.Id == unitId);
         if (unit.BaseUnit == null)
         {
             return(null);
         }
         if (unit.Ratio != null)
         {
             return(unit.Ratio);
         }
         else
         {
             return(ProductMeasures.First(m => m.ProductId == productId && m.UnitId == unitId).Ratio);
         }
     }
     catch (Exception) { return(null); }
 }
        public void FitTest2()
        {
            double[][] observations =
            {
                new double[] { 0.1000, -0.2000 },
                new double[] { 0.4000,  0.6000 },
                new double[] { 2.0000,  0.2000 },
                new double[] { 2.0000,  0.3000 }
            };

            double[]   mean = Measures.Mean(observations, dimension: 0);
            double[][] cov  = Measures.Covariance(observations, dimension: 0);

            var target = new MultivariateEmpiricalDistribution(observations);

            target.Fit(observations);

            Assert.IsTrue(Matrix.IsEqual(mean, target.Mean));
            Assert.IsTrue(Matrix.IsEqual(cov, target.Covariance, 1e-10));
        }
Example #16
0
        /// <summary>
        ///   Fits the underlying distribution to a given set of observations.
        /// </summary>
        ///
        /// <param name="observations">The array of observations to fit the model against. The array
        /// elements can be either of type double (for univariate data) or
        /// type double[] (for multivariate data).</param>
        /// <param name="weights">The weight vector containing the weight for each of the samples.</param>
        /// <param name="options">Optional arguments which may be used during fitting, such
        /// as regularization constants and additional parameters.</param>
        ///
        /// <remarks>
        ///   Although both double[] and double[][] arrays are supported,
        ///   providing a double[] for a multivariate distribution or a
        ///   double[][] for a univariate distribution may have a negative
        ///   impact in performance.
        /// </remarks>
        ///
        public override void Fit(double[] observations, int[] weights, IFittingOptions options)
        {
            double mean;
            double stdDev;

            if (weights != null)
            {
                mean   = Measures.WeightedMean(observations, weights);
                stdDev = Measures.WeightedStandardDeviation(observations, weights, mean);
            }
            else
            {
                mean   = Measures.Mean(observations);
                stdDev = Measures.StandardDeviation(observations, mean);
            }

            double u = mean + 0.45006 * stdDev;
            double b = (stdDev * Math.Sqrt(6)) / Math.PI;

            this.init(u, b);
        }
Example #17
0
        public GaussianProbabilityModel(double[,] dataset, double threshold)
        {
            this.m = dataset.GetLength(0);
            this.n = dataset.GetLength(1);

            if (m <= n)
            {
                throw new Exception("The number of examples must be greater than number of features");
            }

            this.mean      = Measures.Mean(dataset, 0);
            this.cov       = Measures.Covariance(dataset, this.mean);
            this.threshold = threshold;

            if (Matrix.Determinant(cov) == 0)
            {
                throw new Exception("Determinant of covariance matrix is 0. Try to add more example.");
            }

            this.probModel = new MultivariateNormalDistribution(this.mean, this.cov);
        }
        public void ProbabilityFunctionTest()
        {
            IDistribution target = CreateUnivariateDiscreteDistribution();

            double p = 0.42;
            double q = 1 - p;

            Assert.AreEqual(q, target.ProbabilityFunction(0));
            Assert.AreEqual(p, target.ProbabilityFunction(1));


            double[] observations = { 0, 1, 0, 0, 1, 0 };

            target.Fit(observations);

            p = Measures.Mean(observations);
            q = 1 - p;

            Assert.AreEqual(q, target.ProbabilityFunction(0));
            Assert.AreEqual(p, target.ProbabilityFunction(1));
        }
        private string ReplicateMeasures()
        {
            Output.Clear();
            var inputMeasures = DbOracleContext.MEASURES;
            var outputMeasures = DbContext.Measures;

            Output.Append(ReplicateMeasuresString);
            foreach (var measure in inputMeasures)
            {
                var newMeasure = new Measures()
                {
                    Name = measure.NAME
                };

                outputMeasures.AddOrUpdate(m => m.Name, newMeasure);
            }

            DbContext.SaveChanges();
            Output.AppendLine(Done);
            return Output.ToString();
        }
Example #20
0
        public double CalcAFV(byte[] input)
        {
            try
            {
                double   output      = 0;
                double[] contrastArr = new double[input.Length - 2];

                for (int i = 2; i < input.Length - 2; i++)
                {
                    contrastArr[i] = (double)(Math.Abs(input[i] - input[i - 1]) + Math.Abs(input[i] - input[i + 1]) / input.Length);
                }

                output = Measures.Variance(contrastArr);
                return(output);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return(-999);
            }
        }
        public int?genCorrectedPosition(CommandSelections selection)
        {
            int init = (int)selection.Position;

            foreach (Measure Measure in Measures)
            {
                if (Measure.Position.Index == init)
                {
                    return(null);
                }
            }

            int first_pos = (from Measure measure in Measures select measure.Position.Index).Min();

            if (init > first_pos)
            {
                init -= (Measures.Count() - 1);
            }

            return(init);
        }
        public static void FirstDoesNotHaveHigherVariance(AggregateMetrics first, AggregateMetrics second)
        {
            double[] firstSamples  = first.Runs.Select(run => run.ElapsedNanos).ToArray();
            double[] secondSamples = second.Runs.Select(run => run.ElapsedNanos).ToArray();

            // Fisher's F-test (also known as Snedecor)
            var firstVariance  = Measures.Variance(firstSamples);
            var secondVariance = Measures.Variance(secondSamples);
            var fishersFTest   = new FTest(
                firstVariance,
                secondVariance,
                firstSamples.Length - 1,
                secondSamples.Length - 1,
                TwoSampleHypothesis.FirstValueIsGreaterThanSecond);

            Trace.WriteLine(
                "FTest Var(s1) > Var(s2):  " + fishersFTest.PValue +
                " - Significant: " + fishersFTest.Significant + " - Hyp: " + fishersFTest.Hypothesis);

            PerfAssertContext.AssertIsFalse(fishersFTest.Significant);
        }
Example #23
0
        /// <summary>
        ///   Fits the underlying distribution to a given set of observations.
        /// </summary>
        ///
        /// <param name="observations">The array of observations to fit the model against. The array
        ///   elements can be either of type double (for univariate data) or
        ///   type double[] (for multivariate data).</param>
        /// <param name="weights">The weight vector containing the weight for each of the samples.</param>
        /// <param name="options">Optional arguments which may be used during fitting, such
        /// as regularization constants and additional parameters.</param>
        ///
        /// <remarks>
        ///   Although both double[] and double[][] arrays are supported,
        ///   providing a double[] for a multivariate distribution or a
        ///   double[][] for a univariate distribution may have a negative
        ///   impact in performance.
        /// </remarks>
        ///
        /// <example>
        ///   Please see <see cref="ExponentialDistribution"/>.
        /// </example>
        ///
        public override void Fit(double[] observations, double[] weights, IFittingOptions options)
        {
            if (options != null)
            {
                throw new ArgumentException("This method does not accept fitting options.");
            }


            double lambda;

            if (weights == null)
            {
                lambda = 1.0 / Measures.Mean(observations);
            }
            else
            {
                lambda = 1.0 / Measures.WeightedMean(observations, weights);
            }

            init(lambda);
        }
Example #24
0
        public void FitTest2()
        {
            double[] coefficients = { 0.50, 0.50 };

            NormalDistribution[] components = new NormalDistribution[2];
            components[0] = new NormalDistribution(2, 1);
            components[1] = new NormalDistribution(5, 1);

            var target = new Mixture <NormalDistribution>(coefficients, components);

            double[] values  = { 12512, 1, 1, 0, 1, 6, 6, 5, 7, 5 };
            double[] weights = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
            weights = weights.Divide(weights.Sum());
            double[] part1 = values.Submatrix(1, 4);
            double[] part2 = values.Submatrix(5, 9);

            MixtureOptions opt = new MixtureOptions()
            {
                Threshold = 0.000001
            };

            target.Fit(values, weights, opt);

            var mean1 = Measures.Mean(part1);
            var var1  = Measures.Variance(part1);

            Assert.AreEqual(mean1, target.Components[0].Mean, 1e-5);
            Assert.AreEqual(var1, target.Components[0].Variance, 1e-5);

            var mean2 = Measures.Mean(part2);
            var var2  = Measures.Variance(part2);

            Assert.AreEqual(mean2, target.Components[1].Mean, 1e-5);
            Assert.AreEqual(var2, target.Components[1].Variance, 1e-5);

            var expectedMean = Measures.WeightedMean(values, weights);
            var actualMean   = target.Mean;

            Assert.AreEqual(expectedMean, actualMean, 1e-5);
        }
Example #25
0
        /// <summary>
        ///   Computes the optimum number of bins based on a <see cref="BinAdjustmentRule"/>.
        /// </summary>
        ///
        public static int NumberOfBins(double[] values, DoubleRange range, BinAdjustmentRule rule)
        {
            switch (rule)
            {
            case BinAdjustmentRule.None:
                return(0);

            case BinAdjustmentRule.Scott:
                double h = (3.49 * Measures.StandardDeviation(values))
                           / System.Math.Pow(values.Length, 1.0 / 3.0);
                return((int)Math.Ceiling(range.Length / h));

            case BinAdjustmentRule.Sturges:
                return((int)Math.Ceiling(Math.Log(values.Length, 2)));

            case BinAdjustmentRule.SquareRoot:
                return((int)Math.Floor(Math.Sqrt(values.Length)));

            default:
                goto case BinAdjustmentRule.SquareRoot;
            }
        }
        public void FitTest2()
        {
            IDistribution target = CreateMultivariateContinuousDistribution();

            double[][] observations =
            {
                new double[] { 1, 2 },
                new double[] { 3, 2 },
                new double[] { 2, 3 },
                new double[] { 1, 2 },
            };

            target.Fit(observations);

            double[]   expectedMean = Measures.Mean(observations, dimension: 0);
            double[][] expectedCov  = Measures.Covariance(observations, expectedMean);

            MultivariateContinuousDistribution actual = target as MultivariateContinuousDistribution;

            Assert.IsTrue(expectedMean.IsEqual(actual.Mean));
            Assert.IsTrue(expectedCov.IsEqual(actual.Covariance));
        }
Example #27
0
        public void QuartileTest4()
        {
            // This is equivalent to R's type 6. This is the
            // same algorithm used by Minitab and SPSS. It is
            // not the same used by R and S.

            double[] values =
            {
                -0.309882133,       -0.640157313179586, 0.00470721699999999,
                -0.709738241179586,        0.328021416,   -1.95662033217959,
                0.618215405,               0.113038781,         0.311043694,-0.0662271140000001,
                -0.314138172179586,                  0,        -0.220574326, 0.078498723, 0.287448082
            };

            double q1, q3, actual;

            actual = Measures.Quartiles(values, out q1, out q3, false);

            Assert.AreEqual(-0.31413817217958601, q1);
            Assert.AreEqual(0, actual);
            Assert.AreEqual(0.28744808199999999, q3);
        }
Example #28
0
        public void ModeTest_NonComparable()
        {
            object a = new object();
            object b = new object();
            object c = new object();

            object[] values;
            object   actual;

            values = new[] { a, a, b, c };
            actual = Measures.Mode(values);
            Assert.AreEqual(a, actual);

            values = new[] { a, b, b, c };
            actual = Measures.Mode(values);
            Assert.AreEqual(b, actual);

            values = new[] { a, b, c, c };
            actual = Measures.Mode(values);
            Assert.AreEqual(c, actual);

            int count;

            values = new[] { a, b, c, a };
            actual = Measures.Mode(values, out count);
            Assert.AreEqual(a, actual);
            Assert.AreEqual(2, count);

            values = new[] { b, a, b, b, c };
            actual = Measures.Mode(values, out count);
            Assert.AreEqual(b, actual);
            Assert.AreEqual(3, count);

            values = new[] { c, c, a, b, c, c };
            actual = Measures.Mode(values, out count);
            Assert.AreEqual(c, actual);
            Assert.AreEqual(4, count);
        }
Example #29
0
        public void ModeTest_Comparable()
        {
            int a = 1;
            int b = 10;
            int c = 100;

            int[] values;
            int   actual;

            values = new[] { a, a, b, c };
            actual = Measures.Mode(values);
            Assert.AreEqual(a, actual);

            values = new[] { a, b, b, c };
            actual = Measures.Mode(values);
            Assert.AreEqual(b, actual);

            values = new[] { a, b, c, c };
            actual = Measures.Mode(values);
            Assert.AreEqual(c, actual);

            int count;

            values = new[] { a, b, c, a };
            actual = Measures.Mode(values, out count);
            Assert.AreEqual(a, actual);
            Assert.AreEqual(2, count);

            values = new[] { b, a, b, b, c };
            actual = Measures.Mode(values, out count);
            Assert.AreEqual(b, actual);
            Assert.AreEqual(3, count);

            values = new[] { c, c, a, b, c, c };
            actual = Measures.Mode(values, out count);
            Assert.AreEqual(c, actual);
            Assert.AreEqual(4, count);
        }
Example #30
0
        public void ModeTest()
        {
            int[] values = new int[] { 1, 2, 2, 3, 3, 3 };
            int   mode   = Measures.HistogramMode(values);

            Assert.AreEqual(3, mode);

            values = new int[] { 1, 1, 1, 2, 2, 2 };
            mode   = Measures.HistogramMode(values);
            Assert.AreEqual(3, mode);

            values = new int[] { 2, 2, 2, 1, 1, 1 };
            mode   = Measures.HistogramMode(values);
            Assert.AreEqual(0, mode);

            values = new int[] { 0, 0, 0, 0, 0, 0 };
            mode   = Measures.HistogramMode(values);
            Assert.AreEqual(0, mode);

            values = new int[] { 1, 1, 2, 3, 6, 8, 11, 12, 7, 3 };
            mode   = Measures.HistogramMode(values);
            Assert.AreEqual(7, mode);
        }
Example #31
0
        private Uri GetDataTypeMeasure(Measures measure)
        {
            switch (measure)
            {
            case Measures.g:
                return(new Uri("http://dbpedia.org/datatype/gram"));

            case Measures.mg:
                return(new Uri("http://dbpedia.org/datatype/milligram"));

            case Measures.kg:
                return(new Uri("http://dbpedia.org/datatype/kilogram"));

            case Measures.L:
                return(new Uri("http://dbpedia.org/datatype/litre"));

            case Measures.ml:
                return(new Uri("http://dbpedia.org/datatype/millilitre"));

            default:
                return(new Uri(string.Empty));
            }
        }
        public void EditMeasure(int id)
        {
            var item = Measures.FirstOrDefault(t => t.Id == id);

            if (item == null)
            {
                return;
            }

            var f = new MeasureEditForm(item)
            {
                Text = @"Редактировать упаковку"
            };

            if (f.ShowDialog() == DialogResult.OK)
            {
                DataManager.MeasureRepository.Update(item);
                DataManager.Save();

                FillListView();

                foreach (ListViewItem lv in Form.ListMeasures.Items)
                {
                    if (lv.Text == item.Name)
                    {
                        lv.Selected = true;
                        lv.Focused  = true;
                        lv.EnsureVisible();
                    }
                    else
                    {
                        lv.Selected = false;
                    }
                }
            }
        }
Example #33
0
        void EndPopulate(IAsyncResult res)
        {
            Exception ex;
            if (this.InvokeRequired)
            {
                AsyncCallback d = new AsyncCallback(EndPopulate);
                this.Invoke(d, new object[] { res });
            }
            else
            {
                AsyncResult result = (AsyncResult)res;
                DelegateWithOutAndRefParameters del = (DelegateWithOutAndRefParameters)result.AsyncDelegate;
                del.EndInvoke(out ex, res);

                if (_SearchSalesOrderDetailRes.Error != null)
                {
                    txtSimpleResult.Text = _SearchSalesOrderDetailRes.Error.GetXml();
                    return;
                }
                dataGridView2.DataSource = _SearchSalesOrderDetailRes.BusinessData.Times;

                _Sizes = new Measures();
                _Sizes.Add(new Measure("Result", GetSizeOfObject(_SearchSalesOrderDetailRes), false));
                _Sizes.Add(new Measure("Entity SalesOrderDetailList", GetSizeOfObject(_SearchSalesOrderDetailRes.BusinessData.SalesOrderDetailList), false));
                _Sizes.Add(new Measure("Test measures", GetSizeOfObject(_SearchSalesOrderDetailRes.BusinessData.Times), false));
                _Sizes.Add(new Measure("Result contextInformation", GetSizeOfObject(_SearchSalesOrderDetailRes.ContextInformation), false));

                dataGridView3.DataSource = _Sizes;

                string info = Fwk.HelperFunctions.SerializationFunctions.SerializeToXml(_SearchSalesOrderDetailRes.ContextInformation);
                txtSimpleResult.Text = string.Concat(info,Environment.NewLine,Environment.NewLine + "Bussiness data ",Environment.NewLine, _SearchSalesOrderDetailRes.BusinessData.SalesOrderDetailList.GetXml());

            }

        }