public static List<Point> OptimizeForIndexedChart(this IEnumerable<Point> points, Chart chart)
 {
     var isFirst = true;
     var result = new List<Point>();
     var ppp = chart.PerformanceConfiguration.PixelsPerPoint;
     double? x = null;
     var g = new List<Point>();
     foreach (var point in points)
     {
         var chartValue = chart.ToPlotArea(point.X,AxisTags.X);
         if (x == null) x = chartValue;
         if (chartValue - x < ppp)
         {
             g.Add(point);
             continue;
         }
         //ToDo: Think about this:
         //average seems the best "general" method, but maybe a developer
         //should be able to choose the method.
         var xx = g.Average(p => p.X);
         if (isFirst)
         {
             xx = g.First().X;
             isFirst = false;
         }
         result.Add(new Point(xx, g.Average(p => p.Y)));
         g = new List<Point> {point};
         x = chart.ToPlotArea(point.X, AxisTags.X);
     }
     result.Add(new Point(g.Last().X, g.Average(p => p.Y)));
     return result;
 }
Example #2
0
        public static void TestInPlaceFloatAddition(int testSetSize) {
            WriteLine();
            Write("Testing float array addition, generating test data...");
            var floatsOne = GetRandomFloatArray(testSetSize);
            var floatsTwo = GetRandomFloatArray(testSetSize);
            WriteLine(" done, testing...");
            
            var naiveTimesMs = new List<long>();
            var hwTimesMs = new List<long>();
            for (var i = 0; i < 3; i++) {
                var floatsOneCopy = new float[floatsOne.Length];

                floatsOne.CopyTo(floatsOneCopy, 0);
                stopwatch.Restart();
                FloatSimdProcessor.HwAcceleratedSumInPlace(floatsOneCopy, floatsTwo);
                var hwTimeMs = stopwatch.ElapsedMilliseconds;
                hwTimesMs.Add(hwTimeMs);
                WriteLine($"HW accelerated addition took: {hwTimeMs}ms (last value = {floatsOneCopy[floatsOneCopy.Length - 1]}).");

                floatsOne.CopyTo(floatsOneCopy, 0);
                stopwatch.Restart();
                FloatSimdProcessor.NaiveSumInPlace(floatsOneCopy, floatsTwo);
                var naiveTimeMs = stopwatch.ElapsedMilliseconds;
                naiveTimesMs.Add(naiveTimeMs);
                WriteLine($"Naive addition took:          {naiveTimeMs}ms (last value = {floatsOneCopy[floatsOneCopy.Length - 1]}).");
            }

            WriteLine("Testing float array addition");
            WriteLine($"Naive method average time:          {naiveTimesMs.Average():.##}");
            WriteLine($"HW accelerated method average time: {hwTimesMs.Average():.##}");
            WriteLine($"Hardware speedup:                   {naiveTimesMs.Average() / hwTimesMs.Average():P}%");
        }
Example #3
0
        public InputForm(string toDisplay, string title)
        {
            InitializeComponent();
            var displayLines = toDisplay.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            var widthList = new List<int>();
            using (var g = CreateGraphics())
            {
                widthList.AddRange(displayLines.Select(line => (int)g.MeasureString(line, MessageRichTextBox.Font).Width));
            }
            Width = 50;
            if(widthList.Count > 0)
                Width = ((int)widthList.Average() + 50 < 500) ? (int)widthList.Average() + 50 : 500;

            toDisplay = toDisplay.Replace(Environment.NewLine, @" \line "); //Flattening carriage returns from string input to rtf.

            var text = new StringBuilder();

            text.Append(@"{\rtf1\ansi ");
            text.Append(toDisplay);
            text.Append(@"}");
            MessageRichTextBox.Rtf = text.ToString();
            Text = title;
            using (var g = CreateGraphics())
            {
                Height = (int)g.MeasureString(MessageRichTextBox.Text,
                    MessageRichTextBox.Font, MessageRichTextBox.Width).Height + 80;
            }            
        }
        private double ComputeSyntheticMag(FilterResponse filterResponse, AbsFluxSpectra spectra, out double magError)
        {
            double targetSum = 0;
            double prevNonNaNVal = 0;

            foreach (int wavelength in filterResponse.Response.Keys)
            {
                double responseCoeff = filterResponse.Response[wavelength];

                double targetVal = InterpolateValue(spectra.ResolvedWavelengths, spectra.AbsoluteFluxes, wavelength);
                if (!double.IsNaN(targetVal)) prevNonNaNVal = targetVal;

                targetSum += prevNonNaNVal * responseCoeff;
            }

            var allMags = new List<double>();
            foreach (double conv in m_SynthetizedReferneceFluxMagnitudes.Keys)
            {
                double mag = m_SynthetizedReferneceFluxMagnitudes[conv] + 2.5 * Math.Log10(conv / targetSum);
                allMags.Add(mag);
            }

            // First itteration
            double averageMag = allMags.Average();
            double threeSigma = 3 * Math.Sqrt(allMags.Select(x => (averageMag - x) * (averageMag - x)).Sum()) / (allMags.Count - 1);
            allMags = allMags.Where(x => (Math.Abs(x - averageMag) <= threeSigma)).ToList();

            // Second itteration after removing outliers
            averageMag = allMags.Average();
            magError = m_AverageAbsFluxFitMagError + Math.Sqrt(allMags.Select(x => (averageMag - x) * (averageMag - x)).Sum()) / (allMags.Count - 1);
            return averageMag;
        }
Example #5
0
        public static void TestIntArrayAdditionFunctions(int testSetSize) {
            WriteLine();
            Write("Testing int array addition, generating test data...");
            var intsOne = GetRandomIntArray(testSetSize);
            var intsTwo = GetRandomIntArray(testSetSize);
            WriteLine($" done, testing...");

            var naiveTimesMs = new List<long>();
            var hwTimesMs = new List<long>();
            for (var i = 0; i < 3; i++) {
                stopwatch.Restart();
                var result = IntSimdProcessor.NaiveSumFunc(intsOne, intsTwo);
                var naiveTimeMs = stopwatch.ElapsedMilliseconds;
                naiveTimesMs.Add(naiveTimeMs);
                WriteLine($"Naive analysis took:                {naiveTimeMs}ms (last value = {result.Last()}).");

                stopwatch.Restart();
                result = IntSimdProcessor.HWAcceleratedSumFunc(intsOne, intsTwo);
                var hwTimeMs = stopwatch.ElapsedMilliseconds;
                hwTimesMs.Add(hwTimeMs);
                WriteLine($"Hareware accelerated analysis took: {hwTimeMs}ms (last value = {result.Last()}).");
            }

            WriteLine("Int array addition:");
            WriteLine($"Naive method average time:          {naiveTimesMs.Average():.##}");
            WriteLine($"HW accelerated method average time: {hwTimesMs.Average():.##}");
            WriteLine($"Hardware speedup:                   {naiveTimesMs.Average() / hwTimesMs.Average():P}%");
        }
Example #6
0
 private static TestResult GetAverage(List<TestResult> insertResult)
 {
     return new TestResult
     {
         AfectedRecord = (int)insertResult.Average(result => result.AfectedRecord),
         Label = insertResult.First().Label,
         TimeInMilisecond = (int)insertResult.Average(result => result.TimeInMilisecond)
     };
 }
Example #7
0
 public static void Main(string[] args)
 {
     Console.WriteLine("TokenizerTest: START");
     Console.WriteLine("TokenizerTest: RawTokenTest: START");
     var testString = "\"This is a string\" null false true \"another string\" { } [ ] ,";
     var times = new List<double>();
     for(int i = 0; i < 5; i++)
     {
         times.Clear();
         for (int j = 0;  j < 1000; j++)
         {
             using(var stream = new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(testString))))
             {
                 var lexerUnderTest = new JsonLexer(stream);
                 var time = Time(() => {
                     Token token = null;
                     do
                     {
                         token = lexerUnderTest.GetNextToken();
                     } while(token.Type != TokenTypes.EOF);
                 });
                 times.Add(time.TotalMilliseconds);
             }
         }
         Console.WriteLine($"TokenizerTest: {times.Average()}");
     }
     Console.WriteLine("TokenizerTest: RawTokenTest: STOP");
     Console.WriteLine("TokenizerTest: STOP");
     Console.WriteLine("ParserTest: START");
     Console.WriteLine("ParserTest: ProjectParse START");
     for(int i = 0; i < 5; i++)
     {
         times.Clear();
         for (int j = 0;  j < 1000; j++)
         {
             var time = Time(RunProjectParse);
             times.Add(time.TotalMilliseconds);
         }
         Console.WriteLine($"ParserTest: ProjectParse: {times.Average()}");
     }
     Console.WriteLine("ParserTest: ExistingParser START");
     for(int i = 0; i < 5; i++)
     {
         times.Clear();
         for (int j = 0;  j < 1000; j++)
         {
             var time = Time(RunExistingProjectParse);
             times.Add(time.TotalMilliseconds);
         }
         Console.WriteLine($"ParserTest: ProjectParse: {times.Average()}");
     }
     Console.WriteLine("ParseTest: ExistingParser STOP");
     Console.WriteLine("ParserTest: ProjectParse STOP");
 }
        public static void CalculateDistancesToCenter(List<CornerFeature> features)
        {
            var centerX = features.Average(feature => feature.CornerPoint.X);
            var centerY = features.Average(feature => feature.CornerPoint.Y);

            foreach (var feature in features)
            {
                var distance = Math.Sqrt(Math.Pow(feature.CornerPoint.X - centerX, 2) + Math.Pow(feature.CornerPoint.Y - centerY, 2));
                feature.FeatureVector[6] = distance;
            }
        }
		private void setHandleToAverage(List<Vector3> vector_list, Pipe.HandleSelected handleCallback){
			if(vector_list.Count > 0 && handleCallback != null){
				//not Average but the min and max's halfway point
				Vector3 average_vector = new Vector3 (
					vector_list.Average(x=>x.x),
					vector_list.Average(x=>x.y),
					vector_list.Average(x=>x.z)
				);

				setHandlePosition (average_vector, handleCallback);
			}
		}
Example #10
0
        public void AveragesWeatherResults()
        {
            WeatherApiResult celciusResult = TestData.GetTestWeatherResult(TemperatureUnit.DegreeCelsius, SpeedUnit.MilePerHour);
            WeatherApiResult otherCelciusResult = TestData.GetTestWeatherResult(TemperatureUnit.DegreeCelsius, SpeedUnit.MilePerHour);
            var weatherResults = new List<WeatherApiResult>() { celciusResult, otherCelciusResult };

            var averaged = weatherResults.AverageWeatherResults(TemperatureUnit.DegreeCelsius, SpeedUnit.MilePerHour);

            averaged.TemperatureUnit.Should().Be(TemperatureUnit.DegreeCelsius);
            averaged.WindSpeedUnit.Should().Be(SpeedUnit.MilePerHour);
            averaged.Temperature.Should().Be(weatherResults.Average(o => o.Temperature));
            averaged.Temperature.Should().Be(weatherResults.Average(o => o.Temperature));
        }
