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 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 #4
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 #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)
     };
 }
        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;
            }
        }
Example #8
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");
 }
		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;
        }
Example #13
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;
        }
        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);
        }
        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 #16
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);
        }
Example #17
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 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());
        }
        /// <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 #20
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());
        }
        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();
        }
Example #22
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 #23
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 #24
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 #25
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));
        }
 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();
 }
//========================================================================= 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;
        }
Example #28
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()
 {
     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 #30
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;
            }
        }