Example #11
0
        internal BitmapWrapper(Bitmap data)
        {
            img=data;
            IntegralImage iimg = IntegralImage.FromImage(data);
            List= FastHessian.getIpoints(0.0002f, 5, 2, iimg);
            SurfDescriptor.DecribeInterestPoints(List, false, false, iimg);
            List<Color> cdata = new List<Color>();

            int w = data.Width;
            int h = data.Height;
            //for (var i = 0; i < h; i++)
            //    for (var j = 0; j < w; j++) {
            //        var c=data.GetPixel(j, i);
            //        if (!(_pcolorlist.Any(color => color.Near(c, 64))))
            //            cdata.Add(c);
            //        else
            //            data.SetPixel(j, i, Color.Black);
            //    }

            var image=img;
            BitmapData dataIn = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
            unsafe {
                byte* pIn = (byte*)(dataIn.Scan0.ToPointer());
                for (int y = 0; y < dataIn.Height; y++) {
                    for (int x = 0; x < dataIn.Width; x++) {
                        int cb = (byte)(pIn[0]);
                        int cg = (byte)(pIn[1]);
                        int cr = (byte)(pIn[2]);
                        Color c = Color.FromArgb(cr, cg, cb);
                        if (!(_pcolorlist.Any(color => color.Near(c, 64))))
                            cdata.Add(c);
                        else
                            *pIn = *(pIn + 1) = *(pIn + 2) = 0;

                        pIn += 3;
                    }
                    pIn += dataIn.Stride - dataIn.Width * 3;
                }
            }
            image.UnlockBits(dataIn);

            if (cdata.Any() && cdata.Count>100)
                AvgColor = Color.FromArgb((int)cdata.Average(p => p.R), (int)cdata.Average(p => p.G),
                                   (int)cdata.Average(p => p.B));
            else
                AvgColor = Color.Black;

            Factor = 1.0*cdata.Count()/h/w;
        }
        /// <summary> Compresses a bitmap using TrigradCompression. </summary>
        /// <param name="bitmap"> The input bitmap.</param>
        /// <param name="options"> TrigradOptions specifying how the image will be compressed.</param>
        public static TrigradCompressed CompressBitmap(Bitmap bitmap, TrigradOptions options)
        {
            TrigradCompressed compressed = new TrigradCompressed { Height = bitmap.Height, Width = bitmap.Width };
            List<Point> samplePoints = new List<Point>();

            samplePoints.Add(new Point(0, 0));
            samplePoints.Add(new Point(bitmap.Width - 1, 0));
            samplePoints.Add(new Point(0, bitmap.Height - 1));
            samplePoints.Add(new Point(bitmap.Width - 1, bitmap.Height - 1));

            double baseChance = 1d / ((double)(bitmap.Width * bitmap.Height) / options.SampleCount / 8);

            for (int x = 0; x < bitmap.Width; x++)
            {
                for (int y = 0; y < bitmap.Height; y++)
                {
                    double chance = ((options.FrequencyTable != null) ? options.FrequencyTable.Table[x, y] : 1d) * baseChance;

                    if (options.Random.NextDouble() < chance)
                    {
                        samplePoints.Add(new Point(x, y));
                    }
                }
            }

            foreach (var sample in samplePoints)
            {
                List<Color> averageColors = new List<Color>();

                for (int x = sample.X - options.SampleRadius; x < sample.X + options.SampleRadius + 1; x++)
                {
                    for (int y = sample.Y - options.SampleRadius; y < sample.Y + options.SampleRadius + 1; y++)
                    {
                        if (y >= 0 && y < bitmap.Height && x >= 0 && x < bitmap.Width)
                        {
                            averageColors.Add(bitmap.GetPixel(x, y));
                        }
                    }
                }

                byte R = (byte)averageColors.Average(c => c.R);
                byte G = (byte)averageColors.Average(c => c.G);
                byte B = (byte)averageColors.Average(c => c.B);
                compressed.SampleTable[sample] = Color.FromArgb(R, G, B);
            }

            return compressed;
        }
//========================================================================= Classification Functions ==========================================================================================================

        public Dictionary<GestureKey, Dictionary<GestureKey, List<float>>> classify()
        {
            Dictionary<GestureKey, Dictionary<GestureKey, List<float>>> session_dtwResults = new Dictionary<GestureKey, Dictionary<GestureKey, List<float>>>(session.Count);

            foreach (KeyValuePair<GestureKey, List<List<float>>> session_kvp in session)
            {
                Dictionary<GestureKey, List<float>> dtwResults = new Dictionary<GestureKey, List<float>>(library.Count);
                foreach (KeyValuePair<GestureKey, List<List<float>>> library_kvp in library)
                {
                    List<float> values = new List<float>();
                    for (int jointIndex = 2; jointIndex < 62; jointIndex += vectCount)
                    {
                        var sessionJoint = session_kvp.Value.GetRange(jointIndex, vectCount);
                        var libraryJoint = library_kvp.Value.GetRange(jointIndex, vectCount);
                        float d = dtw(sessionJoint, libraryJoint);
                        values.Add(d);
                    }
                    float average = values.Average();
                    values.Add(average);
                    dtwResults.Add(library_kvp.Key, values);
                }
                session_dtwResults.Add(session_kvp.Key, dtwResults);
            }
            return session_dtwResults;
        }
        /// <summary> 
        /// 標準差(StandardDifference) 
        /// </summary> 
        /// <param name="list">歷史報酬率</param> 
        /// <returns>標準差</returns> 
        public List<double> GetSD(List<Double> list)
        {
          
            double AVG = list.Average();
            double sigma = 0,sum = 0;
            for (int i = 0; i < list.Count; i++)
            {
                sum += Math.Pow(list[i] - AVG, 2);                
            }

            sigma = Math.Sqrt( sum / list.Count);
           
            //Romove Errors
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i] < AVG - 2 * sigma || list[i] > AVG + 2 * sigma) //xbar - 3*sigma < list[i] < xbar + 3*sigma  ( 65_95_99.7)
                // list[i]= AVG;
                {
                    list.RemoveAt(i);                  
                    i--;
                }
            }         
          
            return list;
        }
Example #15
0
        private void ofdJSON_FileOk(object sender, CancelEventArgs e)
        {
            lblMessage.ForeColor = Color.Black;
            lblMessage.Text = @"JSON Loaded!";
            txtFileName.Text = ofdJSON.FileName;

            try
            {
                _reports = JsonConvert.DeserializeObject<List<Report>>(File.ReadAllText(txtFileName.Text));

                var firstOrDefault = _reports.FirstOrDefault();
                if (firstOrDefault != null)
                {
                    ReportsContext.IncidentLocation = firstOrDefault.reportPosition;
                }
                ReportsContext.AverageDistanceToP0 = (int) _reports.Average(x => x.DistanceToP0);

                foreach (var r in _reports)
                {
                    ReportsContext.reportIds.Add(r.reportIdentifier, "R" + (ReportsContext.reportIds.Count + 1));
                }

                btnS1.Enabled = btnS2.Enabled = btnExport.Enabled = btnExportVis.Enabled = true;
            }
            catch
            {
                lblMessage.Text = @"There was an error loading your JSON file";
                lblMessage.ForeColor = Color.Red;
            }
        }
Example #16
0
    static void Main()
    {
        string input = Console.ReadLine();
            double[] numbers = input.Split().Select(double.Parse).ToArray();
            List<double> roundNum = new List<double>();
            List<double> zeroFractNum = new List<double>();
            for (int i = 0; i < numbers.Length; i++)
            {
                if (numbers[i] % 1 != 0)
                {
                    zeroFractNum.Add(numbers[i]);
                }
                else
                {
                    roundNum.Add(numbers[i]);
                }
            }

            Console.WriteLine("Zero Fractional Numbers");
            zeroFractNum.ForEach(a => Console.WriteLine(a + " "));
            Console.WriteLine("max = {0}", zeroFractNum.Max());
            Console.WriteLine("min = {0}", zeroFractNum.Min());
            Console.WriteLine("sum = {0}", zeroFractNum.Sum());
            Console.WriteLine("avg = {0}", zeroFractNum.Average());
            Console.WriteLine("Round Numbers");
            roundNum.ForEach(a => Console.WriteLine(a + " "));
            Console.WriteLine("max = {0}", roundNum.Max());
            Console.WriteLine("sum = {0}", roundNum.Sum());
            Console.WriteLine("min = {0}", roundNum.Min());
            Console.WriteLine("avg = {0}", roundNum.Average());
    }
 static void Main(string[] args)
 {
     List<string> elements = Console.ReadLine().Split(' ').ToList();
     List<int>integers=new List<int>();
     List<double> decimals = new List<double>();
     foreach (var item in elements)
     {
         if((double.Parse(item)-Math.Ceiling(double.Parse(item)))==0)
             integers.Add(Convert.ToInt32(Math.Ceiling(double.Parse(item))));
         else
             decimals.Add(double.Parse(item));
     }
     Console.Write("[ ");
     integers.ForEach(i => Console.Write("{0} ", i));
     Console.Write("]");
     double min=integers.Min();
     double max=integers.Max();
     double sum=integers.Sum();
     double avg=integers.Average();
     Console.WriteLine(" -> min: {0}, max: {1}, sum: {2}, avg: {3:0.00}",min,max,sum,avg);
     Console.WriteLine();
     Console.Write("[ ");
     decimals.ForEach(j => Console.Write("{0} ", j));
     Console.Write("]");
     min = decimals.Min();
     max = decimals.Max();
     sum = decimals.Sum();
     avg = decimals.Average();
     Console.WriteLine(" -> min: {0}, max: {1}, sum: {2}, avg: {3:0.00}", min, max, sum, avg);
     Console.WriteLine();
 }
Example #18
0
        static void Main(string[] args)
        {
            string[] numbers = Console.ReadLine().Split(' ');
            List<double> floatingNumbers = new List<double>();
            List<int> integerNumbers = new List<int>();
            foreach(string number in numbers)
            {
                if (number.Contains("."))
                {
                    double number2 = double.Parse(number);

                    if (number2 % 1 == 0)
                    {
                        integerNumbers.Add(Convert.ToInt32(number2));
                    }
                    else
                    {
                        floatingNumbers.Add(number2);
                    }
                }
                else
                {
                    integerNumbers.Add(int.Parse(number));
                }
            }
            string output = string.Join(", ", floatingNumbers);
            Console.WriteLine("{0} -> min: {1:f2}, max: {2:f2}, sum: {3:f2}, avg: {4:f2}", output, floatingNumbers.Min(), floatingNumbers.Max(),
                floatingNumbers.Sum(), floatingNumbers.Average());
            output = string.Join(", ", integerNumbers);
            Console.WriteLine("{0} -> min: {1}, max: {2}, sum: {3}, avg: {4:f2}", output, integerNumbers.Min(), integerNumbers.Max(),
                integerNumbers.Sum(), integerNumbers.Average());
        }
Example #19
0
 public void Run(Action action)
 {
     const double count = 5;
     var times = new List<double>();
     var timer = new Stopwatch();
     var totalTime = new Stopwatch();
     double maxTime = 0;
     double minTime = double.MaxValue;
     Console.WriteLine("Ensuring code is Jitted");
     action();
     Console.WriteLine();
     Console.WriteLine("Time before run: {0}", DateTime.Now);
     Console.WriteLine("Running {0} times.", count);
     totalTime.Start();
     for (var i = 0; i < count; i++)
     {
         timer.Start();
         action();
         timer.Stop();
         maxTime = Math.Max(maxTime, timer.ElapsedMilliseconds);
         minTime = Math.Min(minTime, timer.ElapsedMilliseconds);
         times.Add(timer.ElapsedMilliseconds);
         timer.Reset();
     }
     totalTime.Stop();
     Console.WriteLine();
     Console.WriteLine("Time after run: {0}", DateTime.Now);
     Console.WriteLine("Elapsed: {0}ms", totalTime.ElapsedMilliseconds);
     Console.WriteLine("Diffs Per Second: {0}", (count / totalTime.ElapsedMilliseconds) * 1000);
     Console.WriteLine("Average: {0}ms", times.Average());
     Console.WriteLine("Max time for a call: {0}ms", maxTime);
     Console.WriteLine("Min time for a call: {0}ms", minTime);
 }
        public Statistics(IEnumerable<double> values)
        {
            list = values.ToList();
            N = list.Count;
            if (N == 0)
                throw new InvalidOperationException("StatSummary: Sequence contains no elements");
            list.Sort();

            if (N == 1)
                Q1 = Median = Q3 = list[0];
            else
            {
                Func<IList<double>, double> getMedian = x => x.Count % 2 == 0
                    ? (x[x.Count / 2 - 1] + x[x.Count / 2]) / 2
                    : x[x.Count / 2];
                Median = getMedian(list);
                Q1 = getMedian(list.Take(N / 2).ToList());
                Q3 = getMedian(list.Skip((N + 1) / 2).ToList());
            }

            Min = list.First();
            Mean = list.Average();
            Max = list.Last();

            InterquartileRange = Q3 - Q1;
            LowerFence = Q1 - 1.5 * InterquartileRange;
            UpperFence = Q3 + 1.5 * InterquartileRange;

            Outliers = list.Where(IsOutlier).ToArray();

            StandardDeviation = N == 1 ? 0 : Math.Sqrt(list.Sum(d => Math.Pow(d - Mean, 2)) / (N - 1));
            StandardError = StandardDeviation / Math.Sqrt(N);
            ConfidenceInterval = new ConfidenceInterval(Mean, StandardError);
            Percentiles = new PercentileValues(list);
        }
Example #21
0
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>();

            string number;

            for (int i = 0; i < int.MaxValue; i++)
            {
                Console.Write("Enter a number: ");
                number = Console.ReadLine();

                if (number != string.Empty)
                {
                    numbers.Add(int.Parse(number));
                }
                else
                {
                    break;
                }
            } Console.WriteLine();

            if (numbers.Count == 0)
            {
                Console.WriteLine("Your list is empty!");
                Console.WriteLine();
            }
            else
            {
                Console.WriteLine("The sum of all numbers in your sequence is: " + numbers.Sum());
                Console.WriteLine("The average value in your sequence is: " + numbers.Average());
                Console.WriteLine();
            }
        }
Example #22
0
        static void Main(string[] args)
        {
            int times;
            int diceFace;

            Console.WriteLine("How many times do you throw dice? >");
            times = int.Parse(Console.ReadLine());
            
            Dice dice = new Dice();
            List<int> dicefaces = new List<int>();

            for (int i=0; i< times; i++)
            {
                diceFace = dice.Throw(); // 1-6
                dicefaces.Add(diceFace);
                
                    
            }
            Console.WriteLine("Dice is now thrown {0} times, Average is : {1}", times, dicefaces.Average());

            /*foreach (int d in dicefaces)
            {
                Console.WriteLine(d + ",");
            }*/

        }
Example #23
0
        public static List<TestResult> RunTests(int runID, Framework framework, ITestSignature testSignature)
        {
            List<TestResult> results = new List<TestResult>();

            TestResult result = new TestResult() { Run = runID, Framework = framework };
            List<long> playerByIDResults = new List<long>();
            for (int i = 1; i <= NumPlayers; i++)
            {
                playerByIDResults.Add(testSignature.GetPlayerByID(i));
            }
            result.PlayerByIDMilliseconds = Math.Round(playerByIDResults.Average(), 2);

            List<long> playersForTeamResults = new List<long>();
            for (int i = 1; i <= NumTeams; i++)
            {
                playersForTeamResults.Add(testSignature.GetPlayersForTeam(i));
            }
            result.PlayersForTeamMilliseconds = Math.Round(playersForTeamResults.Average(), 2);
            List<long> teamsForSportResults = new List<long>();
            for (int i = 1; i <= NumSports; i++)
            {
                teamsForSportResults.Add(testSignature.GetTeamsForSport(i));
            }
            result.TeamsForSportMilliseconds = Math.Round(teamsForSportResults.Average(), 2);
            results.Add(result);

            return results;
        }
Example #24
0
        public static void Main()
        {
            var listOfNumbers = new List<int>();

            var list = new List<Number>()
            {
                new Number(5),
                new Number(5),
                new Number(5)
            };

            while(true)
            {
                string symbol = Console.ReadLine();

                if (symbol == string.Empty)
                {
                    break;
                }
                listOfNumbers.Add(int.Parse(symbol));
            }

            Console.WriteLine ("Sum ={0}", listOfNumbers.Sum());
            Console.WriteLine ("Average ={0:F2}", listOfNumbers.Average());
            Console.WriteLine(list.Sum(x=>x.Value));
        }
        public static TreeReport GetReport(FixedSizeTree fst, bool includeDetails)
        {
            List <double> pageDensities = null;

            if (includeDetails)
            {
                pageDensities = GetPageDensities(fst);
            }

            var density = pageDensities?.Average() ?? -1;

            var treeReport = new TreeReport
            {
                Type                  = fst.Type ?? RootObjectType.FixedSizeTree,
                Name                  = fst.Name.ToString(),
                BranchPages           = -1,
                Depth                 = fst.Depth,
                NumberOfEntries       = fst.NumberOfEntries,
                LeafPages             = -1,
                OverflowPages         = 0,
                PageCount             = fst.PageCount,
                Density               = density,
                AllocatedSpaceInBytes = fst.PageCount * Constants.Storage.PageSize,
                UsedSpaceInBytes      = includeDetails ? (long)(fst.PageCount * Constants.Storage.PageSize * density) : -1,
                MultiValues           = null,
            };

            return(treeReport);
        }
        public static void Main()
        {
            /*
            Write a program that reads from the console a sequence of positive integer numbers.
            The sequence ends when empty line is entered.
            Calculate and print the sum and average of the elements of the sequence.
            Keep the sequence in List<int>.
            */

            var positiveNumbers = new List<int>();

            string input = string.Empty;
            while ((input = Console.ReadLine()) != string.Empty)
            {
                var currentNumbers = input.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToArray();

                foreach (var numberAsString in currentNumbers)
                {
                    var number = int.Parse(numberAsString);
                    positiveNumbers.Add(number);
                }
            }

            Console.WriteLine("Sum of the numbers is: {0}", positiveNumbers.Sum());
            Console.WriteLine("Average of the numbers is: {0}", positiveNumbers.Average());
        }
        static void Main()
        {
            Console.WriteLine("The text is:");
            StringBuilder newString = new StringBuilder();
            newString.Append("Lorem Ipsum е елементарен примерен текст, използван в печатарската и типографската индустрия. Lorem Ipsum е индустриален стандарт от около 1500 година, когато неизвестен печатар взема няколко печатарски букви и ги разбърква, за да напечата с тях книга с примерни шрифтове. Този начин не само е оцелял повече от 5 века, но е навлязъл и в публикуването на електронни издания като е запазен почти без промяна. Популяризиран е през 60те години на 20ти век със издаването на Letraset листи, съдържащи Lorem Ipsum пасажи, популярен е и в наши дни във софтуер за печатни издания като Aldus PageMaker, който включва различни версии на Lorem Ipsum.");
            Console.WriteLine(newString);
            newString = newString.Substring(6, 19);
            Console.WriteLine();
            Console.WriteLine("The substring is:");
            Console.WriteLine(newString);
            Console.WriteLine();
            Console.WriteLine(new string('*', 80));

            Console.WriteLine("The IEnumerable extancions test is: ");
            var arr = new List<double>() { 3.5, 4.2, 7.5, 9.2, 1 };

            Console.WriteLine("The sum is: ");
            Console.WriteLine(arr.Sum());

            Console.WriteLine("The product is: ");
            Console.WriteLine(arr.Product());

            Console.WriteLine("The minimum is: ");
            Console.WriteLine(arr.Min());

            Console.WriteLine("The maximum is: ");
            Console.WriteLine(arr.Max());

            Console.WriteLine("The average is: ");
            Console.WriteLine(arr.Average());
            Console.WriteLine();
            Console.WriteLine(new string('*', 80));
            Console.WriteLine("Students 3task: ");
            Students();
        }
        static void Main(string[] args)
        {
            string[] input = Console.ReadLine().Split();
            float[] array = Array.ConvertAll(input, float.Parse);
            List<float> roundNumbers = new List<float>();
            List<float> floatingPointNumbers = new List<float>();

            for (int i = 0; i < array.Length; i++)
            {
                if (array[i] % 1 == 0)
                {
                    roundNumbers.Add(array[i]);
                }
                else
                {
                    floatingPointNumbers.Add(array[i]);
                }
            }

            Console.WriteLine("[" + string.Join(" ,", floatingPointNumbers) + "]" + " -> min: {0}, max:{1}, sum:{2}, avg:{3}",
                floatingPointNumbers.Min(), floatingPointNumbers.Max(), floatingPointNumbers.Sum(), String.Format("{0:0.00}", floatingPointNumbers.Average()));

            Console.WriteLine("[" + string.Join(" ,", roundNumbers) + "]" + " -> min: {0}, max:{1}, sum:{2}, avg:{3}",
                roundNumbers.Min(), roundNumbers.Max(), roundNumbers.Sum(), String.Format("{0:0.00}", roundNumbers.Average()));
        }
Example #29
0
	private static void Main(string[] args)
	{
		using (var store = new DocumentStore
		{
			Url = "http://localhost:8080",
			DefaultDatabase = "dump"
		}.Initialize())
		{
			for (int k = 0; k < 5; k++)
			{
				var rand = new Random(9321);
				var longs = new List<long>();
				for (int i = 0; i < 100; i++)
				{
					var sp = Stopwatch.StartNew();
					var x = store.DatabaseCommands.Get("tracks/" + rand.Next(1, 999999));

					var q = store.DatabaseCommands.Query("Tracks/ByCommon", new IndexQuery
					{
						Query = "Query:" + x.DataAsJson.Value<string>("NormalizedTitle").Split().Last()
					}, new string[0]);

					longs.Add(sp.ElapsedMilliseconds);
				}

				Console.Write(longs.Average() + ", ");
			}
		}
	}
Example #30
0
        private static void Main()
        {
            List<Dog> dogs = new List<Dog>
            {
                new Dog("Cesar", 5, "Male"),
                new Dog("Sharo", 9, "Male")
            };

            List<Frog> frogs = new List<Frog>
            {
                new Frog("Maya Manolova", 4, "Female"),
                new Frog("Petar Chobanov", 2, "Male")
            };

            List<Cat> cats = new List<Cat>
            {
                new Tomcat("Misho", 3),
                new Kitten("Pisana", 5),
                new Kitten("Emma", 1)
            };

            double catsAverageAge = cats.Average(x => x.Age);
            double dogsAverageAge = dogs.Average(x => x.Age);
            double frogsAverageAge = frogs.Average(x => x.Age);
            Console.WriteLine("Average age of frogs is: {0:F2} years", frogsAverageAge);
            Console.WriteLine("Average age of cats is: {0:F2} years", catsAverageAge);
            Console.WriteLine("Average age of dogs is: {0:F2} years", dogsAverageAge);
            Console.WriteLine("Average age of all animals is: {0:F2} years", (frogsAverageAge + catsAverageAge + dogsAverageAge)/3);
        }
 static void Main()
 {
     Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
     float[] allNumbers = Console.ReadLine().Split(' ').Select(float.Parse).ToArray();
     List<float> fpNumbers = new List<float> { };
     List<int> integerNumbers = new List<int> { };
     for (int index = 0; index < allNumbers.Length; index++)
     {
         if (allNumbers[index].ToString().Contains('.'))
         {
             fpNumbers.Add(allNumbers[index]);
         }
         else
         {
             integerNumbers.Add((int)allNumbers[index]);
         }
     }
     Console.WriteLine("[{0}] -> min: {1}, max: {2}, sum: {3}, avg: {4:f2}"
         , string.Join(", ", fpNumbers)
         , fpNumbers.Min()
         , fpNumbers.Max()
         , fpNumbers.Sum()
         , fpNumbers.Average());
     Console.WriteLine("[{0}] -> min: {1}, max: {2}, sum: {3}, avg: {4:f2}"
         , string.Join(", ", integerNumbers)
         , integerNumbers.Min()
         , integerNumbers.Max()
         , integerNumbers.Sum()
         , integerNumbers.Average());
 }
Example #32
0
        public double averageOfSpecifiedValueType(string valueType, int start, int end)
        {
            List <DataBlock> listOfDataBlocksToAverage = DataBlocks?.Where(x => x.dataType == valueType && x.timeStamp >= start && x.timeStamp <= end).ToList();

            if (listOfDataBlocksToAverage.Count > 0)
            {
                return(listOfDataBlocksToAverage?.Average(x => x.dataValue) ?? 0);
            }
            else
            {
                return(0);
            }
        }
Example #33
0
        public virtual StatsEmployees CalculateStats()
        {
            int     countEmployees;
            decimal avgVacationDays;
            int     diffJobTitles;

            EmployeesController employeesController = new();
            List <Employee>?    allEmployees        = employeesController.GetAllEmployees()?.ToList();

            countEmployees  = allEmployees?.Count ?? 0;
            avgVacationDays = (decimal)(allEmployees?.Average(x => x.VacationDays) ?? 0);
            diffJobTitles   = allEmployees?.Select(x => x.JobTitle)?.Distinct()?.Count() ?? 0;

            return(new(countEmployees, avgVacationDays, diffJobTitles));
        }
Example #34
0
        public void Show()
        {
            string text = $"_barcode: '{_barcode}'{Environment.NewLine} ";

            if (_millisecondsList.Count > 0)
            {
                text +=
                    $"min: {_millisecondsList?.Min()}, {Environment.NewLine}" +
                    $"max: {_millisecondsList?.Max()}, {Environment.NewLine}" +
                    $"avg: {_millisecondsList?.Average()} " +
                    Environment.NewLine + $"{string.Join("," + Environment.NewLine, _millisecondsList)}";
            }
            MessageBox.Show(text);
            _lastPress        = null;
            _millisecondsList = new List <double>();
            _barcode          = "";
        }
        public static TreeReport GetReport(Tree tree, bool includeDetails)
        {
            List <double>         pageDensities = null;
            Dictionary <int, int> pageBalance   = null;

            if (includeDetails)
            {
                pageDensities = GetPageDensities(tree);
                pageBalance   = GatherBalanceDistribution(tree);
            }

            MultiValuesReport multiValues = null;
            StreamsReport     streams     = null;

            if (tree.State.Flags == TreeFlags.MultiValueTrees)
            {
                multiValues = CreateMultiValuesReport(tree);
            }
            else if (tree.State.Flags == (TreeFlags.FixedSizeTrees | TreeFlags.Streams))
            {
                streams = CreateStreamsReport(tree);
            }

            var density = pageDensities?.Average() ?? -1;

            var treeReport = new TreeReport
            {
                Type                  = RootObjectType.VariableSizeTree,
                Name                  = tree.Name.ToString(),
                BranchPages           = tree.State.BranchPages,
                Depth                 = tree.State.Depth,
                NumberOfEntries       = tree.State.NumberOfEntries,
                LeafPages             = tree.State.LeafPages,
                OverflowPages         = tree.State.OverflowPages,
                PageCount             = tree.State.PageCount,
                Density               = density,
                AllocatedSpaceInBytes = tree.State.PageCount * Constants.Storage.PageSize + (streams?.AllocatedSpaceInBytes ?? 0),
                UsedSpaceInBytes      = includeDetails ? (long)(tree.State.PageCount * Constants.Storage.PageSize * density) : -1,
                MultiValues           = multiValues,
                Streams               = streams,
                BalanceHistogram      = pageBalance,
            };

            return(treeReport);
        }
        }//end Stop()

        public UsageStatistics Get()
        {
            var result = new UsageStatistics();

            try
            {
                result.ElapsedMilliseconds = _stopwatch?.ElapsedMilliseconds ?? 0;
                result.AverageCPU          = _cpuMetrics?.Any() == true?_cpuMetrics?.Average() ?? 0 : 0;

                result.AverageRAM = _ramMetrics?.Any() == true?_ramMetrics?.Average() ?? 0 : 0;
            }
            catch (Exception e)
            {
                _genericLog.Error($"{_nameOfThis} - Exception while Getting Statistics: {e.Message}");
                _genericLog.Debug($"{_nameOfThis} - Exception while Getting Statistics: {e.StackTrace}");
                if (!ContinueOnError)
                {
                    throw;
                }
            }
            return(result);
        }//end Get()
        public static TreeReport GetReport(Tree tree, bool calculateExactSizes)
        {
            List <double> pageDensities = null;

            if (calculateExactSizes)
            {
                pageDensities = GetPageDensities(tree);
            }

            MultiValuesReport multiValues = null;

            if (tree.State.Flags == TreeFlags.MultiValueTrees)
            {
                multiValues = CreateMultiValuesReport(tree);
            }

            var density = pageDensities?.Average() ?? -1;

            var treeReport = new TreeReport
            {
                Type                  = RootObjectType.VariableSizeTree,
                Name                  = tree.Name.ToString(),
                BranchPages           = tree.State.BranchPages,
                Depth                 = tree.State.Depth,
                NumberOfEntries       = tree.State.NumberOfEntries,
                LeafPages             = tree.State.LeafPages,
                OverflowPages         = tree.State.OverflowPages,
                PageCount             = tree.State.PageCount,
                Density               = density,
                AllocatedSpaceInBytes = tree.State.PageCount * tree.Llt.PageSize,
                UsedSpaceInBytes      = calculateExactSizes ? (long)(tree.State.PageCount * tree.Llt.PageSize * density) : -1,
                MultiValues           = multiValues
            };

            return(treeReport);
        }
Example #38
0
        public static void Main(string[] args)
        {
            Stopwatch RunningTime = new Stopwatch();

            RunningTime.Start();
            // Cronómetro que llevará registro de las operaciones realizadas
            Stopwatch     sw                = new Stopwatch();
            string        FilePath          = "";
            List <string> OutputFileContent = new List <string>();

            Console.WriteLine("Ingrese el nombre del archivo en el cual desea revisar el resultado final de las operaciones.");
            FilePath = Console.ReadLine() + ".csv";
            OutputFileContent.Add("Grado de Arbol, Tiempo Promedio de Busqueda (ms), Tiempo Promedio de Eliminacion (ms)");

            TreeElementFactory ElementFactory = new TreeElementFactory();
            GUIDKeyFactory     KeyFactory     = new GUIDKeyFactory();
            List <BTree <TreeElement, GUIDKey> > BTreeList = new List <BTree <TreeElement, GUIDKey> >();

            for (int i = 3; i < 21; i++)
            {
                BTreeList.Add(new BTree <TreeElement, GUIDKey>(i, ($"ArbolB-{i}.btree"), ElementFactory, KeyFactory));
            }
            int cantidadErrores = 0;

            foreach (BTree <TreeElement, GUIDKey> BTree in BTreeList)
            {
                Stopwatch TiempoArbol = new Stopwatch();
                TiempoArbol.Restart();
                sw.Start();
                List <GUIDKey>       KeysList    = new List <GUIDKey>();
                LinkedList <GUIDKey> QueriesList = new LinkedList <GUIDKey>();

                List <TimeSpan> SearchTimes       = new List <TimeSpan>();
                double          SearchAverageTime = -1;

                List <TimeSpan> DeletionTimes       = new List <TimeSpan>();
                double          DeletionAverageTime = -1;

                sw.Reset();

                for (int i = 0; i < 1000000; i++)
                {
                    KeysList.Add(new GUIDKey());
                    BTree.Insert(KeysList[i], new TreeElement());
                    if (i % 10000 == 0)
                    {
                        QueriesList.AddLast(KeysList[i]);
                    }
                }

                foreach (GUIDKey Query in QueriesList)
                {
                    sw.Restart();
                    BTree.BTreeSearch(Query);
                    SearchTimes.Add(sw.Elapsed);
                }
                sw.Stop();
                SearchAverageTime = SearchTimes.Average(x => x.TotalMilliseconds);

                foreach (GUIDKey Query in QueriesList)
                {
                    sw.Restart();
                    try
                    {
                        BTree.Delete(Query);
                    }
                    catch
                    {
                        cantidadErrores++;
                    }
                    DeletionTimes.Add(sw.Elapsed);
                }
                sw.Stop();
                DeletionAverageTime = DeletionTimes.Average(x => x.TotalMilliseconds);
                OutputFileContent.Add($"{BTree.Degree},{SearchAverageTime},{DeletionAverageTime}");
                OutputFileContent.Add($"Finaliza Arbol de Grado {BTree.Degree}. Tiempo: {TiempoArbol.Elapsed.Hours} h, {TiempoArbol.Elapsed.Minutes} min, {TiempoArbol.Elapsed.Seconds} s, {TiempoArbol.Elapsed.Seconds} ms");
                Console.WriteLine($"Finaliza Arbol de Grado {BTree.Degree}. Tiempo: {TiempoArbol.Elapsed.Hours} h, {TiempoArbol.Elapsed.Minutes} min, {TiempoArbol.Elapsed.Seconds} s, {TiempoArbol.Elapsed.Seconds} ms");
            }
            OutputFileContent.Add($"Tiempo Total de Ejecución: {RunningTime.Elapsed.Hours} h, {RunningTime.Elapsed.Minutes} min, {RunningTime.Elapsed.Seconds} s, {RunningTime.Elapsed.Milliseconds} ms");
            OutputFileContent.Add($"Cantidad de Errores: {cantidadErrores}");
            File.WriteAllLines(FilePath, OutputFileContent);

            Console.ReadLine();
        }
Example #39
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine(base.ToString());
            sb.AppendLine($" Components ({components.Count}):");
            foreach (var item in components)
            {
                sb.AppendLine($"  {item}");
            }
            sb.AppendLine($" Peripherals ({peripherals.Count}); Average Overall Performance ({peripherals.Average(p=>p.OverallPerformance)}):");
            foreach (var item in peripherals)
            {
                sb.AppendLine($"  {item}");
            }
            return(sb.ToString().TrimEnd());
        }
Example #40
0
        /// <summary>
        /// Does training or prediction for a set number of sessions
        /// </summary>
        /// <param name="sessions">Number of session to train/predict for</param>
        /// <param name="learn">Lets the RLM know if we are training or predicting</param>
        /// <returns>The final output for the training or prediction</returns>
        private PlanogramOptResults Optimize(int sessions, bool learn = true, bool enablePlanogramDisplay = false)
        {
            var output = new PlanogramOptResultsSettings();

            // holds the unique SKUs that are already in the planogram. Ensures there are no duplicate SKUs
            var hashedSku = new HashSet <int>();
            var itemDict  = new Dictionary <int, int>();

            var    shelves          = new List <Shelf>();
            double totalMetricScore = 0;

            for (int i = 0; i < sessions; i++)
            {
                // reset for next session
                shelves.Clear();
                hashedSku.Clear();
                itemDict.Clear();
                ResetCurrentItemIndexes();
                totalMetricScore = 0;
                totalSessions++;
                DateTime startSession = DateTime.Now;

                // starts the session. we need to save the session ID as we will pass it to the cycle.Run later on
                long sessionId = network.SessionStart();

                int numSlotFlattened = 0;
                // iterates for how many number of shelves our planogram has
                for (int shelf = 1; shelf <= simSettings.NumShelves; shelf++)
                {
                    // this shelf instance will hold the items the RLM will output
                    var shelfInstance = new Shelf()
                    {
                        Number = shelf
                    };
                    int itemIndex;
                    int numFacings;

                    // iterates for how many number of slots on each shelf
                    // notice that the slot is incremented depending on how many number of facings was outputed by the RLM
                    for (int slot = 1; slot <= simSettings.NumSlots; slot += numFacings)
                    {
                        itemIndex  = -1;
                        numFacings = -1;
                        bool isValid = false;
                        numSlotFlattened++;
                        do
                        {
                            // create the inputs with their corresponding values
                            var inputs = new List <RlmIOWithValue>();
                            //inputs.Add(new RlmIOWithValue(network.Inputs.First(a => a.Name == "Shelf"), shelf.ToString()));
                            //inputs.Add(new RlmIOWithValue(network.Inputs.First(a => a.Name == "Slot"), slot.ToString()));
                            inputs.Add(new RlmIOWithValue(network.Inputs.First(a => a.Name == "Slot"), numSlotFlattened.ToString()));

                            var rlmItemOutput = network.Outputs.FirstOrDefault();
                            var rlmIdeas      = new List <RlmIdea>()
                            {
                                new RlmOutputLimiter(rlmItemOutput.ID, currentItemIndexes.Count - 1, GetEquivalentIndex)
                            };

                            // runs a cycle with the sessionId passed in
                            var cycle     = new RlmCycle();
                            var rlmOutput = cycle.RunCycle(network, sessionId, inputs, learn, ideas: rlmIdeas);

                            // get the outputs
                            // the RLM outputs the item index so we will get the actual reference to the Item later on and
                            // the second output is the number of facings that will show up on the plangram
                            itemIndex  = Convert.ToInt32(rlmOutput.CycleOutput.Outputs.First(a => a.Name == "Item").Value);
                            numFacings = 1;//Convert.ToInt32(rlmOutput.CycleOutput.Outputs.First(a => a.Name == "NumFacings").Value);

                            // we calculate how many remaining slots are there left to check for validity
                            // because there might not be enough slots for what the number of facings was outputed by the RLM
                            int  remainingSlots = simSettings.NumSlots - shelfInstance.Items.Count();
                            bool isWithinLimit  = CheckDuplicateItem(itemDict, itemIndex, numFacings);

                            // here we check if the item is not a duplicate and that we have enough slots to fit the number of facings
                            //if (hashedSku.Add(itemIndex) && remainingSlots >= numFacings)
                            if (isWithinLimit && remainingSlots >= numFacings)
                            {
                                isValid = true;
                                Item itemReference = items[itemIndex]; // we get the item reference using the index outputed by the RLM

                                // with the item reference we will also have the Attributes which we need to calculate for the metrics
                                double itemMetricScore = PlanogramOptimizer.GetCalculatedWeightedMetrics(itemReference, simSettings);

                                // we add the item's metric score to totalMetricScore(which is our Session score in this case)
                                // notice that we multplied it with the numFacings since that is how many will also show up on the planogram
                                totalMetricScore += (itemMetricScore * numFacings);

                                // add the items to the shelf container depending on how many facings
                                for (int n = 0; n < numFacings; n++)
                                {
                                    shelfInstance.Add(itemReference, itemMetricScore);
                                }

                                // A non-duplicate is good.
                                network.ScoreCycle(rlmOutput.CycleOutput.CycleID, 1);
                            }
                            else
                            {
                                // we give the cycle a zero (0) score as it was not able to satisfy our conditions (punish it)
                                isValid = false;
                                network.ScoreCycle(rlmOutput.CycleOutput.CycleID, -1);
                                //System.Diagnostics.Debug.WriteLine("try again");
                            }
                        } while (!isValid); // if invalid, we redo the whole thing until the RLM is able to output an item that is unique and fits the remaining slot in the planogram
                    }

                    shelves.Add(shelfInstance);
                }

                // ends the session with the summed metric score for all items in the planogram
                network.SessionEnd(totalMetricScore);
                //System.Diagnostics.Debug.WriteLine($"Session #{i}, Score: {totalMetricScore}");

                // set statistics and the optimized planogram shelves (and items inside them)
                output.Shelves = shelves;
                metricScoreHistory.Add(totalMetricScore);
                metricAvgLastTen.Enqueue(totalMetricScore);
                if (metricAvgLastTen.Count > 10)
                {
                    metricAvgLastTen.Dequeue();
                }
                output.Score      = totalMetricScore;
                output.AvgScore   = metricScoreHistory.Average();
                output.AvgLastTen = metricAvgLastTen.Average();
                output.MinScore   = metricScoreHistory.Min();
                output.MaxScore   = metricScoreHistory.Max();
                var timeRemaining = simSettings.EndsOn.Value - DateTime.Now;
                output.TimeElapsed            = timeRemaining.TotalSeconds < 0 ? TimeSpan.Zero : timeRemaining; //DateTime.Now - simSettings.StartedOn;
                output.CurrentSession         = totalSessions;
                output.MaxItems               = MAX_ITEMS;
                output.StartRandomness        = network.StartRandomness;
                output.EndRandomness          = network.EndRandomness;
                output.SessionsPerBatch       = DEFAULT_SESSIONS_PER_BATCH;
                output.InputType              = inputType.ToString();
                output.CurrentRandomnessValue = network.RandomnessCurrentValue;

                if (logger != null)
                {
                    SimulationData logdata = new SimulationData();

                    logdata.Session = output.CurrentSession;
                    logdata.Score   = output.Score;
                    logdata.Elapse  = DateTime.Now - startSession;

                    logger.Add(logdata);
                }

                // update the numScoreHits if the sim type is Score
                if (simSettings.SimType == SimulationType.Score)
                {
                    if (totalMetricScore >= simSettings.Score.Value)
                    {
                        numScoreHits++;
                        output.NumScoreHits = numScoreHits;
                    }
                    else
                    {
                        numScoreHits = 0;
                    }
                }

                //OnSessionDone?.Invoke(output);

                // updates the results to the UI
                //bool enableSimDisplay = (!learn) ? true : (learn && simSettings.EnableSimDisplay) ? true : false;
                if (enablePlanogramDisplay)
                {
                    output.MetricMin = simSettings.ItemMetricMin;
                    output.MetricMax = simSettings.ItemMetricMax;
                    output.CalculateItemColorIntensity();
                }
                UpdateUI?.Invoke(output, enablePlanogramDisplay);

                // checks if we have already by passed the time or score that was set
                // if we did, then we stop the training and end it abruptly
                if ((simSettings.SimType == SimulationType.Time && simSettings.EndsOn.Value <= DateTime.Now) ||
                    (simSettings.SimType == SimulationType.Score && numScoreHits >= SimulationSettings.NUM_SCORE_HITS))
                {
                    break;
                }

                //System.Diagnostics.Debug.WriteLine("Randomness: " + network.RandomnessCurrentValue);
            }

            return(output);
        }
        public bool WriteTXTFile(string fileName)
        {
            string outputText = "";

            outputText += FormatLine(PlaceHolderWidth * 6, new [] { "######Superbowl winners######" });

            outputText += FormatLine(PlaceHolderWidth, new string[] { "Team name", "year", "QB", "Coach", "MVP", "Point lead" });

            foreach (var superBowlEntry in Entries)
            {
                outputText += FormatLine(PlaceHolderWidth,
                                         new[]
                {
                    superBowlEntry.WinningTeam, superBowlEntry.Date.Year.ToString(), superBowlEntry.WinningQB, superBowlEntry.WinningCoach,
                    superBowlEntry.MVP, (superBowlEntry.WinningPoints - superBowlEntry.LosingPoints).ToString()
                });
            }

            outputText += "\r\n\r\n";

            outputText += FormatLine(PlaceHolderWidth * 6, new [] { "######Top five attended######" });


            outputText += FormatLine(PlaceHolderWidth, new string[] { "Year", "Winning team", "Losing team", "City", "State", "Stadium" });

            var sortedByAttendanceEntries = Entries.OrderByDescending(entry => entry.Attendance).Take(5);

            foreach (var entry in sortedByAttendanceEntries)
            {
                outputText += FormatLine(PlaceHolderWidth,
                                         new[]
                {
                    entry.Date.Year.ToString(), entry.WinningTeam, entry.LosingTeam, entry.City,
                    entry.State, entry.Stadium
                });
            }

            outputText += "\r\n\r\n";
            outputText += FormatLine(PlaceHolderWidth * 6, new[] { "######State that hosted the most Super Bowls######" });

            //var SuperBowlsSortedByMostInState =
            SuperBowlEntry hostedMost      = null;
            int            mostHostedCount = -1;

            foreach (var entry in Entries)
            {
                if (Entries.Where(e => e.State == entry.State).Count() > mostHostedCount)
                {
                    hostedMost = entry;
                }
            }

            outputText += FormatLine(PlaceHolderWidth,
                                     new[]
            {
                hostedMost.City,
                hostedMost.State, hostedMost.Stadium
            });

            outputText += "\r\n\r\n";
            outputText += FormatLine(PlaceHolderWidth * 6, new[] { "######MVP's more then once######" });

            var MVPMoreThenOnce = Entries.Where(e => Entries.Where(z => z.MVP == e.MVP).Count() > 1).ToList();

            foreach (var mvp in MVPMoreThenOnce)
            {
                outputText += FormatLine(PlaceHolderWidth,
                                         new[]
                {
                    mvp.MVP, mvp.WinningTeam, mvp.LosingTeam
                });
            }

            outputText += "\r\n\r\n";
            outputText += FormatLine(PlaceHolderWidth, new[] { "######Coach that lost the most######" });

            //var coachGroups = Entries.GroupBy(e => e.LosingCoach).OrderByDescending(e=>e.Count()).Take(1);

            var groupsOfLosingCoaches = from groups in
                                        from entry in Entries
                                        group entry by entry.LosingCoach
                                        orderby groups.Count() descending select groups;

            outputText += FormatLine(PlaceHolderWidth, new[] { groupsOfLosingCoaches.First().Key });


            outputText += "\r\n\r\n";
            outputText += FormatLine(PlaceHolderWidth, new[] { "######Coach that won the most######" });

            var groupsOfWinningCoaches = from groups in
                                         from entry in Entries
                                         group entry by entry.WinningCoach
                                         orderby groups.Count() descending
                                         select groups;

            outputText += FormatLine(PlaceHolderWidth, new[] { groupsOfWinningCoaches.First().Key });


            outputText += "\r\n\r\n";
            outputText += FormatLine(PlaceHolderWidth, new[] { "######Team that won the most######" });

            var groupsOfWinningTeams = from groups in
                                       from entry in Entries
                                       group entry by entry.WinningTeam
                                       orderby groups.Count() descending
                                       select groups;

            outputText += FormatLine(PlaceHolderWidth, new[] { groupsOfWinningTeams.First().Key });


            outputText += "\r\n\r\n";
            outputText += FormatLine(PlaceHolderWidth, new[] { "######Team that lost the most######" });

            var groupsOfLosingTeams = from groups in
                                      from entry in Entries
                                      group entry by entry.LosingTeam
                                      orderby groups.Count() descending
                                      select groups;

            outputText += FormatLine(PlaceHolderWidth, new[] { groupsOfLosingTeams.First().Key });

            outputText += "\r\n\r\n";
            outputText += FormatLine(PlaceHolderWidth, new[] { "######Largest point difference######" });

            var pointsDifference =
                from entry in Entries
                orderby entry.WinningPoints - entry.LosingPoints descending
                select entry;

            outputText += FormatLine(PlaceHolderWidth, new[] { (pointsDifference.First().WinningPoints - pointsDifference.First().LosingPoints).ToString() });


            outputText += "\r\n\r\n";
            outputText += FormatLine(PlaceHolderWidth, new[] { "######Average attendance of all Superbowls######" });

            var avg = Entries.Average(e => e.Attendance);

            outputText += FormatLine(PlaceHolderWidth, new[] { Math.Round(avg).ToString() });


            File.WriteAllText(fileName, outputText);
            return(false);
        }
Example #42
0
        public static void ComputeRiseFallTimes(float[] voltages, float minVoltage, float maxVoltage, double samplePeriod, float pct, Dictionary <int, bool> risingNFallingEdges, out double riseTime, out double fallTime)
        {
            riseTime = double.NaN;
            fallTime = double.NaN;
            List <double> riseTimes = new List <double>();
            List <double> fallTimes = new List <double>();

            float amp           = maxVoltage - minVoltage;
            float lowVBoundary  = minVoltage + amp * (1f - pct) / 2f;
            float highVBoundary = maxVoltage - amp * (1f - pct) / 2f;

            //copy for fast access -- ElementAt is terribly slow!!
            int[]  risingNFallingEdgesIndices = risingNFallingEdges.Keys.ToArray();
            bool[] risingNFallingEdgesBools   = risingNFallingEdges.Values.ToArray();

            for (int i = 1; i < risingNFallingEdges.Count - 1; i++)
            {
                bool risingEdge     = risingNFallingEdgesBools[i];
                int  prevCrossIndex = risingNFallingEdgesIndices[i - 1];
                int  currCrossIndex = risingNFallingEdgesIndices[i];
                int  nextCrossIndex = risingNFallingEdgesIndices[i + 1];

                if (risingEdge) //rising edge
                {
                    //walk backwards
                    int beginIndex = currCrossIndex;
                    while (beginIndex > prevCrossIndex && voltages[beginIndex] > lowVBoundary)
                    {
                        beginIndex--;
                    }

                    //walk forward
                    int endIndex = currCrossIndex;
                    while (endIndex < nextCrossIndex && voltages[endIndex] < highVBoundary)
                    {
                        endIndex++;
                    }

                    //only add in case both boundary voltages were reached
                    if (beginIndex > prevCrossIndex && endIndex < nextCrossIndex)
                    {
                        if (endIndex - beginIndex - 1 > 1)
                        {
                            riseTimes.Add((endIndex - beginIndex - 1) * samplePeriod);
                        }
                    }
                }
                else //falling edge
                {
                    //walk backwards
                    int beginIndex = currCrossIndex;
                    while (beginIndex > prevCrossIndex && voltages[beginIndex] < highVBoundary)
                    {
                        beginIndex--;
                    }

                    //walk forward
                    int endIndex = currCrossIndex;
                    while (endIndex < nextCrossIndex && voltages[endIndex] > lowVBoundary)
                    {
                        endIndex++;
                    }

                    //only add in case both boundary voltages were reached
                    if (beginIndex > prevCrossIndex && endIndex < nextCrossIndex)
                    {
                        if (endIndex - beginIndex - 1 > 1)
                        {
                            fallTimes.Add((endIndex - beginIndex - 1) * samplePeriod);
                        }
                    }
                }
            }

            if (riseTimes.Count == 0)
            {
                riseTime = double.NaN;
            }
            else
            {
                riseTime = riseTimes.Average();
            }

            if (fallTimes.Count == 0)
            {
                fallTime = double.NaN;
            }
            else
            {
                fallTime = fallTimes.Average();
            }
        }
Example #43
0
 /// <summary>
 /// Annualized return statistic calculated as an average of daily trading performance multiplied by the number of trading days per year.
 /// </summary>
 /// <param name="performance">Dictionary collection of double performance values</param>
 /// <param name="tradingDaysPerYear">Trading days per year for the assets in portfolio</param>
 /// <remarks>May be unaccurate for forex algorithms with more trading days in a year</remarks>
 /// <returns>Double annual performance percentage</returns>
 private static decimal GetAnnualPerformance(List <double> performance, int tradingDaysPerYear = 252)
 {
     return((decimal)performance.Average() * tradingDaysPerYear);
 }
Example #44
0
 public double CalculateAverageAge(List <Person> users)
 {
     return(users.Average(user => user.Age));
 }
Example #45
0
        public IQueryable <Auto> GetAverageSalePrice(List <Auto> getAuto)
        {
            string splitModel = null; IQueryable <Auto> queryGetAuto = null; int avgBid = 0;

            if (getAuto.Average(a => a.BidAmountC) != null)
            {
                avgBid = Convert.ToInt32(getAuto.Average(a => a.BidAmountC));
            }

            foreach (var item in getAuto)
            {
                var AutoModel = Convert.ToString(item.Model).Split();

                if (AutoModel.Count() < 3)
                {
                    splitModel = AutoModel[0] + ' ' + AutoModel[1];
                }
                else
                {
                    splitModel = AutoModel[0] + ' ' + AutoModel[1] + ' ' + AutoModel[2];
                }

                queryGetAuto = _context.Auto.Where(a => a.Year.Equals(item.Year) &&
                                                   a.Model.Contains(splitModel) &&
                                                   a.Cyl.Equals(item.Cyl) &&
                                                   a.Status.Equals(item.Status) &&
                                                   a.Vin != item.Vin &&
                                                   a.BidAmountC != null);
            }

            if (queryGetAuto.Average(a => a.BidAmountC) == null)
            {
                foreach (var item in getAuto)
                {
                    var AutoModel = Convert.ToString(item.Model).Split();

                    if (AutoModel.Count() < 3)
                    {
                        splitModel = AutoModel[0] + ' ' + AutoModel[1];
                    }
                    else
                    {
                        splitModel = AutoModel[0] + ' ' + AutoModel[1] + ' ' + AutoModel[2];
                    }

                    queryGetAuto = _context.Auto.Where(a => a.Year.Equals(item.Year) &&
                                                       a.Model.Contains(splitModel) &&
                                                       a.Status.Equals(item.Status) &&
                                                       a.Vin != item.Vin &&
                                                       a.BidAmountC != null);
                }
            }

            if (queryGetAuto.Average(a => a.BidAmountC) == null)
            {
                foreach (var item in getAuto)
                {
                    var AutoModel = Convert.ToString(item.Model).Split();

                    if (AutoModel.Count() < 3)
                    {
                        splitModel = AutoModel[0] + ' ' + AutoModel[1];
                    }
                    else
                    {
                        splitModel = AutoModel[0] + ' ' + AutoModel[1] + ' ' + AutoModel[2];
                    }

                    queryGetAuto = _context.Auto.Where(a => a.Year.Equals(item.Year) &&
                                                       a.Model.Contains(splitModel) &&
                                                       a.Vin != item.Vin &&
                                                       a.BidAmountC != null);
                }
            }

            if (queryGetAuto.Average(a => a.BidAmountC) == null)
            {
                foreach (var item in getAuto)
                {
                    var AutoModel = Convert.ToString(item.Model).Split();

                    if (AutoModel.Count() < 3)
                    {
                        splitModel = AutoModel[0] + ' ' + AutoModel[1];
                    }
                    else
                    {
                        splitModel = AutoModel[0] + ' ' + AutoModel[1] + ' ' + AutoModel[2];
                    }

                    queryGetAuto = _context.Auto.Where(a => a.Model.Contains(splitModel) &&
                                                       a.Status.Equals(item.Status) &&
                                                       a.Vin != item.Vin &&
                                                       a.BidAmountC != null);
                }
            }

            if (queryGetAuto.Average(a => a.BidAmountC) == null)
            {
                foreach (var item in getAuto)
                {
                    var AutoModel = Convert.ToString(item.Model).Split();

                    if (AutoModel.Count() < 3)
                    {
                        splitModel = AutoModel[0] + ' ' + AutoModel[1];
                    }
                    else
                    {
                        splitModel = AutoModel[0] + ' ' + AutoModel[1] + ' ' + AutoModel[2];
                    }

                    queryGetAuto = _context.Auto.Where(a => a.Model.Contains(splitModel) &&
                                                       a.Vin != item.Vin &&
                                                       a.BidAmountC != null);
                }
            }

            return(queryGetAuto);
        }
Example #46
0
 public float GetAverageFoodWeightPerAnimal()
 {
     return((float)_places.Average(place => place.GetAverageFoodWeightPerAnimal()));
 }
        //Firstly we will get product from products/index on add click we get product -> redirection to Cart View

        public ActionResult Add(int productId, decimal price, int quantity)
        {
            var product      = db.Products.GetAll().ToList().FirstOrDefault(x => x.ProductId == productId);
            var cart         = CreateOrGetCart();
            var existingItem = cart.OrderProducts.Where(x => x.ProductId == productId).Any();

            //If added product that exists
            if (existingItem)
            {
                //getting previous product -> creating new OrderPruct and add them to a temp list
                //So i can calculate quantities and prices
                //after using linq i replace current OrderProduct with the new one

                var previousProduct = cart.OrderProducts.Where(x => x.ProductId == productId).First();
                var currentProduct  = new OrderProduct()
                {
                    Order     = null,
                    Price     = price,
                    Quantity  = quantity,
                    ProductId = productId,
                    Product   = db.Products.GetById(productId)
                };

                var tempList = new List <OrderProduct>();
                tempList.Add(previousProduct);
                tempList.Add(currentProduct);

                var avgPrice        = tempList.Average(x => x.Price);
                var currentQuantity = tempList.Sum(x => x.Quantity);

                var query = cart.OrderProducts.Where(x => currentProduct.ProductId == previousProduct.ProductId)
                            .Select(g => new OrderProduct()
                {
                    Order     = null,
                    Price     = avgPrice,
                    Quantity  = currentQuantity,
                    ProductId = productId,
                    Product   = db.Products.GetById(productId),
                }).FirstOrDefault();

                tempList.Remove(previousProduct);
                cart.OrderProducts.Remove(previousProduct);
                cart.OrderProducts.Add(query);
            }
            else
            {
                cart.OrderProducts.Add(new OrderProduct()
                {
                    //We dont need to create an order -> we will create order at checkout proccess
                    Order     = null,
                    ProductId = productId,
                    Product   = db.Products.GetById(productId),
                    Price     = price,
                    Quantity  = quantity
                });
            }



            SaveCart(cart);

            return(RedirectToAction("Cart", "OrderProducts"));
        }
Example #48
0
        public string getKijijiData(string model, string year)
        {
            try
            {
                HtmlWeb web = new HtmlWeb();

                var modelSplit = model.Split();

                string weburl = null;

                if (modelSplit.Count() == 3 && (modelSplit[2].Length == 2 || modelSplit[2].Length == 3))
                {
                    weburl = "https://www.kijiji.ca/b-cars-vehicles/canada/" + year + "-" + modelSplit[0] + "-" + modelSplit[1] + "-" + modelSplit[2] + "/k0c27l0?ad=offering&price=1000__100000";
                }
                else
                {
                    weburl = "https://www.kijiji.ca/b-cars-vehicles/canada/" + year + "-" + modelSplit[0] + "-" + modelSplit[1] + "/k0c27l0?ad=offering&price=1000__100000";
                }

                HtmlDocument doc = web.Load(weburl.ToLower());

                var priceList = doc.DocumentNode.SelectNodes("//div[@class='price']").ToList();

                List <int> prices = new List <int>();

                string priceAvg;

                foreach (var price in priceList)
                {
                    int i;

                    if (int.TryParse(price.InnerText.Replace("$", "").Replace(",", "").Replace(".00", ""), out i))
                    {
                        int intPrice = Convert.ToInt32(price.InnerText.Replace("$", "").Replace(",", "").Replace(".00", ""));

                        prices.Add(intPrice);
                    }
                }

                priceAvg = Convert.ToString(Convert.ToInt32(prices.Average()));

                return(priceAvg);
            }
            catch (Exception)
            {
                try
                {
                    HtmlWeb web = new HtmlWeb();

                    var modelSplit = model.Split();

                    string weburl = null;

                    if (modelSplit.Count() == 3 && (modelSplit[2].Length == 2 || modelSplit[2].Length == 3))
                    {
                        weburl = "https://www.autotrader.ca/cars/" + modelSplit[0] + "/" + modelSplit[1] + "%20" + modelSplit[2] + "/" + year + "/?rcp=100&sts=Used";
                    }
                    else
                    {
                        weburl = "https://www.autotrader.ca/cars/" + modelSplit[0] + "/" + modelSplit[1] + "/" + year + "/?rcp=100&sts=Used";
                    }

                    HtmlDocument doc = web.Load(weburl.ToLower());

                    var priceList = doc.DocumentNode.SelectNodes("//span[@class='price-amount']").ToList();

                    List <int> prices = new List <int>();

                    string priceAvg;

                    foreach (var price in priceList)
                    {
                        int i;

                        if (int.TryParse(price.InnerText.Replace("$", "").Replace(",", ""), out i))
                        {
                            int intPrice = Convert.ToInt32(price.InnerText.Replace("$", "").Replace(",", ""));

                            prices.Add(intPrice);
                        }
                    }

                    if (Convert.ToInt32(prices.Average()) > 30000)
                    {
                        web = new HtmlWeb();

                        modelSplit = model.Split();

                        weburl = "https://www.autotrader.ca/cars/" + modelSplit[0] + "/" + modelSplit[1] + "/" + year + "/?rcp=100&sts=Used";

                        doc = web.Load(weburl.ToLower());

                        priceList = doc.DocumentNode.SelectNodes("//span[@class='price-amount']").ToList();

                        prices = new List <int>();

                        foreach (var price in priceList)
                        {
                            int i;

                            if (int.TryParse(price.InnerText.Replace("$", "").Replace(",", ""), out i))
                            {
                                int intPrice = Convert.ToInt32(price.InnerText.Replace("$", "").Replace(",", ""));

                                prices.Add(intPrice);
                            }
                        }

                        priceAvg = Convert.ToString(Convert.ToInt32(prices.Average()));

                        return(priceAvg);
                    }
                    else
                    {
                        priceAvg = Convert.ToString(Convert.ToInt32(prices.Average()));

                        return(priceAvg);
                    }
                }
                catch (Exception)
                {
                    HtmlWeb web = new HtmlWeb();

                    var modelSplit = model.Split();

                    string weburl = null;

                    if (modelSplit.Count() == 3 && (modelSplit[2].Length == 2 || modelSplit[2].Length == 3))
                    {
                        weburl = "https://www.kijijiautos.ca/cars/" + modelSplit[0] + "/" + modelSplit[1] + "-" + modelSplit[2] + "/" + year + "/";
                    }
                    else
                    {
                        weburl = "https://www.kijijiautos.ca/cars/" + modelSplit[0] + "/" + modelSplit[1] + "/" + year + "/";
                    }

                    HtmlDocument doc = web.Load(weburl.ToLower());

                    var priceList = doc.DocumentNode.SelectNodes("//span[@class='_257rsiOLZRw2SUP41j3TiB _2EdRVi2tLqR7VPkJ2yR6Zx QVJux59ueO-M7o0DZZ6Vx _14Nqyg9Gv-h-nJ_lZalHW_']").ToList();

                    List <int> prices = new List <int>();

                    string priceAvg;

                    foreach (var price in priceList)
                    {
                        int i;

                        if (int.TryParse(price.InnerText.Replace("$", "").Replace(",", ""), out i))
                        {
                            int intPrice = Convert.ToInt32(price.InnerText.Replace("$", "").Replace(",", ""));

                            prices.Add(intPrice);
                        }
                    }

                    priceAvg = Convert.ToString(Convert.ToInt32(prices.Average()));

                    return(priceAvg);
                }
            }
        }
Example #49
0
        /// <summary>
        /// Метод разпознования объектов
        /// </summary>
        /// <param name="filenameForRecognize"></param>
        /// <param name="cascade"></param>
        private void Recognize(string filenameForRecognize, string cascade)
        {
            string filename = string.Format("{0}/{1}", App._APRSDir, cascade);

            long time;

            List <Rectangle> tubes    = new List <Rectangle>();
            List <Rectangle> old      = new List <Rectangle>();
            List <double>    areaList = new List <double>();
            CircleF          circle   = new CircleF();
            int     counter           = 0;
            int     i    = 1; //counter tubes
            MCvFont font = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_COMPLEX_SMALL, 1.0, 1.0);


            var ArchFile = filenameForRecognize.LoadAndResizeBitmap(1024, 1024);
            //Haar cascade
            var FileForRecognize = new Image <Bgr, byte>(ArchFile);

            DetectFace.Detect(FileForRecognize, filename, filename, tubes, old, out time);
            double AVGarea = 0.00;

            foreach (Rectangle tube in tubes)
            {
                var area = (3.14) * tube.Width * tube.Height;
                areaList.Add(area);
            }
            try
            {
                AVGarea = areaList.Average();
            }
            catch (Exception nullObjDetect)
            {
                Toast.MakeText(this, "Нет найденых объектов!!!", ToastLength.Short).Show();
            }
            foreach (var tube in tubes.OrderBy(s => s.X).ThenBy(u => u.Y))
            {
                System.Drawing.Point point = new System.Drawing.Point(tube.X + tube.Width / 3, tube.Y + tube.Height / 2);
                circle.Center = new System.Drawing.PointF(tube.X + tube.Width / 2, tube.Y + tube.Height / 2);
                circle.Radius = tube.Width / 2;
                var area = (3.14) * tube.Width * tube.Height;
                if (area / AVGarea * 100 <= 40) // меньше или равно 20 % от среднего по детектируемым объектам - не выводить в детектор
                {
                    continue;
                }
                counter = i++;
                if (FileForRecognize.Width <= 1024 && FileForRecognize.Height <= 768)
                {
                    FileForRecognize.Draw(circle, new Bgr(System.Drawing.Color.Yellow), 1);
                    FileForRecognize.Draw(string.Format("{0}", counter), ref font, point, new Bgr(System.Drawing.Color.Red));
                }
                else
                {
                    FileForRecognize.Draw(circle, new Bgr(System.Drawing.Color.Yellow), 7);
                    FileForRecognize.Draw(string.Format("{0}", counter), ref font, point, new Bgr(System.Drawing.Color.Red));
                }
            }
            //Toast.MakeText(this, "Количество: " + counter + "  Затрачено времени: " + time, ToastLength.Long).Show();
            AlertDialog.Builder alert = new AlertDialog.Builder(this);
            alert.SetTitle("Подтверждение");
            alert.SetMessage(string.Format("Распознано объектов: {0} , " +
                                           "                           Время распознавания: {1}", counter.ToString(), time.ToString()));

            alert.SetPositiveButton("Подтверждение", (senderAlert, args) => { Toast.MakeText(this, "Подтверждено!", ToastLength.Short).Show(); });
            RunOnUiThread(() => { alert.Show(); });
            imageView.SetImageBitmap(FileForRecognize.ToBitmap());

            GC.Collect();
        }
Example #50
0
        /// <summary>
        /// Same as before but with LocalDB which is much faster. Both tests are polluted by the DB implementation but this at least gives
        /// us another perspective.
        /// </summary>
        static void PerfTestSqlServer()
        {
            var sw = new Stopwatch();

            Console.WriteLine("Dapper".PadLeft(10) + " " + "+SqlBinder".PadLeft(10));
            Console.WriteLine(new string('-', 21));

            var dapper        = new List <double>();
            var plusSqlbinder = new List <double>();

            for (var n = 0; n < 10; n++)
            {
                using (var connection = OpenSqlServerConnection())
                {
                    // Dapper
                    sw.Restart();
                    for (var i = 0; i < 500; i++)
                    {
                        connection.Query <Employee>(
                            "SELECT * FROM POSTS WHERE ID IN @id",
                            new Dictionary <string, object> {
                            ["id"] = new[] { i, 1 + i, 2 + i }
                        });
                    }
                    sw.Stop();
                    Console.Write(sw.Elapsed.TotalMilliseconds.ToString("N2").PadLeft(10));
                    if (n > 0)
                    {
                        dapper.Add(sw.Elapsed.TotalMilliseconds);
                    }

                    Console.Write(' ');

                    // SqlBinder + Dapper (cached query)
                    sw.Restart();
                    var query = new Query("SELECT * FROM POSTS {WHERE {ID @id}}");
                    for (var i = 0; i < 500; i++)
                    {
                        query.SetCondition("id", new[] { i, 1 + i, 2 + i });
                        query.GetSql();
                        connection.Query <Employee>(query.OutputSql, query.SqlParameters);
                    }
                    sw.Stop();
                    if (n > 0)
                    {
                        plusSqlbinder.Add(sw.Elapsed.TotalMilliseconds);
                    }
                    Console.Write(sw.Elapsed.TotalMilliseconds.ToString("N2").PadLeft(10));
                    Console.WriteLine();
                }
            }

            Console.Write($"AVG {dapper.Average():N0}".PadLeft(10));
            Console.Write(' ');
            Console.Write($"AVG {plusSqlbinder.Average():N0}".PadLeft(10));

            Console.WriteLine();
            Console.WriteLine(" ^ Dapper = Just Dapper.");
            Console.WriteLine(" ^ +SqlBinder = Dapper with SqlBinder.");
            Console.WriteLine(" * First iteration is not accounted for in AVG.");
        }
Example #51
0
 public double AverageGrade(List <double> Grade)
 {
     return(Grade.Average());
 }
Example #52
0
        public async Task <IEnumerable <DashboardDto> > GetDashboardData(int userId)
        {
            List <Inventory>       items = new List <Inventory>();
            List <ProductCategory> cats  = new List <ProductCategory>();
            var responseList             = new List <DashboardDto>();

            items = await _context.Inventories.Where(i => i.AppUserId == userId).ToListAsync();

            cats = await _context.ProductCategories.ToListAsync();

            //All gender and age range possibilities
            var response = new DashboardDto()
            {
                AppUserId    = userId,
                Gender       = "All",
                AgeRange     = "All",
                AveragePrice = items?.Average(i => i?.ItemPrice),
                TotalCount   = items?.Sum(i => i?.ItemCount),
                Categories   = GetCategorySummary(items, cats)
            };

            responseList.Add(response);

            //Boys 2-4
            var itemsFiltered = items?.Where(i => i?.Gender == "Boys" && i?.AgeRange == "2 - 4");

            response = new DashboardDto()
            {
                AppUserId    = userId,
                Gender       = "Boys",
                AgeRange     = "2 - 4",
                AveragePrice = itemsFiltered?.Average(i => i?.ItemPrice),
                TotalCount   = itemsFiltered?.Sum(i => i?.ItemCount),
                Categories   = GetCategorySummary(itemsFiltered.ToList(), cats)
            };
            responseList.Add(response);

            //Boys 5-9
            itemsFiltered = items?.Where(i => i?.Gender == "Boys" && i?.AgeRange == "5 - 9");
            response      = new DashboardDto()
            {
                AppUserId    = userId,
                Gender       = "Boys",
                AgeRange     = "5 - 9",
                AveragePrice = itemsFiltered?.Average(i => i?.ItemPrice),
                TotalCount   = itemsFiltered?.Sum(i => i?.ItemCount),
                Categories   = GetCategorySummary(itemsFiltered.ToList(), cats)
            };
            responseList.Add(response);

            //Boys 10-14
            itemsFiltered = items?.Where(i => i?.Gender == "Boys" && i?.AgeRange == "10 - 14");
            response      = new DashboardDto()
            {
                AppUserId    = userId,
                Gender       = "Boys",
                AgeRange     = "10 - 14",
                AveragePrice = itemsFiltered?.Average(i => i?.ItemPrice),
                TotalCount   = itemsFiltered?.Sum(i => i?.ItemCount),
                Categories   = GetCategorySummary(itemsFiltered.ToList(), cats)
            };
            responseList.Add(response);

            //Girls 2-4
            itemsFiltered = items?.Where(i => i?.Gender == "Girls" && i?.AgeRange == "2 - 4");
            response      = new DashboardDto()
            {
                AppUserId    = userId,
                Gender       = "Girls",
                AgeRange     = "2 - 4",
                AveragePrice = itemsFiltered?.Average(i => i?.ItemPrice),
                TotalCount   = itemsFiltered?.Sum(i => i?.ItemCount),
                Categories   = GetCategorySummary(itemsFiltered.ToList(), cats)
            };
            responseList.Add(response);

            //Girls 5-9
            itemsFiltered = items?.Where(i => i?.Gender == "Girls" && i?.AgeRange == "5 - 9");
            response      = new DashboardDto()
            {
                AppUserId    = userId,
                Gender       = "Girls",
                AgeRange     = "5 - 9",
                AveragePrice = itemsFiltered?.Average(i => i?.ItemPrice),
                TotalCount   = itemsFiltered?.Sum(i => i?.ItemCount),
                Categories   = GetCategorySummary(itemsFiltered.ToList(), cats)
            };
            responseList.Add(response);

            //Girls 10-14
            itemsFiltered = items?.Where(i => i?.Gender == "Girls" && i?.AgeRange == "10 - 14");
            response      = new DashboardDto()
            {
                AppUserId    = userId,
                Gender       = "Girls",
                AgeRange     = "10 - 14",
                AveragePrice = itemsFiltered?.Average(i => i?.ItemPrice),
                TotalCount   = itemsFiltered?.Sum(i => i?.ItemCount),
                Categories   = GetCategorySummary(itemsFiltered.ToList(), cats)
            };
            responseList.Add(response);

            //Either 2-4
            itemsFiltered = items?.Where(i => i?.Gender == "Either" && i?.AgeRange == "2 - 4");
            response      = new DashboardDto()
            {
                AppUserId    = userId,
                Gender       = "Either",
                AgeRange     = "2 - 4",
                AveragePrice = itemsFiltered?.Average(i => i?.ItemPrice),
                TotalCount   = itemsFiltered?.Sum(i => i?.ItemCount),
                Categories   = GetCategorySummary(itemsFiltered.ToList(), cats)
            };
            responseList.Add(response);

            //Either 5-9
            itemsFiltered = items?.Where(i => i?.Gender == "Either" && i?.AgeRange == "5 - 9");
            response      = new DashboardDto()
            {
                AppUserId    = userId,
                Gender       = "Either",
                AgeRange     = "5 - 9",
                AveragePrice = itemsFiltered?.Average(i => i?.ItemPrice),
                TotalCount   = itemsFiltered?.Sum(i => i?.ItemCount),
                Categories   = GetCategorySummary(itemsFiltered.ToList(), cats)
            };
            responseList.Add(response);

            //Either 10-14
            itemsFiltered = items?.Where(i => i?.Gender == "Either" && i?.AgeRange == "10 - 14");
            response      = new DashboardDto()
            {
                AppUserId    = userId,
                Gender       = "Either",
                AgeRange     = "10 - 14",
                AveragePrice = itemsFiltered?.Average(i => i?.ItemPrice),
                TotalCount   = itemsFiltered?.Sum(i => i?.ItemCount),
                Categories   = GetCategorySummary(itemsFiltered.ToList(), cats)
            };
            responseList.Add(response);

            return(responseList);
        }
Example #53
0
 public double GetAverageTicks()
 {
     return(m_Times.Average());
 }
 public static double mean(List <double> values)
 {
     return(values.Average());
 }
Example #55
0
        protected void ZedGraphWeb1_RenderGraph(ZedGraph.Web.ZedGraphWeb webObject, System.Drawing.Graphics g, ZedGraph.MasterPane pane)
        {
            String  masina            = (String)Cache["CacheMasini"];
            DataSet dataSetITP        = (DataSet)Cache["CacheITP"];
            DataSet dataSetMasini_ITP = (DataSet)Cache["CacheMasini_ITP"];



            GraphPane myPane = pane[0];

            myPane.Title.Text       = "";
            myPane.XAxis.Title.Text = "Proprietar"; myPane.YAxis.Title.Text = "KM";
            Color[] colors =
            {
                Color.Red,    Color.Yellow, Color.Green, Color.Blue,
                Color.Purple, Color.Pink,   Color.Plum,  Color.Silver, Color.Salmon
            };
            double media;

            if (Request.QueryString["tip"] != null)
            {
                List <string> listaX = new List <string>();
                List <double> listaY = new List <double>();
                PointPairList list   = new PointPairList();
                int           i      = 0;

                List <int> listaITPPentruMasina = new List <int>();
                foreach (DataRow r in dataSetMasini_ITP.Tables[0].Rows)
                {
                    if ((int)r[1] == int.Parse(masina))
                    {
                        listaITPPentruMasina.Add((int)r[2]);
                    }
                }

                foreach (int id in listaITPPentruMasina)
                {
                    foreach (DataRow r in dataSetITP.Tables[0].Rows)
                    {
                        if (id == (int)r[0])
                        {
                            string v = r[3].ToString();

                            string v2 = r[4].ToString();
                            listaX.Add(r[3].ToString());
                            listaY.Add(double.Parse((r[4].ToString())));
                            list.Add(0, double.Parse((r[4].ToString())));
                        }
                    }
                }



                switch (Request.QueryString["tip"])
                {
                case "Bare":
                {
                    BarItem myCurve = myPane.AddBar("Curve 2", list, Color.Blue);
                    myCurve.Bar.Fill                  = new Fill(colors);
                    myCurve.Bar.Fill.Type             = FillType.GradientByZ;
                    myCurve.Bar.Fill.RangeMin         = 0;
                    myCurve.Bar.Fill.RangeMax         = list.Count;
                    myPane.XAxis.Type                 = AxisType.Text;
                    myPane.XAxis.Scale.TextLabels     = listaX.ToArray();
                    myPane.XAxis.Scale.FontSpec.Angle = 90;
                    myPane.XAxis.Scale.FontSpec.Size  = 10;
                    myPane.YAxis.Scale.FontSpec.Size  = 10;
                    //zedGraphControl1.AxisChange();


                    media = (double)listaY.Average();
                    // = media;
                    // myPane.YAxis.MajorGrid.Equals(10);
                    var yScale = myPane.YAxis.Scale;

                    double yMin = yScale.Min;
                    double yMax = yScale.Max;
                    var    line = new LineObj(media, 50000.00, media, 10000.000)
                    {
                        IsClippedToChartRect = true
                    };
                    line.Line.Color = Color.DarkGreen;
                    myPane.GraphObjList.Add(line);
                    break;
                }

                case "Bare3D": break;

                case "Pie3D": break;

                case "Linie":
                {
                    LineItem curve = myPane.AddCurve("Spline", list, Color.Red, SymbolType.Diamond);
                    curve.Line.IsSmooth      = true;
                    curve.Line.SmoothTension = 0.5F;
                    curve.Line.Width         = 2;

                    curve = myPane.AddCurve("Dreapta", list, Color.Blue, SymbolType.Diamond);
                    curve.Line.IsSmooth = false;
                    curve.Line.Width    = 2;
                    curve.Symbol.Size   = 5;

                    curve = myPane.AddCurve("ForwardStep", list, Color.Black, SymbolType.Diamond);
                    curve.Line.StepType = StepType.ForwardStep;
                    curve.Line.Width    = 2;
                    curve.Symbol.Size   = 5;

                    curve.Symbol.Fill = new Fill(Color.White);
                    curve.Symbol.Size = 10;

                    myPane.XAxis.Scale.TextLabels     = listaX.ToArray();
                    myPane.XAxis.Type                 = AxisType.Text;
                    myPane.XAxis.Scale.FontSpec.Size  = 10;
                    myPane.XAxis.Scale.FontSpec.Angle = 90;
                    myPane.YAxis.Scale.FontSpec.Size  = 10;
                    break;
                }

                case "Pie":
                {
                    i = 0;


                    foreach (int id in listaITPPentruMasina)
                    {
                        foreach (DataRow r in dataSetITP.Tables[0].Rows)
                        {
                            if (id == (int)r[0])
                            {
                                PieItem segment1 = myPane.AddPieSlice((double.Parse(r[4].ToString())),
                                                                      colors[(i++) % colors.Length],
                                                                      Color.White, 45f, (i % 2 == 0) ? 0.2 : 0, r[3].ToString());
                            }
                        }
                    }
                    break;
                }
                }
            }
        }
 public ConsolidatedLine(List <Siegler> lst)
 {
     Pixel = lst[0].Pixel;
     Depth = lst.Average(s => s.Depth);
     StDev = (float)Math.Sqrt(lst.Sum(s => Math.Pow(s.Depth - Depth, 2)) / (lst.Count - 1));
 }
Example #57
0
        public static void ComputeFrequencyDutyCycle(ChannelData data, out double frequency, out double frequencyError, out double dutyCycle, out double dutyCycleError, out Dictionary <int, bool> risingNFallingEdges, float minVoltage, float maxVoltage)
        {
            frequency           = double.NaN;
            frequencyError      = double.NaN;
            dutyCycle           = double.NaN;
            dutyCycleError      = double.NaN;
            risingNFallingEdges = new Dictionary <int, bool>();

            bool[] digitized = data.array.GetType().GetElementType() == typeof(bool) ? (bool[])data.array : LabNation.Common.Utils.Schmitt((float[])data.array, minVoltage, maxVoltage);

            List <double> edgePeriod = new List <double>();
            List <double> highPeriod = new List <double>();
            List <double> lowPeriod  = new List <double>();

            int    lastRisingIndex  = 0;
            int    lastFallingIndex = 0;
            double samplePeriod     = data.samplePeriod;

            for (int i = 1; i < digitized.Length; i++)
            {
                //Edge detection by XOR-ing sample with previous sample
                bool edge = digitized[i] ^ digitized[i - 1];
                if (edge)
                {
                    //If we're high now, it's a rising edge
                    if (digitized[i])
                    {
                        risingNFallingEdges.Add(i, true);
                        if (lastRisingIndex > 0)
                        {
                            edgePeriod.Add((i - lastRisingIndex) * samplePeriod);
                        }
                        if (lastFallingIndex > 0)
                        {
                            lowPeriod.Add((i - lastFallingIndex) * samplePeriod);
                        }

                        lastRisingIndex = i;
                    }
                    else
                    {
                        risingNFallingEdges.Add(i, false);
                        if (lastFallingIndex > 0)
                        {
                            edgePeriod.Add((i - lastFallingIndex) * samplePeriod);
                        }
                        if (lastRisingIndex > 0)
                        {
                            highPeriod.Add((i - lastRisingIndex) * samplePeriod);
                        }
                        lastFallingIndex = i;
                    }
                }
            }

            if (edgePeriod.Count < 1)
            {
                return;
            }

            //if freq is way too high to be measured
            if (risingNFallingEdges.Count >= digitized.Length / 2)
            {
                //invalidate all results and return
                frequency           = double.NaN;
                frequencyError      = double.NaN;
                dutyCycle           = double.NaN;
                dutyCycleError      = double.NaN;
                risingNFallingEdges = new Dictionary <int, bool>();
                return;
            }

            //take median
            edgePeriod.Sort();
            double median = edgePeriod.ElementAt((int)edgePeriod.Count / 2);

            if (highPeriod.Count > 0 && lowPeriod.Count > 0)
            {
                dutyCycle  = highPeriod.Average() / median;
                dutyCycle += 1.0 - lowPeriod.Average() / median;
                dutyCycle *= 50;
            }
            if (dutyCycle < 0)
            {
                dutyCycle = 0;
            }
            if (dutyCycle > 100)
            {
                dutyCycle = 100;
            }

            //reject if more than 5% of are more than 50% off
            float         rejectRatio = 0.05f;
            float         errorRatio  = 0.5f;
            double        f           = 1 / median;
            double        fError      = edgePeriod.Select(x => Math.Abs(1 / x - f)).Max();
            List <double> outliers    = edgePeriod.Where(x => Math.Abs(x - median) > median * errorRatio).ToList();

            if (fError > f * 0.6 && outliers.Count > edgePeriod.Count * rejectRatio)
            {
                return;
            }
            frequency      = f;
            frequencyError = fError;
        }
Example #58
0
        static void Main(string[] args)
        {
            var entero = 20;



            // Libreria
            var libro1 = new Libro();

            libro1.Titulo = "Harry Potter";
            libro1.Precio = 200;
            libro1.Autor  = "Autora";

            var libro2 = new Libro("Harry", 200, "Autora");

            var libro3 = new Libro()
            {
                Titulo = "Harry Potter",
                Precio = 200,
                Autor  = "Autora"
            };

            var booleano = true;

            // arreglo (finito)
            Libro[] libros = new Libro[3];

            libros[0] = libro1;
            libros[1] = libro2;
            libros[2] = libro3;


            int[] numeros = new int[3];

            // diamante < >
            // Clase lista se llama generics
            var listaLibros = new List <Libro>();

            listaLibros.Add(libro1);
            listaLibros.Add(libro2);

            // tipos de variables
            // primitivas
            int primitiva = 20;
            // objetos
            Libro objeto = new Libro();
            // arreglos (finitos)
            // listas hash, stack, queue
            List <string> paises = new List <string>();

            paises.Add("Chile");
            paises.Add("Argentina");
            paises.Add("Peru");

            int contador = 0;

            //contador=contador+1;
            //contador++;
            //contador+=1;


            // loop
            // 1) for

            for (int i = 0; i < 3; i++)
            {
                Debug.WriteLine(paises[i]);
            }

            for (int i = 2; i >= 0; i--)
            {
                Debug.WriteLine(paises[i]);
            }

            // de dos en dos
            for (int i = 0; i < 3; i += 2)
            {
                Debug.WriteLine(paises[i]);
            }


            // ciclo anidado
            for (int i = 0; i < 10; i++)
            {
                for (int e = 0; e < 10; e++)
                {
                    Debug.WriteLine(i + " " + e);
                }
            }

            // 2) ciclo while
            // quiero usar el while cuando no
            // se cuando debo terminar el loop.
            // Por ejemplo: si voy a leer un texto linea
            // a linea.
            int cont = 0;

            while (cont < 10)
            {
                Debug.WriteLine("ciclo while");
                cont = cont + 1;
            }

            do
            {
                Debug.WriteLine("ciclo while");
                cont = cont + 1;
            } while (cont < 10);

            // 3) foreach
            // necesitamos una lista o arreglo.

            foreach (string pais in paises)
            {
                Debug.WriteLine(pais);
            }

            List <int> precios = new List <int>();

            precios.Add(1);
            precios.Add(2);
            precios.Add(10);

            // obtener el promedio.
            int total = 0;

            foreach (int precio in precios)
            {
                total = total + precio;
            }
            int promedio = total / precios.Count;

            Debug.WriteLine(promedio);

            // alias => alias

            double promedio2 = precios.Average(p => p);

            total = precios.Sum(p => p);
        }
Example #59
0
        public void Consume(CompletedSimpleWorkItem message)
        {
            Interlocked.Increment(ref _received);

            int messageMs = DateTime.UtcNow.Subtract(message.RequestCreatedAt).Milliseconds;

            lock (_values)
            {
                _values.Add(messageMs);
            }

            _log.InfoFormat("Received: {0} - {1} [{2}ms]", _received, message.CorrelationId, messageMs);
            _log.InfoFormat("Stats\n\tMin: {0:0000.0}ms\n\tMax: {1:0000.0}ms\n\tAvg: {2:0000.0}ms", _values.Min(), _values.Max(), _values.Average());
        }
 /// <summary>
 /// Annualized return statistic calculated as an average of daily trading performance multiplied by the number of trading days per year.
 /// </summary>
 /// <param name="performance">Dictionary collection of double performance values</param>
 /// <param name="tradingDaysPerYear">Trading days per year for the assets in portfolio</param>
 /// <remarks>May be unaccurate for forex algorithms with more trading days in a year</remarks>
 /// <returns>Double annual performance percentage</returns>
 public static double AnnualPerformance(List <double> performance, double tradingDaysPerYear = 252)
 {
     return(performance.Average() * tradingDaysPerYear);
 }