Example #1
0
    private void ShowSampleItems_Click(object sender, EventArgs e) {
      // create some sample items;

      MyMap.MapElements.Clear();
      MyMap.Layers.Clear();

      var bounds = new List<LocationRectangle>();
      foreach (var area in DataManager.SampleAreas) {
        var shape = new MapPolygon();
        foreach (var parts in area.Split(' ').Select(cord => cord.Split(','))) {
          shape.Path.Add(new GeoCoordinate(double.Parse(parts[1], ci), double.Parse(parts[0], ci)));
        }

        shape.StrokeThickness = 3;
        shape.StrokeColor = Colors.Blue;
        shape.FillColor = Color.FromArgb((byte)0x20, shape.StrokeColor.R, shape.StrokeColor.G, shape.StrokeColor.B);
        bounds.Add(LocationRectangle.CreateBoundingRectangle(shape.Path));
        MyMap.MapElements.Add(shape);
      }

      var rect = new LocationRectangle(bounds.Max(b => b.North), bounds.Min(b => b.West), bounds.Min(b => b.South), bounds.Max(b => b.East));
      MyMap.SetView(rect);

      // show all Items
      var itemsLayer = new MapLayer();
      foreach (var item in DataManager.SampleItems) {
        DrawItem(item, "Ulm", itemsLayer);
      }

      MyMap.Layers.Add(itemsLayer);
    }
        public static Tuple<int, int> getSmartPosition(List<System.Drawing.Rectangle> listRect, System.Drawing.Rectangle rect)
        {
            HashSet<Rectangle> hsRect = new HashSet<Rectangle>(listRect);
            List<Rectangle> listGotCollide = new List<Rectangle>();

            foreach (var item in hsRect)
            {
                Rectangle intersect = Rectangle.Intersect(item, rect);
                if (intersect.Width > 1 && intersect.Height > 1)
                {
                    listGotCollide.Add(item);
                }
            }

            int xOuter = listGotCollide.Min(item => item.X);
            int yOuter = listGotCollide.Min(item => item.Y);

            int xInner = xOuter + 32;
            int yInner = yOuter + 32;

            int xResult = Math.Abs(rect.X - xOuter) > Math.Abs(rect.X - xInner) ? xInner : xOuter;
            int yResult = Math.Abs(rect.Y - yOuter) > Math.Abs(rect.Y - yInner) ? yInner : yOuter;

            Tuple<int, int> result = new Tuple<int, int>(xResult, yResult);

            return result;
        }
        public ShipOnMap(Texture2D texture, Texture2D circle, Vector2 position, Vector2 scale, List<Ship> ships)
        {
            Texture = texture;
            Circle = circle;
            Scale = scale;
            this.position = position;
            this.velocity = ships.Min(x => x.Velocity);

            FinalWidth = position.X + texture.Width * scale.X;
            FinalHeight = position.Y + texture.Height * scale.Y;

            Ships = ships;

            IsPressed = false;
            IsOwnByThisPlayer = false;
            IsRightButtonPressed = false;
            IsMoving = false;

            SpeedMod = ships.Min(x => x.SpeedMod);

            Origin = new Vector2(Texture.Width / 2, Texture.Height / 2);
            CircleOrigin = new Vector2((Circle.Width - Texture.Width) / 2, (Circle.Height - Texture.Height) / 2);
            CircleScale = Scale;

            Rotation = 0;
            Timer = 0;
            Mobility = 0;
            Target = null;
            IsMovingToSystem = false;
            IsVisible = true;
        }
Example #4
0
    static void Main()
    {
        var numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };

        var odd = numbers.WhereNot(x => x % 2 == 0);
        Console.WriteLine(string.Join(" ", odd));

        var numbersBiggerThanTen = numbers.WhereNot(LessThanTen);
        Console.WriteLine(string.Join(" ", numbersBiggerThanTen));
        Console.WriteLine();

        var students = new List<Student>()
        {
            new Student("Stavri",5.5),
            new Student("Loshiq",2),
            new Student("Me4a", 3.50),
            new Student("Anatoli", 4.4),
            new Student("Rambo", 5.95)
        };

        Console.WriteLine(students.Max(student => student.Grade));
        Console.WriteLine(students.Min(Grade));

        Console.WriteLine();
        Console.WriteLine(students.Max(Name));
        Console.WriteLine(students.Min(student => student.Name));
    }
Example #5
0
    static void Main()
    {
        string input = Console.ReadLine();

        List<decimal> inputNums = new List<decimal>();
        List<decimal> oddNums = new List<decimal>();
        List<decimal> evenNums = new List<decimal>();

        string[] numbers = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

        foreach (var num in numbers)
        {
            inputNums.Add(decimal.Parse(num));
        }

        int index = 1;

        for (int i = 0; i < inputNums.Count; i++)
        {

            if (index % 2 == 1)
            {
                oddNums.Add(inputNums[i]);
            }
            else
            {
                evenNums.Add(inputNums[i]);
            }

            index++;
        }

        if (inputNums.Count == 0)
        {
            Console.WriteLine("OddSum=No, OddMin=No, OddMax=No, EvenSum=No, EvenMin=No, EvenMax=No");
        }

        else if (inputNums.Count == 1)
        {
            double oddNumsSum = (double)oddNums.Sum();
            double oddNumsMin = (double)oddNums.Min();
            double oddNumsMax = (double)oddNums.Max();
            
            Console.WriteLine("OddSum={0:G0}, OddMin={1:G0}, OddMax={2:G0}, EvenSum=No, EvenMin=No, EvenMax=No",
                oddNumsSum, oddNumsMin, oddNumsMax);
        }

        else
        {
            double oddNumsSum = (double)oddNums.Sum();
            double oddNumsMin = (double)oddNums.Min();
            double oddNumsMax = (double)oddNums.Max();
            double evenNumsSum = (double)evenNums.Sum();
            double evenNumsMin = (double)evenNums.Min();
            double evenNumsMax = (double)evenNums.Max();

            Console.WriteLine("OddSum={0:G0}, OddMin={1:G0}, OddMax={2:G0}, EvenSum={3:G0}, EvenMin={4:G0}, EvenMax={5:G0}",  // {...:G0} Remove trailing zeros
                oddNumsSum, oddNumsMin, oddNumsMax, evenNumsSum, evenNumsMin, evenNumsMax);
        }
    }
Example #6
0
 private static Map ParseMap(string zone, string[] lines) {
     Map tmpMap = new Map();
     tmpMap.zone = zone;
     if (tmpMap.zone != "") {
         List<MapLineSegment> segmentList = new List<MapLineSegment>();
         foreach (string l in lines) {
             if (l[0] == 'L') {
                 segmentList.Add(ParseSegment(l));
             }
             else if (l[0] == 'P') {
                 //parse place
             }
         }
         //group up line segments according to color(RGB) value, then create one pen for each color used
         //this should greatly lower the overhead for creating brush and pen objects 
         //*edit* aparently not.
         List<MapLineSegment> distinctSegments = segmentList.Distinct(new MapLineSegmentColorComparer()).ToList();
         foreach (MapLineSegment colorSource in distinctSegments) {
             List<MapLineSegment> tmpSegmentList = segmentList.FindAll(x => x.color == colorSource.color);
             SolidColorBrush colorBrush = new SolidColorBrush(colorSource.color);
             Pen tmpPen = new Pen(colorBrush, 1.0);
             tmpMap.lineList.Add(new MapLine(tmpSegmentList, tmpPen));
         }
         if (segmentList.Count > 0) {
             tmpMap.maxX = Math.Max(segmentList.Max(x => x.aX), segmentList.Max(x => x.bX));
             tmpMap.maxY = Math.Max(segmentList.Max(x => x.aY), segmentList.Max(x => x.bY));
             tmpMap.minX = Math.Min(segmentList.Min(x => x.aX), segmentList.Min(x => x.bX));
             tmpMap.minY = Math.Min(segmentList.Min(x => x.aY), segmentList.Min(x => x.bY));
             tmpMap.width = tmpMap.maxX - tmpMap.minX;
             tmpMap.height = tmpMap.maxY - tmpMap.minY;
             tmpMap.depth = tmpMap.maxZ - tmpMap.minZ;
         }
     }
     return tmpMap;
 }
        private void AddPlotSeries(List<Tuple<double, double>> ansv, double stepX, double stepY)
        {
            _stepX = stepX;
            _stepY = stepY;
            if (!_firstLoaded)
                DrawGrid(ansv.Min(item => item.Item1), ansv.Max(item => item.Item1), stepX,
                    ansv.Min(item => item.Item2), ansv.Max(item => item.Item2), stepY);

            MyCanvas.Children.Add(GenerateSeriesPath(ansv));
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="table"></param>
        /// <param name="chart"></param>
        /// <param name="indexAxisX"></param>
        /// <param name="indexAxisY"></param>
        public void Plot(DataTable table, Chart chart, int indexAxisX, int indexAxisY)
        {
            if (HasNull(table))
            {
                MessageBox.Show(@"Iterate data first!");
            }
            else
            {
                try
                {
                    var xValue = new List<double>();
                    var yValue = new List<double>();

                    foreach (var series in chart.Series)
                    {
                        series.Points.Clear();
                    }

                    for (var i = 1; i < table.Columns.Count; i++)
                    {
                        xValue.Add(
                            Convert.ToDouble(table.Rows[indexAxisX][i].ToString()));
                        yValue.Add(
                            Convert.ToDouble(table.Rows[indexAxisY][i].ToString()));
                    }

                    if (Math.Abs(xValue.Min() - xValue.Max()) < 0.0000001 ||
                        Math.Abs(yValue.Min() - yValue.Max()) < 0.0000001)
                    {
                        MessageBox.Show(@"The selected data cannot be charted!");
                    }
                    else
                    {
                        chart.Series[0].Points.DataBindXY(xValue, yValue);
                        chart.Series[0].ChartType = SeriesChartType.FastLine;
                        chart.Series[0].Color = Color.Black;
                        chart.ChartAreas[0].AxisX.Maximum = xValue.Max();
                        chart.ChartAreas[0].AxisX.Minimum = xValue.Min();
                        chart.ChartAreas[0].AxisY.Maximum = yValue.Max();
                        chart.ChartAreas[0].AxisY.Minimum = yValue.Min();
                        chart.ChartAreas[0].AxisX.MajorGrid.Enabled = true;
                        chart.ChartAreas[0].AxisY.MajorGrid.Enabled = true;
                        chart.ChartAreas[0].AxisX.Title =
                            table.Rows[indexAxisX][0].ToString();
                        chart.ChartAreas[0].AxisY.Title =
                            table.Rows[indexAxisY][0].ToString();
                        chart.Series[0].IsVisibleInLegend = false;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(@"Chart error: " + ex.Message);
                }
            }
        }
    static void Main()
    {
        string numbersString = Console.ReadLine();
        if (numbersString == "")
        {
            Console.WriteLine("OddSum=No, OddMin=No, OddMax=No, EvenSum=No, EvenMin=No, EvenMax=No");
        }

        else
        {
            decimal[] numbers = Array.ConvertAll(numbersString.Split(' '), decimal.Parse);


            List<decimal> odd = new List<decimal>();
            List<decimal> even = new List<decimal>();


            for (int i = 0; i < numbers.Length; i++)
            {
                if (i % 2 == 0)
                {
                    odd.Add(numbers[i]);

                }
                else
                {
                    even.Add(numbers[i]);
                }
            }
            if ((odd.Count == 0 && even.Count == 0) || numbersString == "")
            {
                Console.WriteLine("OddSum=No, OddMin=No, OddMax=No, EvenSum=No, EvenMin=No, EvenMax=No");
            }
            if (even.Count == 0)
            {
                decimal oddSum = odd.Sum();
                decimal oddMin = odd.Min();
                decimal oddMax = odd.Max();
                Console.WriteLine("OddSum={0:0.##}, OddMin={1:0.##}, OddMax={2:0.##}, EvenSum=No, EvenMin=No, EvenMax=No", oddSum, oddMin, oddMax);
            }
            else
            {
                decimal oddSum = odd.Sum();
                decimal oddMin = odd.Min();
                decimal oddMax = odd.Max();

                decimal evenSum = even.Sum();
                decimal evenMin = even.Min();
                decimal evenMax = even.Max();

                Console.WriteLine("OddSum={0:0.##}, OddMin={1:0.##}, OddMax={2:0.##}, EvenSum={3:0.##}, EvenMin={4:0.##}, EvenMax={5:0.##}"
                                            , oddSum, oddMin, oddMax, evenSum, evenMin, evenMax);
            }
        }    
    }
Example #10
0
 public static Point MinPoint( List<Point> points, Axis axis)
 {
     double min;
     if (axis == Axis.X)
     {
         min = points.Min(p => p.X);
         return points.FirstOrDefault(p => DoubleCompare(p.X , min));
     }
     min = points.Min(p => p.Y);
     return points.FirstOrDefault(p => DoubleCompare(p.Y, min));
 }
Example #11
0
        public Rectangle boundingRectangle(List<Point> points)
        {
            // Add checks here, if necessary, to make sure that points is not null,
            // and that it contains at least one (or perhaps two?) elements

            var minX = points.Min(p => p.X);
            var minY = points.Min(p => p.Y);
            var maxX = points.Max(p => p.X);
            var maxY = points.Max(p => p.Y);

            return new Rectangle(new Point(minX, minY), new Size(maxX - minX, maxY - minY));
        }
Example #12
0
		public VectorPath(List<VectorPathSegment> seg)
		{
			segments = seg;
			Length = segments.Sum(p => p.Length);

			float top = segments.Min(p => p.Boundings.Top);
			float bot = segments.Max(p => p.Boundings.Bottom);
			float lef = segments.Min(p => p.Boundings.Left);
			float rig = segments.Max(p => p.Boundings.Right);

			Boundings = new FRectangle(lef, top, rig-lef, bot-top);
		}
Example #13
0
 public static void GetEnvelope(double lat, double lon, double dist, out double minLat, out double minLon, out double maxLat, out double maxLon)
 {
     var gc = new GeodeticCalculator();
     var endpoints = new List<GlobalCoordinates>();
     endpoints.Add(gc.CalculateEndingGlobalCoordinates(Ellipsoid.WGS84, new GlobalCoordinates(new Angle(lat), new Angle(lon)), new Angle(0), dist * 1000.0));
     endpoints.Add(gc.CalculateEndingGlobalCoordinates(Ellipsoid.WGS84, new GlobalCoordinates(new Angle(lat), new Angle(lon)), new Angle(90), dist * 1000.0));
     endpoints.Add(gc.CalculateEndingGlobalCoordinates(Ellipsoid.WGS84, new GlobalCoordinates(new Angle(lat), new Angle(lon)), new Angle(180), dist * 1000.0));
     endpoints.Add(gc.CalculateEndingGlobalCoordinates(Ellipsoid.WGS84, new GlobalCoordinates(new Angle(lat), new Angle(lon)), new Angle(270), dist * 1000.0));
     minLat = endpoints.Min(x => x.Latitude.Degrees);
     maxLat = endpoints.Max(x => x.Latitude.Degrees);
     minLon = endpoints.Min(x => x.Longitude.Degrees);
     maxLon = endpoints.Max(x => x.Longitude.Degrees);
 }
 public static void Sorting(List<int> array)
 {
     int[] sortedArray = new int[array.Count];
     for (int i = 0; i < sortedArray.Length; i++)
     {
         sortedArray[i] = array.Min();
         array.Remove(array.Min());
     }
     Console.WriteLine("The sorted array is: ");
     for (int i = 0; i < sortedArray.Length; i++)
     {
         Console.WriteLine(sortedArray[i]);
     }
 }
Example #15
0
        private void AssignLabel()
        {
            Doggies.ForEach(x =>
            {
                var distances = new List<double> () {   GetEuclideanDistance(x, chihuahuaCentroid),
                                                        GetEuclideanDistance(x, beaglesCentroid),
                                                        GetEuclideanDistance(x, daschundCentroid) };
                if (distances[0] == distances.Min()) x.Label = Label.Chihuahuas;
                else if (distances[1] == distances.Min()) x.Label = Label.Beagles;
                else x.Label = Label.Daschunds;

                FixCentroids(x.Label);

            });
        }
        private Floor ChooseElevator(Floor start, ElevatorStatus elevatorStatus)
        {
            List <ElevatorNumFloor> diffFloors = new List <ElevatorNumFloor>();

            building.floors.ForEach(x =>
            {
                if (x.elevators.Count > 0)
                {
                    foreach (Elevator elevator in x.elevators)
                    {
                        if (elevator.Status != ElevatorStatus.LONGSTOP && (elevatorStatus == elevator.Status || elevator.Status == ElevatorStatus.STOP))
                        {
                            diffFloors.Add(new ElevatorNumFloor()
                            {
                                FloorNum = x.FloorNum, FloorDiff = Math.Abs(x.FloorNum - start.FloorNum)
                            });
                        }
                    }
                }
            }
                                    );

            var minDiff = diffFloors?.Min(x => x.FloorDiff);

            return(building.floors.Where(f => f.FloorNum == diffFloors.First(x => x.FloorDiff == minDiff).FloorNum).FirstOrDefault());
        }
        public double CariDiApple(double imApple1,double imApple2,double imApple3,double imApple4,double imApple5,double imApple6,double imApple7)
        {
            List<double> listUApple = new List<double>();
            SqlConnection sqlcon = new SqlConnection(con);
            sql = "select * from Apple";
            sqlcon.Open();
            SqlCommand cmd = new SqlCommand(sql, sqlcon);
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                double h1 = Math.Abs(Convert.ToDouble(dr["m1"]) - imApple1);
                double h2 = Math.Abs(Convert.ToDouble(dr["m2"]) - imApple2);
                double h3 = Math.Abs(Convert.ToDouble(dr["m3"]) - imApple3);
                double h4 = Math.Abs(Convert.ToDouble(dr["m4"]) - imApple4);
                double h5 = Math.Abs(Convert.ToDouble(dr["m5"]) - imApple5);
                double h6 = Math.Abs(Convert.ToDouble(dr["m6"]) - imApple6);
                double h7 = Math.Abs(Convert.ToDouble(dr["m7"]) - imApple7);
                double Nh = Math.Sqrt(Math.Pow(h1,2)+Math.Pow(h2,2)+Math.Pow(h3,2)+Math.Pow(h4,2)+Math.Pow(h5,2)+Math.Pow(h6,2)+Math.Pow(h7,2));
                listUApple.Add(Nh);

            }
            sqlcon.Close();

            NApple = listUApple.Min();

            return NApple;
        }
Example #18
0
        static void Main(string[] args)
        {
            int[] numbers = Console
                .ReadLine()
                .Split(new Char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(item => int.Parse(item))
                .ToArray();

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

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

            for (int i = 0; i < numbers.Length; i++)
            {
                allNumbers.Add(numbers[i]);
            }

            for (int i = 0; i < numbers.Length; i++)
            {
                for (int j = 0; j < allNumbers.Count; j++)
                {
                    int min = allNumbers.Min();
                    allNumbers.Remove(min);
                    sortNumbers.Add(min);
                }
            }

            Console.Write(string.Join(" ", sortNumbers));

            Console.WriteLine();
        }
Example #19
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();
 }
        public bool Graph(bool genCustom = true)
        {
            var logN = new LogNormal();
            var normal = new Normal();
            var m = genCustom ? normal.GenCustomNormal(1000000, Environment.TickCount) : normal.GenNormal(10000);

            var mas = new double[m.Count];
            var i = 0;
            var list = new List<double>();

            foreach (var el in m)
            {
                list.Add(el);
                mas[i] = logN.GenLogNormalNumber(1, 10, el);
                i++;
            }

            var res = new CreateGraphicData();

            res.Create(mas, 80);

            var gg = new GetMuSigma(list.ToArray());
            Console.WriteLine(gg.ResultMu + "\n" + gg.ResultSigma);
            Console.WriteLine(list.Min());
            Console.ReadLine();

            return true;
        }
        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 #23
0
        public Histogram(List<uint> items, int binsArg)
        {
            TotalBins = binsArg;

            // Performs binning.  Reference: http://stackoverflow.com/questions/2387916/looking-for-a-histogram-binning-algorithm-for-decimal-data
            Min = items.Min();
            Max = items.Max();
            bins = new List<uint>(TotalBins);
            for (int i = 0; i < TotalBins; i++)
            {
                bins.Add(0);
            }

            BinSize = (Max - Min) / (uint)TotalBins;
            foreach (var value in items)
            {
                int bucketIndex = 0;
                if (BinSize > 0.0)
                {
                    bucketIndex = (int)((value - Min) / BinSize);
                    if (bucketIndex >= TotalBins)
                    {
                        bucketIndex = TotalBins - 1;
                    }
                }
                bins[bucketIndex]++;
            }
        }
Example #24
0
        public GiftBox CreateBox(List<string> dimensions)
        {
            if (dimensions.Count != 3)
            {
                throw new InvalidOperationException("Box was malformed in number of dimensions: " + dimensions.Count);
            }

            if (0 == dimensions.Min(x => x.Length))
            {
                throw new InvalidOperationException("Box was malformed");
            }

            int length;
            int width;
            int height;

            if (!int.TryParse(dimensions[0], out length))
            {
                throw new InvalidOperationException("Failed to parse length: " + dimensions[0]);
            }
            if (!int.TryParse(dimensions[1], out width))
            {
                throw new InvalidOperationException("Failed to parse width: " + dimensions[1]);
            }
            if (!int.TryParse(dimensions[2], out height))
            {
                throw new InvalidOperationException("Failed to parse height: " + dimensions[2]);
            }

            return new GiftBox(length, width, height);
        }
Example #25
0
        public async Task RunAsync(CancellationToken cancellationToken)
        {
            var sw = Stopwatch.StartNew();
            var min = _fromDate.ToUniversalTime().Ticks;
            var max = _toDate.ToUniversalTime().Ticks;

            var table = _tableClient.GetTableReference("WADPerformanceCountersTable");

            var query = new TableQuery<WADPerformanceCountersTable>()
                .Where(TableQuery.CombineFilters(
                    TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.GreaterThanOrEqual, min.ToString("d19")),
                    TableOperators.And,
                    TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.LessThan, max.ToString("d19"))));

            var result = new List<WADPerformanceCountersTable>();
            TableContinuationToken token = null;
            do
            {
                var segment = await table.ExecuteQuerySegmentedAsync(query, token, null, null, cancellationToken);
                token = segment.ContinuationToken;
                result.AddRange(segment.Results);
                // Console.Write($"{segment.Results.Count}.");

            } while (token != null);
            Console.WriteLine();

            sw.Stop();
            Console.WriteLine("Count:{0}, Min: {1}, Max: {2}, Elapsed: {3:F2} sec",
                result.Count, result.Min(e => e.PartitionKey), result.Max(e => e.PartitionKey), (sw.ElapsedMilliseconds / 1000.0));
        }
    static void Main()
    {
        Console.Write("Please enter a positive integer number: ");

        int n = int.Parse(Console.ReadLine());

        var temp = new List<decimal>();

        decimal add = 0;

        if (n != 1)
        {
            for (int i = 1; i <= n; i++)
            {

                Console.Write("Please enter number {0}: ", i);
                add = decimal.Parse(Console.ReadLine());
                temp.Add(add);
            }
        }

        decimal sum = temp.Sum();
        decimal min = temp.Min();
        decimal max = temp.Max();
        decimal avg = sum / n;

        Console.WriteLine("------------------------", min, max, sum, avg);
        Console.WriteLine("min = {0:F0}\n\rmax = {1:F0}\n\rsum = {2:F0}\n\ravg = {3:F2}", min, max, sum, avg);

        Console.ReadKey();
    }
Example #27
0
 public override double GetNominalStrength()
 {
     //(17.4.1.2)
     List<double> stresses = new List<double>() { 125000, 1.9 * fya, futa };
     double N_sa = n * (A_se_N * stresses.Min() / 1000);
     return N_sa;
 }
Example #28
0
        private void FindPath(int startNode)
        {
            List<int> unprocessedNodesIdxs = new List<int>();
            foreach(var n in _Graph.Keys)
            {
                _ClosestNodes[n] = new Edge { Distance = decimal.MaxValue };
                unprocessedNodesIdxs.Add(n);
            }
            _ClosestNodes[startNode].Distance = 0;

            while(unprocessedNodesIdxs.Count > 0)
            {
                var currentNodeIdx = unprocessedNodesIdxs.First(p => _ClosestNodes[p].Distance == unprocessedNodesIdxs.Min(pp => _ClosestNodes[pp].Distance));
                unprocessedNodesIdxs.Remove(currentNodeIdx);

                foreach(var outEdge in _Graph[currentNodeIdx])
                {
                    decimal currentDistance = _ClosestNodes[outEdge.NextNodeId].Distance;
                    decimal newDistance = Math.Min(currentDistance, _ClosestNodes[currentNodeIdx].Distance + outEdge.EdgeVeight);
                    if(newDistance < currentDistance)
                    {
                        _ClosestNodes[outEdge.NextNodeId].Distance = newDistance;
                        _ClosestNodes[outEdge.NextNodeId].NextNodeId = currentNodeIdx;
                    }
                }
            }
        }
        public ActionResult Index(int id, List<int> grSel) {
            var db = new ZkDataContext();
            var post = db.ForumPosts.Find(id);

            string txt1;
            string txt2;

            if (grSel != null && grSel.Any())
            {
                if (grSel.Count > 1)
                {
                    txt1 = db.ForumPostEdits.Find(grSel.Min()).NewText;
                    txt2 = db.ForumPostEdits.Find(grSel.Max()).NewText;
                } else
                {
                    var edit = db.ForumPostEdits.Find(grSel.First());
                    txt1 = edit.OriginalText;
                    txt2 = edit.NewText;
                }

                var sd = new SideBySideDiffBuilder(new Differ());
                ViewBag.DiffModel = sd.BuildDiffModel(txt1, txt2);
            } else
            {
                var edit = post.ForumPostEdits.OrderByDescending(x => x.ForumPostEditID).FirstOrDefault();
                if (edit != null)
                {
                    var sd = new SideBySideDiffBuilder(new Differ());
                    ViewBag.DiffModel = sd.BuildDiffModel(edit.OriginalText, edit.NewText);
                }
            }


            return View("PostHistoryIndex", post);
        }
 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 #31
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 #32
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          = "";
        }
Example #33
0
        ///<summary>
        ///To Get the Id of the default scorecard to show the user
        ///</summary>
        ///<param name="userName"> The Logged in user name</param>
        ///<returns> Returns the Id of the default scorecard to show the user</returns>
        public int?GetDefaultScorecardId(User user)
        {
            int?       scorecardId     = null;
            List <int> scorecardIdList = new List <int>();

            // check if user is a KPI Owner of any scorecard(s), add the scorecardId to  scorecardIdList
            if (user?.KPIOwnerScorecards.Count(x => x.IsActive) > 0)
            {
                scorecardIdList = user.KPIOwnerScorecards.Where(x => x.IsActive)?.Select(x => x.ScorecardId).ToList();
            }
            //check if user is a KPI Owner of any scorecard(s), add the scorecardId to  scorecardIdList
            else if (user?.TeamScorecards.Count(x => x.IsActive) > 0)
            {
                scorecardIdList.AddRange(user.TeamScorecards.Where(x => x.IsActive)?.Select(x => x.ScorecardId).ToList());
            }
            scorecardId = scorecardIdList.Any()? scorecardIdList?.Min() : null;

            return(scorecardId);
        }
        /// <summary>
        /// 获取该分区中心坐标
        /// </summary>
        /// <param name="SectionDataCollection"></param>
        /// <returns></returns>
        public Vector GetCentre(SectionDataCollection SectionDataCollection)
        {
            //变量初始化
            Vector         Result    = new Vector();
            List <decimal> Tem_Dat_X = new List <decimal>();
            List <decimal> Tem_Dat_Y = new List <decimal>();

            //获取数据
            foreach (var o in SectionDataCollection.SectionDatas)
            {
                if (!o.EN)
                {
                    continue;
                }
                if (o.ArcLine.Count > 0)
                {
                    for (int i = 0; i < o.ArcLine.Count; i++)
                    {
                        if (o.ArcLine[i].Count >= 0)//判断数据大于零
                        {
                            Tem_Dat_X.Add(o.ArcLine[i].Max(p => p.Start_x));
                            Tem_Dat_X.Add(o.ArcLine[i].Min(p => p.Start_x));
                            Tem_Dat_X.Add(o.ArcLine[i].Max(p => p.End_x));
                            Tem_Dat_X.Add(o.ArcLine[i].Min(p => p.End_x));
                            Tem_Dat_Y.Add(o.ArcLine[i].Max(p => p.Start_y));
                            Tem_Dat_Y.Add(o.ArcLine[i].Min(p => p.Start_y));
                            Tem_Dat_Y.Add(o.ArcLine[i].Max(p => p.End_y));
                            Tem_Dat_Y.Add(o.ArcLine[i].Min(p => p.End_y));
                        }
                    }
                }
                if (o.Circle.Count > 0)
                {
                    Tem_Dat_X.Add(o.Circle.Max(p => p.Center_x));
                    Tem_Dat_X.Add(o.Circle.Min(p => p.Center_x));
                    Tem_Dat_Y.Add(o.Circle.Max(p => p.Center_y));
                    Tem_Dat_Y.Add(o.Circle.Min(p => p.Center_y));
                }
                if (o.LWPolyline.Count > 0)
                {
                    for (int i = 0; i < o.LWPolyline.Count; i++)
                    {
                        if (o.LWPolyline[i].Count >= 0)//判断数据大于零
                        {
                            Tem_Dat_X.Add(o.LWPolyline[i].Max(p => p.Start_x));
                            Tem_Dat_X.Add(o.LWPolyline[i].Min(p => p.Start_x));
                            Tem_Dat_X.Add(o.LWPolyline[i].Max(p => p.End_x));
                            Tem_Dat_X.Add(o.LWPolyline[i].Min(p => p.End_x));
                            Tem_Dat_Y.Add(o.LWPolyline[i].Max(p => p.Start_y));
                            Tem_Dat_Y.Add(o.LWPolyline[i].Min(p => p.Start_y));
                            Tem_Dat_Y.Add(o.LWPolyline[i].Max(p => p.End_y));
                            Tem_Dat_Y.Add(o.LWPolyline[i].Min(p => p.End_y));
                        }
                    }
                }
            }
            //计算返回坐标
            if ((Tem_Dat_X.Count <= 0) || (Tem_Dat_Y.Count <= 0))
            {
                Result = new Vector(0, 0);
            }
            else
            {
                Result = new Vector((Tem_Dat_X.Max() + Tem_Dat_X.Min()) / 2, (Tem_Dat_Y.Max() + Tem_Dat_Y.Min()) / 2);
            }
            return(Result);
        }
Example #35
0
        static void SetResult(DateTime now)
        {
            try
            {
                var screening = new DBC.Screening(now);
                //看看有没有预设当场结果
                if (screening.Preset != Enums.Fruits.None)
                {
                    screening.Result = screening.Preset;
                }
                //统计当场各种水果的数量
                else
                {
                    var list = new List <FruitCount>();
                    var sql  = string.Format("select sum(orange),sum(banana),sum(grape),sum(pineapple),sum(strawberry),sum(watermelon) from {0} where screeningid=?", DBTables.Betting);
                    var res  = DB.SExecuteReader(sql, screening.ID);
                    var row  = res[0];
                    list.Add(new FruitCount()
                    {
                        Fruit = Enums.Fruits.Orange, Count = Utility.ToInt32(row[0])
                    });
                    list.Add(new FruitCount()
                    {
                        Fruit = Enums.Fruits.Banana, Count = Utility.ToInt32(row[1])
                    });
                    list.Add(new FruitCount()
                    {
                        Fruit = Enums.Fruits.Grape, Count = Utility.ToInt32(row[2])
                    });
                    list.Add(new FruitCount()
                    {
                        Fruit = Enums.Fruits.Pineapple, Count = Utility.ToInt32(row[3])
                    });
                    list.Add(new FruitCount()
                    {
                        Fruit = Enums.Fruits.Strawberry, Count = Utility.ToInt32(row[4])
                    });
                    list.Add(new FruitCount()
                    {
                        Fruit = Enums.Fruits.Watermelon, Count = Utility.ToInt32(row[5])
                    });

                    var min  = list.Min(i => i.Count);
                    var same = list.Where(i => i.Count == min).ToList();
                    var rand = new Random();
                    screening.Result = same[rand.Next(same.Count)].Fruit;
                }

                //更新投注记录中的中奖额
                {
                    var sql = string.Format("update {0} set winning={1}*5 where screeningid=?", DBTables.Betting, screening.Result.ToString());
                    DB.SExecuteNonQuery(sql, screening.ID);
                }

                //更新中奖用户积分
                {
                    var sql = string.Format("update (select userid, winning from {0},{1} where screeningid=? and user.id=userid and user.role=?) as w, {0},user set points=points+w.winning where w.userid=user.id;", DBTables.Betting, DBTables.User);
                    DB.SExecuteNonQuery(sql, screening.ID, Enums.Roles.Normal);
                }
            }
            catch { }
        }
Example #36
0
 public static int MinScan <T>(this List <T> features) where T : MSFeatureLight
 {
     return(features.Min(feature => feature.Scan));
 }
Example #37
0
        public override void Render(ref ushort[,] canvas, ref RectangleF rect)
        {
            //double area = 0;
            int width  = canvas.GetLength(1);
            int height = canvas.GetLength(0);


            List <PointOnGrid> projectedPoints = ComputeProjection(stateVec, Vertices);

            if (IsWriteDebug)
            {
                File.WriteAllLines(
                    @"C:\Users\88felix\source\repos\MakeImagesForDescrimination\TempDebug\projectedPoints.csv",
                    projectedPoints.ToCSV());
            }

            if (projectedPoints.Count < 0.7 * Vertices.Count)
            {
                rect = RectangleF.Empty;
            }
            else
            {
                maxXShape = projectedPoints.Max(p => p.X);
                maxYShape = projectedPoints.Max(p => p.Y);
                minXShape = projectedPoints.Min(p => p.X);
                minYShape = projectedPoints.Min(p => p.Y);

                if (Logic.Settings.UseConcHull)
                {
                    double len = Math.Sqrt((maxXShape - minXShape) * (maxXShape - minXShape) +
                                           (maxYShape - minYShape) * (maxYShape - minYShape));
                    List <int> newCHull = ConvexHull.GetLocalConvex(projectedPoints, len / 10);
                    ushort[,] tempArray = new ushort[227, 227];

                    #region Obsolete, get convex hull by parts

                    // get convex hull by parts
                    //List<List<PointOnGrid>> convexHulls = new List<List<PointOnGrid>>();
                    //for (int ii = 1; ii < 10; ii++)
                    //{
                    //List<PointOnGrid> lstPart = (projectedPoints.Where(p => p.Component == ii)).ToList();
                    //if (lstPart.Count > 0)
                    //{
                    //    List<PointOnGrid> partialContour = ConvexHull.GetConvexHull(lstPart);
                    //    if (IsWriteDebug)
                    //        File.WriteAllLines(@"C:\Users\88felix\source\repos\MakeImagesForDescrimination\TempDebug\partialConv" + ii + ".csv", partialContour.ToCSV());

                    //    //PlotPoints(partialContour,ref tempArray);

                    //    convexHulls.Add(partialContour);
                    //}
                    //}
                    //List<PointOnGrid> mergedHull = MergeConvexHulls(convexHulls);

                    #endregion Obsolete, get convex hull by parts

                    List <PointOnGrid> mergedHull = GetPointsByIndex(projectedPoints, newCHull);
                    //mergedHull.CreateImage("c:\\temp\\temp.bmp");

                    //ShiftFromEdge(Vertices, canvas);


                    ScaleTargetAndAddToCanvas(canvas, mergedHull, oMaxMin, ref rect);
                }

                #region Obsolete, use cpp version of concave hull

                if (false)
                {
                    //List<PointOnGrid> reducedPoints = projectedPointsContour.Where((x, i) => i % 20 == 0).ToList();
                    //int[] hullPointsIndxs = reducedPoints.Select(point => point.Index).ToArray();
                    //strPoint[] outPoints = new strPoint[reducedPoints.Count];
                    //uint numHullPts = (uint)hullPointsIndxs.Length;
                    //uint numInputPoints = (uint)reducedPoints.Count;
                    //uint numOutPts = (uint)reducedPoints.Count;
                    //double concavity = 1;
                    //double lengthThresh = 1;//(uint)inPoints.Length;
                    //ConvexHull.pyconcaveman2d(projectedPoints.Cnvrt2strPnts(), numInputPoints, hullPointsIndxs, numHullPts,
                    //    concavity, lengthThresh, outPoints, ref numOutPts);
                }

                #endregion Obsolete, get convex hull by parts

                //}
                if (false) //fill by dense points
                {
                    ScaleTargetAndAddToCanvasNew(canvas, projectedPoints, oMaxMin, ref rect);
                }
            }
        }
        public void Interpolate()
        {
            //Node nt = GenerateFullTree();
            //string text1 = PrintTree(nt, "", "");
            //int index = 1;
            //Node result = RAlgorithm(nt, null, ref index);
            //text1 += "\n\n" + PrintTree(result, "", "");

            //Node no = new FuncNode(null, functions[1]);
            //(no as FuncNode).children.Add(new ConstNode(no, 2));
            //(no as FuncNode).children.Add(new FuncNode(no, functions[0]));
            //Node ch = (no as FuncNode).children[1];
            //(ch as FuncNode).children.Add(new ConstNode(ch, 1));
            //(ch as FuncNode).children.Add(new VariableNode(ch, variables[0]));

            //Node nM = Mutation(no);
            //text1 += "\n\n" + PrintTree(no, "", "");
            //text1 += "\n\n" + PrintTree(nM, "", "");

            Node   no    = GenerateFullTree();
            Node   no2   = GenerateFullTree();
            string text2 = PrintTree(no, "", "");

            text2 += "\n\n" + PrintTree(no2, "", "");
            List <Node> cr = Crossover(no, no2);

            //text2 += "\n\n" + PrintTree(no, "", "");
            //text2 += "\n\n" + PrintTree(no2, "", "");
            foreach (Node individual in cr)
            {
                text2 += "\n\n" + PrintTree(individual, "", "");
            }

            //var a = 1;

            //    //double e1 = individual.Evaluate(3);


            population = GeneratePopulation();
            int    iteration = 0;
            string tew       = "";

            foreach (Node individual in population)
            {
                //Node ne = Mutation(individual);

                tew += PrintTree(individual, "", "") + "\n\n";

                //double e1 = individual.Evaluate(3);
            }
            //foreach (Node individual in population)
            //{
            //    //Node ne = Mutation(individual);
            //    tew += PrintTree(individual, "", "") + "\n";
            //    //double e1 = individual.Evaluate(3);

            //}

            //var l = 1;


            absMinFunction = int.MaxValue;
            int counter = 0;

            do
            {
                List <double> calculatedFunction = population.Select(x => EvaluateIndividual(x)).ToList();
                double        newIterMinFunction = calculatedFunction.Min();
                minFuncEachIteration.Add(newIterMinFunction);//population.Select(ind => FitnessFunctionMulti(Converter.ConvertBitToMultiIntervals(intervalStarts, intervalEnds, maxLengthArr, ind))).Max();
                if (newIterMinFunction >= absMinFunction)
                {
                    counter++;
                }
                else
                {
                    counter        = 0;
                    absMinFunction = newIterMinFunction;
                    var indexOfMin = calculatedFunction.IndexOf(newIterMinFunction);
                    minArgument = population[indexOfMin];
                    //maxFunction = FitnessFunctionMulti(maxArgument);
                }
                List <Node> newPopulation = new List <Node>();
                newPopulation.AddRange(EliteAlgo());
                do
                {
                    List <Node> newIndividuals = Crossover(Select(), Select());
                    newIndividuals[0] = Mutation(newIndividuals[0]);
                    newIndividuals[1] = Mutation(newIndividuals[1]);
                    newPopulation.AddRange(newIndividuals);
                }while (newPopulation.Count < population.Count);
                population = new List <Node>(newPopulation);
                iteration++;
            }while (absMinFunction > eps);// counter <= maxIteration);
        }
        private void FourEdgedThickening(Node node, float thickness)
        {
            //this only work for nodes, which has four edges
            if (node.Edges.Count != 4)
            {
                throw new ArgumentException("Parameter node doesn't have exactly four edges", nameof(node));
            }

            bool majorWithMinor = false;

            //FIRST CALCULATE
            Edge edge1 = node.Edges[0];
            Edge edge2 = node.Edges[1];
            Edge edge3 = node.Edges[2];
            Edge edge4 = node.Edges[3];

            if (!(
                    graph.MajorEdges.Contains(edge1) &&
                    graph.MajorEdges.Contains(edge2) &&
                    graph.MajorEdges.Contains(edge3) &&
                    graph.MajorEdges.Contains(edge4)) &&
                !(
                    graph.MinorEdges.Contains(edge1) &&
                    graph.MinorEdges.Contains(edge2) &&
                    graph.MinorEdges.Contains(edge3) &&
                    graph.MinorEdges.Contains(edge4)))
            {
                majorWithMinor = true;
            }


            //radians from node
            float radian1 = edge1.NodeA == node ? edge1.DirRadianFromA : edge1.DirRadianFromB;
            float radian2 = edge2.NodeA == node ? edge2.DirRadianFromA : edge2.DirRadianFromB;
            float radian3 = edge3.NodeA == node ? edge3.DirRadianFromA : edge3.DirRadianFromB;
            float radian4 = edge4.NodeA == node ? edge4.DirRadianFromA : edge4.DirRadianFromB;

            List <float> radians = new List <float> {
                radian1, radian2, radian3, radian4
            };
            List <Edge> edges = new List <Edge> {
                edge1, edge2, edge3, edge4
            };
            List <Edge> sortedEdges = new List <Edge>();

            for (int i = radians.Count - 1; i > -1; i--)  //Get the edges sorted by their radians
            {
                float smallest = radians.Min();
                int   idx      = radians.IndexOf(smallest);
                sortedEdges.Add(edges[idx]);

                edges.RemoveAt(idx);
                radians.RemoveAt(idx);
            }

            //After sorting, we can determine the role of every edge
            Edge baseEdge1   = sortedEdges[0];
            Edge baseEdge2   = sortedEdges[2];
            Edge commonEdge1 = sortedEdges[1];
            Edge commonEdge2 = sortedEdges[3];

            float averageRadBase1Common1 = AverageRadianFromTwoEdges(baseEdge1, commonEdge1, node);
            float averageRadBase1Common2 = AverageRadianFromTwoEdges(baseEdge1, commonEdge2, node);
            float averageRadBase2Common1 = AverageRadianFromTwoEdges(baseEdge2, commonEdge1, node);
            float averageRadBase2Common2 = AverageRadianFromTwoEdges(baseEdge2, commonEdge2, node);

            if (!CorrectFourEdgedAverage(
                    averageRadBase1Common1, baseEdge1, baseEdge2, commonEdge2, node))
            {
                averageRadBase1Common1 += Mathf.PI;
            }
            if (!CorrectFourEdgedAverage(
                    averageRadBase1Common2, baseEdge1, baseEdge2, commonEdge1, node))
            {
                averageRadBase1Common2 += Mathf.PI;
            }
            if (!CorrectFourEdgedAverage(
                    averageRadBase2Common1, baseEdge2, baseEdge1, commonEdge2, node))
            {
                averageRadBase2Common1 += Mathf.PI;
            }
            if (!CorrectFourEdgedAverage(
                    averageRadBase2Common2, baseEdge2, baseEdge1, commonEdge1, node))
            {
                averageRadBase2Common2 += Mathf.PI;
            }

            //4 final vectors to use for thickening
            Vector2 vecB1C1;
            Vector2 vecB1C2;
            Vector2 vecB2C1;
            Vector2 vecB2C2;

            float radianDiffB1C1 = RadianDifferenceFromTwoEdges(baseEdge1, commonEdge1, node);
            float radianDiffB1C2 = RadianDifferenceFromTwoEdges(baseEdge1, commonEdge2, node);
            float radianDiffB2C1 = RadianDifferenceFromTwoEdges(baseEdge2, commonEdge1, node);
            float radianDiffB2C2 = RadianDifferenceFromTwoEdges(baseEdge2, commonEdge2, node);

            //If one of the crossing is a Major-Minor crossing, make the vectors in a different way:
            if ((graph.MajorEdges.Contains(baseEdge1) && graph.MinorEdges.Contains(commonEdge1)) ||
                (graph.MajorEdges.Contains(commonEdge1) && graph.MinorEdges.Contains(baseEdge1)))
            {
                vecB1C1 = MajorMinorCrossingThickening(baseEdge1, commonEdge1, node, radianDiffB1C1);
            }
            else
            {
                if (majorWithMinor && graph.MinorEdges.Contains(baseEdge1) && graph.MinorEdges.Contains(commonEdge1))
                {
                    vecB1C1 = new Vector2(
                        Mathf.Cos(averageRadBase1Common1) * thickness / 2 * (1f / Mathf.Sin(radianDiffB1C1 / 2)),
                        Mathf.Sin(averageRadBase1Common1) * thickness / 2 * (1f / Mathf.Sin(radianDiffB1C1 / 2)));
                }
                else
                {
                    vecB1C1 = new Vector2(
                        Mathf.Cos(averageRadBase1Common1) * thickness * (1f / Mathf.Sin(radianDiffB1C1 / 2)),
                        Mathf.Sin(averageRadBase1Common1) * thickness * (1f / Mathf.Sin(radianDiffB1C1 / 2)));
                }
            }

            if ((graph.MajorEdges.Contains(baseEdge1) && graph.MinorEdges.Contains(commonEdge2)) ||
                (graph.MajorEdges.Contains(commonEdge2) && graph.MinorEdges.Contains(baseEdge1)))
            {
                vecB1C2 = MajorMinorCrossingThickening(baseEdge1, commonEdge2, node, radianDiffB1C2);
            }
            else
            {
                if (majorWithMinor && graph.MinorEdges.Contains(baseEdge1) && graph.MinorEdges.Contains(commonEdge2))
                {
                    vecB1C2 = new Vector2(
                        Mathf.Cos(averageRadBase1Common2) * thickness / 2 * (1f / Mathf.Sin(radianDiffB1C2 / 2)),
                        Mathf.Sin(averageRadBase1Common2) * thickness / 2 * (1f / Mathf.Sin(radianDiffB1C2 / 2)));
                }
                else
                {
                    vecB1C2 = new Vector2(
                        Mathf.Cos(averageRadBase1Common2) * thickness * (1f / Mathf.Sin(radianDiffB1C2 / 2)),
                        Mathf.Sin(averageRadBase1Common2) * thickness * (1f / Mathf.Sin(radianDiffB1C2 / 2)));
                }
            }

            if ((graph.MajorEdges.Contains(baseEdge2) && graph.MinorEdges.Contains(commonEdge1)) ||
                (graph.MajorEdges.Contains(commonEdge1) && graph.MinorEdges.Contains(baseEdge2)))
            {
                vecB2C1 = MajorMinorCrossingThickening(baseEdge2, commonEdge1, node, radianDiffB2C1);
            }
            else
            {
                if (majorWithMinor && graph.MinorEdges.Contains(baseEdge2) && graph.MinorEdges.Contains(commonEdge1))
                {
                    vecB2C1 = new Vector2(
                        Mathf.Cos(averageRadBase2Common1) * thickness / 2 * (1f / Mathf.Sin(radianDiffB2C1 / 2)),
                        Mathf.Sin(averageRadBase2Common1) * thickness / 2 * (1f / Mathf.Sin(radianDiffB2C1 / 2)));
                }
                else
                {
                    vecB2C1 = new Vector2(
                        Mathf.Cos(averageRadBase2Common1) * thickness * (1f / Mathf.Sin(radianDiffB2C1 / 2)),
                        Mathf.Sin(averageRadBase2Common1) * thickness * (1f / Mathf.Sin(radianDiffB2C1 / 2)));
                }
            }

            if ((graph.MajorEdges.Contains(baseEdge2) && graph.MinorEdges.Contains(commonEdge2)) ||
                (graph.MajorEdges.Contains(commonEdge2) && graph.MinorEdges.Contains(baseEdge2)))
            {
                vecB2C2 = MajorMinorCrossingThickening(baseEdge2, commonEdge2, node, radianDiffB2C2);
            }
            else
            {
                if (majorWithMinor && graph.MinorEdges.Contains(baseEdge2) && graph.MinorEdges.Contains(commonEdge2))
                {
                    vecB2C2 = new Vector2(
                        Mathf.Cos(averageRadBase2Common2) * thickness / 2 * (1f / Mathf.Sin(radianDiffB2C2 / 2)),
                        Mathf.Sin(averageRadBase2Common2) * thickness / 2 * (1f / Mathf.Sin(radianDiffB2C2 / 2)));
                }
                else
                {
                    vecB2C2 = new Vector2(
                        Mathf.Cos(averageRadBase2Common2) * thickness * (1f / Mathf.Sin(radianDiffB2C2 / 2)),
                        Mathf.Sin(averageRadBase2Common2) * thickness * (1f / Mathf.Sin(radianDiffB2C2 / 2)));
                }
            }

            //THEN STORE IT
            BlockNode blockNodeB1C1 = new BlockNode(node.X + vecB1C1.x, node.Y + vecB1C1.y);
            BlockNode blockNodeB1C2 = new BlockNode(node.X + vecB1C2.x, node.Y + vecB1C2.y);
            BlockNode blockNodeB2C1 = new BlockNode(node.X + vecB2C1.x, node.Y + vecB2C1.y);
            BlockNode blockNodeB2C2 = new BlockNode(node.X + vecB2C2.x, node.Y + vecB2C2.y);

            blockNodeB1C1.Edges.Add(baseEdge1);
            blockNodeB1C1.Edges.Add(commonEdge1);
            blockNodeB1C2.Edges.Add(baseEdge1);
            blockNodeB1C2.Edges.Add(commonEdge2);
            blockNodeB2C1.Edges.Add(baseEdge2);
            blockNodeB2C1.Edges.Add(commonEdge1);
            blockNodeB2C2.Edges.Add(baseEdge2);
            blockNodeB2C2.Edges.Add(commonEdge2);

            node.BlockNodes.Add(blockNodeB1C1);
            node.BlockNodes.Add(blockNodeB1C2);
            node.BlockNodes.Add(blockNodeB2C1);
            node.BlockNodes.Add(blockNodeB2C2);

            BlockNodes.Add(blockNodeB1C1);
            BlockNodes.Add(blockNodeB1C2);
            BlockNodes.Add(blockNodeB2C1);
            BlockNodes.Add(blockNodeB2C2);
        }
Example #40
0
        public static void Executar()
        {
            var alunos = new List <Aluno>
            {
                new Aluno()
                {
                    Nome = "Pedro", Idade = 24, Nota = 8.0
                },
                new Aluno()
                {
                    Nome = "Andre", Idade = 21, Nota = 4.3
                },
                new Aluno()
                {
                    Nome = "Ana", Idade = 25, Nota = 9.5
                },
                new Aluno()
                {
                    Nome = "Jorge", Idade = 20, Nota = 8.5
                },
                new Aluno()
                {
                    Nome = "Ana", Idade = 21, Nota = 7.7
                },
                new Aluno()
                {
                    Nome = "Júlia", Idade = 22, Nota = 7.5
                },
                new Aluno()
                {
                    Nome = "Márcio", Idade = 18, Nota = 6.8
                },
            };

            var pedro = alunos.Single(aluno => aluno.Nome.Equals("Pedro"));

            Console.WriteLine($"{pedro.Nome} {pedro.Nota}");

            var fulano = alunos.SingleOrDefault(aluno => aluno.Nome.Equals("Fulano"));

            if (fulano == null)
            {
                Console.WriteLine("Aluno inexistente");
            }

            var ana = alunos.First(aluno => aluno.Nome.Equals("Ana"));

            Console.WriteLine($"{ana.Nome} {ana.Nota}");

            var sicrano = alunos.FirstOrDefault(aluno => aluno.Nota.Equals("Sicrano"));

            if (sicrano == null)
            {
                Console.WriteLine("Aluno inexistente");
            }

            var outraAna = alunos.LastOrDefault(aluno => aluno.Nome.Equals("Ana"));

            Console.WriteLine(outraAna.Nota);

            var exemploSkip = alunos.Skip(1).Take(3);

            foreach (var item in exemploSkip)
            {
                Console.WriteLine(item.Nome);
            }

            var maiorNota = alunos.Max(aluno => aluno.Nota);

            Console.WriteLine(maiorNota);

            var menorNota = alunos.Min(aluno => aluno.Nota);

            Console.WriteLine(menorNota);

            var somatorioNotas = alunos.Sum(aluno => aluno.Nota);

            Console.WriteLine(somatorioNotas);

            var mediaDosAprovados = alunos
                                    .Where(a => a.Nota >= 7.0)
                                    .Average(aluno => aluno.Nota);

            Console.WriteLine(mediaDosAprovados);
        }
Example #41
0
        private void buttonLinqLambda_Click(object sender, EventArgs e)
        {
            var contas = new List <Conta>();

            contas.Add(ContaComSaldo(2001));
            contas.Add(ContaComSaldo(2800));
            contas.Add(ContaComSaldo(1800));
            contas.Add(ContaComSaldo(4000));
            contas.Add(ContaComSaldo(200));

            var filtradas = from c in contas
                            where c.Saldo > 2000
                            select c;

            //               ^ LINQ = Uma espécie de comando de banco dentro de listas diretamente no código.
            foreach (Conta c in filtradas)
            {
                MessageBox.Show("R$" + c.Saldo.ToString("n2"));
            }

            double somaSaldo = filtradas.Sum(c => c.Saldo);

            //                               ^ LAMBDA = Função que aponta (=>) um atributo de um elemento.
            MessageBox.Show("Total: R$" + somaSaldo.ToString("n2"));

            MessageBox.Show("Menor: R$" + contas.Min(c => c.Saldo).ToString("n2"));

            MessageBox.Show("Maior: R$" + contas.Max(c => c.Saldo).ToString("n2"));

            //var filtrados = lista.Where(c => c.Numero < 1000 && c.Saldo > 5000.0);
            //                     ^ Método que seleciona listas        ^ Exemplo de Lambda.

            MessageBox.Show(contas.Count(c => c.Saldo > 2000) + " contas com saldo maior que R$2000,00.");

            //PROJEÇÃO - Criando novo objeto na seleção apenas com atributos que queremos:
            var nomeagenciafiltro = from c in contas
                                    where c.Saldo > 2000
                                    /* Cria novo objeto:*/ select new { c.Titular.Nome, c.Agencia };

            foreach (var c in nomeagenciafiltro)
            {
                MessageBox.Show("Nome: " + c.Nome + "\nAgência: " + c.Agencia);
            }

            //LINQ + Arrays:
            int[] nros = { 1, 20, 3, 87, 4, 9, 11 };

            MessageBox.Show(nros.Where(x => x > 10).Count() + " números maiores que 10 nesta array."
                            + "\nSoma: " + nros.Where(x => x > 10).Sum());

            //orderby em LINQ:
            var ordenadasPorSaldoDesc = from c in contas
                                        where c.Saldo > 2000 //, c.Numero <- Se adicionarmos outros critérios por virgula,
                                                             //serão utilizados em caso de igualdade no primeiro.
                                                             // ^ Alternativa em método: contas.Orderby(crit1).ThenBy(crit2);
                                        orderby c.Saldo descending
                                        select c;

            //Alternativa - WHERE e ORDERBY em Métodos:
            ordenadasPorSaldoDesc = contas.Where(c => c.Saldo > 2000).OrderByDescending(c => c.Saldo);

            foreach (var c in ordenadasPorSaldoDesc)
            {
                MessageBox.Show(c.Saldo.ToString("n2"));
            }
        }
Example #42
0
        public static Tuple <DesignItem, Rect> WrapItemsNewContainer(IEnumerable <DesignItem> items, Type containerType, bool doInsert = true)
        {
            var collection = items;

            var _context = collection.First().Context as XamlDesignContext;

            var container = collection.First().Parent;

            if (collection.Any(x => x.Parent != container))
            {
                return(null);
            }

            //Change Code to use the Placment Operation!
            var placement = container.Extensions.OfType <IPlacementBehavior>().FirstOrDefault();

            if (placement == null)
            {
                return(null);
            }

            var operation = PlacementOperation.Start(items.ToList(), PlacementType.Move);

            var        newInstance = _context.Services.ExtensionManager.CreateInstanceWithCustomInstanceFactory(containerType, null);
            DesignItem newPanel    = _context.Services.Component.RegisterComponentForDesigner(newInstance);

            List <ItemPos> itemList = new List <ItemPos>();

            foreach (var item in collection)
            {
                itemList.Add(GetItemPos(operation, item));
                //var pos = placement.GetPosition(null, item);
                if (container.Component is Canvas)
                {
                    item.Properties.GetAttachedProperty(Canvas.RightProperty).Reset();
                    item.Properties.GetAttachedProperty(Canvas.LeftProperty).Reset();
                    item.Properties.GetAttachedProperty(Canvas.TopProperty).Reset();
                    item.Properties.GetAttachedProperty(Canvas.BottomProperty).Reset();
                }
                else if (container.Component is Grid)
                {
                    item.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).Reset();
                    item.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).Reset();
                    item.Properties.GetProperty(FrameworkElement.MarginProperty).Reset();
                }

                var parCol = item.ParentProperty.CollectionElements;
                parCol.Remove(item);
            }

            var xmin = itemList.Min(x => x.Xmin);
            var xmax = itemList.Max(x => x.Xmax);
            var ymin = itemList.Min(x => x.Ymin);
            var ymax = itemList.Max(x => x.Ymax);

            foreach (var item in itemList)
            {
                if (newPanel.Component is Canvas)
                {
                    if (item.HorizontalAlignment == HorizontalAlignment.Right)
                    {
                        item.DesignItem.Properties.GetAttachedProperty(Canvas.RightProperty).SetValue(xmax - item.Xmax);
                    }
                    else
                    {
                        item.DesignItem.Properties.GetAttachedProperty(Canvas.LeftProperty).SetValue(item.Xmin - xmin);
                    }

                    if (item.VerticalAlignment == VerticalAlignment.Bottom)
                    {
                        item.DesignItem.Properties.GetAttachedProperty(Canvas.BottomProperty).SetValue(ymax - item.Ymax);
                    }
                    else
                    {
                        item.DesignItem.Properties.GetAttachedProperty(Canvas.TopProperty).SetValue(item.Ymin - ymin);
                    }

                    newPanel.ContentProperty.CollectionElements.Add(item.DesignItem);
                }
                else if (newPanel.Component is Grid)
                {
                    Thickness thickness = new Thickness(0);
                    if (item.HorizontalAlignment == HorizontalAlignment.Right)
                    {
                        item.DesignItem.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).SetValue(HorizontalAlignment.Right);
                        thickness.Right = xmax - item.Xmax;
                    }
                    else
                    {
                        item.DesignItem.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).SetValue(HorizontalAlignment.Left);
                        thickness.Left = item.Xmin - xmin;
                    }

                    if (item.VerticalAlignment == VerticalAlignment.Bottom)
                    {
                        item.DesignItem.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).SetValue(VerticalAlignment.Bottom);
                        thickness.Bottom = ymax - item.Ymax;
                    }
                    else
                    {
                        item.DesignItem.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).SetValue(VerticalAlignment.Top);
                        thickness.Top = item.Ymin - ymin;
                    }

                    item.DesignItem.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(thickness);

                    newPanel.ContentProperty.CollectionElements.Add(item.DesignItem);
                }
                else if (newPanel.Component is Viewbox)
                {
                    newPanel.ContentProperty.SetValue(item.DesignItem);
                }
            }

            if (doInsert)
            {
                PlacementOperation operation2 = PlacementOperation.TryStartInsertNewComponents(
                    container,
                    new[] { newPanel },
                    new[] { new Rect(xmin, ymin, xmax - xmin, ymax - ymin).Round() },
                    PlacementType.AddItem
                    );

                operation2.Commit();

                _context.Services.Selection.SetSelectedComponents(new[] { newPanel });
            }

            operation.Commit();

            return(new Tuple <DesignItem, Rect>(newPanel, new Rect(xmin, ymin, xmax - xmin, ymax - ymin).Round()));
        }
Example #43
0
        public static void ArrangeItems(IEnumerable <DesignItem> items, ArrangeDirection arrangeDirection)
        {
            var collection = items;

            var _context = collection.First().Context as XamlDesignContext;

            var container = collection.First().Parent;

            if (collection.Any(x => x.Parent != container))
            {
                return;
            }

            var placement = container.Extensions.OfType <IPlacementBehavior>().FirstOrDefault();

            if (placement == null)
            {
                return;
            }

            var operation = PlacementOperation.Start(items.ToList(), PlacementType.Move);

            List <ItemPos> itemList = new List <ItemPos>();

            foreach (var item in collection)
            {
                itemList.Add(GetItemPos(operation, item));
            }

            var xmin  = itemList.Min(x => x.Xmin);
            var xmax  = itemList.Max(x => x.Xmax);
            var mpos  = (xmax - xmin) / 2 + xmin;
            var ymin  = itemList.Min(x => x.Ymin);
            var ymax  = itemList.Max(x => x.Ymax);
            var ympos = (ymax - ymin) / 2 + ymin;

            foreach (var item in collection)
            {
                switch (arrangeDirection)
                {
                case ArrangeDirection.Left:
                {
                    if (container.Component is Canvas)
                    {
                        if (!item.Properties.GetAttachedProperty(Canvas.RightProperty).IsSet)
                        {
                            item.Properties.GetAttachedProperty(Canvas.LeftProperty).SetValue(xmin);
                        }
                        else
                        {
                            var pos = (double)((Panel)item.Parent.Component).ActualWidth - (xmin + (double)((FrameworkElement)item.Component).ActualWidth);
                            item.Properties.GetAttachedProperty(Canvas.RightProperty).SetValue(pos);
                        }
                    }
                    else if (container.Component is Grid)
                    {
                        if ((HorizontalAlignment)item.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).ValueOnInstance != HorizontalAlignment.Right)
                        {
                            var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
                            margin.Left = xmin;
                            item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
                        }
                        else
                        {
                            var pos    = (double)((Panel)item.Parent.Component).ActualWidth - (xmin + (double)((FrameworkElement)item.Component).ActualWidth);
                            var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
                            margin.Right = pos;
                            item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
                        }
                    }
                }
                break;

                case ArrangeDirection.HorizontalMiddle:
                {
                    if (container.Component is Canvas)
                    {
                        if (!item.Properties.GetAttachedProperty(Canvas.RightProperty).IsSet)
                        {
                            if (!item.Properties.GetAttachedProperty(Canvas.RightProperty).IsSet)
                            {
                                item.Properties.GetAttachedProperty(Canvas.LeftProperty).SetValue(mpos - (((FrameworkElement)item.Component).ActualWidth) / 2);
                            }
                            else
                            {
                                var pp  = mpos - (((FrameworkElement)item.Component).ActualWidth) / 2;
                                var pos = (double)((Panel)item.Parent.Component).ActualWidth - pp - (((FrameworkElement)item.Component).ActualWidth);
                                item.Properties.GetAttachedProperty(Canvas.RightProperty).SetValue(pos);
                            }
                        }
                    }
                    else if (container.Component is Grid)
                    {
                        if ((HorizontalAlignment)item.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).ValueOnInstance != HorizontalAlignment.Right)
                        {
                            var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
                            margin.Left = mpos - (((FrameworkElement)item.Component).ActualWidth) / 2;
                            item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
                        }
                        else
                        {
                            var pp     = mpos - (((FrameworkElement)item.Component).ActualWidth) / 2;
                            var pos    = (double)((Panel)item.Parent.Component).ActualWidth - pp - (((FrameworkElement)item.Component).ActualWidth);
                            var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
                            margin.Right = pos;
                            item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
                        }
                    }
                }
                break;

                case ArrangeDirection.Right:
                {
                    if (container.Component is Canvas)
                    {
                        if (!item.Properties.GetAttachedProperty(Canvas.RightProperty).IsSet)
                        {
                            var pos = xmax - (double)((FrameworkElement)item.Component).ActualWidth;
                            item.Properties.GetAttachedProperty(Canvas.LeftProperty).SetValue(pos);
                        }
                        else
                        {
                            var pos = (double)((Panel)item.Parent.Component).ActualWidth - xmax;
                            item.Properties.GetAttachedProperty(Canvas.RightProperty).SetValue(pos);
                        }
                    }
                    else if (container.Component is Grid)
                    {
                        if ((HorizontalAlignment)item.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).ValueOnInstance != HorizontalAlignment.Right)
                        {
                            var pos    = xmax - (double)((FrameworkElement)item.Component).ActualWidth;
                            var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
                            margin.Left = pos;
                            item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
                        }
                        else
                        {
                            var pos    = (double)((Panel)item.Parent.Component).ActualWidth - xmax;
                            var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
                            margin.Right = pos;
                            item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
                        }
                    }
                }
                break;

                case ArrangeDirection.Top:
                {
                    if (container.Component is Canvas)
                    {
                        if (!item.Properties.GetAttachedProperty(Canvas.BottomProperty).IsSet)
                        {
                            item.Properties.GetAttachedProperty(Canvas.TopProperty).SetValue(ymin);
                        }
                        else
                        {
                            var pos = (double)((Panel)item.Parent.Component).ActualHeight - (ymin + (double)((FrameworkElement)item.Component).ActualHeight);
                            item.Properties.GetAttachedProperty(Canvas.BottomProperty).SetValue(pos);
                        }
                    }
                    else if (container.Component is Grid)
                    {
                        if ((VerticalAlignment)item.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).ValueOnInstance != VerticalAlignment.Bottom)
                        {
                            item.Properties.GetAttachedProperty(Canvas.TopProperty).SetValue(ymin);
                            var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
                            margin.Top = ymin;
                            item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
                        }
                        else
                        {
                            var pos    = (double)((Panel)item.Parent.Component).ActualHeight - (ymin + (double)((FrameworkElement)item.Component).ActualHeight);
                            var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
                            margin.Bottom = pos;
                            item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
                        }
                    }
                }
                break;

                case ArrangeDirection.VerticalMiddle:
                {
                    if (container.Component is Canvas)
                    {
                        if (!item.Properties.GetAttachedProperty(Canvas.BottomProperty).IsSet)
                        {
                            item.Properties.GetAttachedProperty(Canvas.TopProperty).SetValue(ympos - (((FrameworkElement)item.Component).ActualHeight) / 2);
                        }
                        else
                        {
                            var pp  = mpos - (((FrameworkElement)item.Component).ActualHeight) / 2;
                            var pos = (double)((Panel)item.Parent.Component).ActualHeight - pp - (((FrameworkElement)item.Component).ActualHeight);
                            item.Properties.GetAttachedProperty(Canvas.BottomProperty).SetValue(pos);
                        }
                    }
                    else if (container.Component is Grid)
                    {
                        if ((VerticalAlignment)item.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).ValueOnInstance != VerticalAlignment.Bottom)
                        {
                            var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
                            margin.Top = ympos - (((FrameworkElement)item.Component).ActualHeight) / 2;
                            item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
                        }
                        else
                        {
                            var pp     = mpos - (((FrameworkElement)item.Component).ActualHeight) / 2;
                            var pos    = (double)((Panel)item.Parent.Component).ActualHeight - pp - (((FrameworkElement)item.Component).ActualHeight);
                            var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
                            margin.Bottom = pos;
                            item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
                        }
                    }
                }
                break;

                case ArrangeDirection.Bottom:
                {
                    if (container.Component is Canvas)
                    {
                        if (!item.Properties.GetAttachedProperty(Canvas.BottomProperty).IsSet)
                        {
                            var pos = ymax - (double)((FrameworkElement)item.Component).ActualHeight;
                            item.Properties.GetAttachedProperty(Canvas.TopProperty).SetValue(pos);
                        }
                        else
                        {
                            var pos = (double)((Panel)item.Parent.Component).ActualHeight - ymax;
                            item.Properties.GetAttachedProperty(Canvas.BottomProperty).SetValue(pos);
                        }
                    }
                    else if (container.Component is Grid)
                    {
                        if ((VerticalAlignment)item.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).ValueOnInstance != VerticalAlignment.Bottom)
                        {
                            var pos    = ymax - (double)((FrameworkElement)item.Component).ActualHeight;
                            var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
                            margin.Top = pos;
                            item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
                        }
                        else
                        {
                            var pos    = (double)((Panel)item.Parent.Component).ActualHeight - ymax;
                            var margin = (Thickness)item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance;
                            margin.Bottom = pos;
                            item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin);
                        }
                    }
                }
                break;
                }
            }

            operation.Commit();
        }
Example #44
0
        public double Minbul(List <double> mamsonuclar)
        {
            double min = mamsonuclar.Min();

            return(min);
        }
Example #45
0
        public void AuthorUsesCases()
        {
            var ev = OrmLiteConfig.DialectProvider.SqlExpression <Author>();

            using (var db = OpenDbConnection())
            {
                int year     = DateTime.Today.AddYears(-20).Year;
                var lastDay  = new DateTime(year, 12, 31);
                int expected = 5;

                ev.Where(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= lastDay);
                List <Author> result = db.Select(ev);
                Assert.AreEqual(expected, result.Count);
                result = db.Select(db.From <Author>().Where(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= lastDay));
                Assert.AreEqual(expected, result.Count);
                result = db.Select <Author>(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= lastDay);
                Assert.AreEqual(expected, result.Count);
                Author a = new Author()
                {
                    Birthday = lastDay
                };
                result = db.Select <Author>(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= a.Birthday);
                Assert.AreEqual(expected, result.Count);

                // select authors from London, Berlin and Madrid : 6
                expected = 6;
                //Sql.In can take params object[]
                var city = "Berlin";
                ev.Where().Where(rn => Sql.In(rn.City, "London", "Madrid", city));
                result = db.Select(ev);
                Assert.AreEqual(expected, result.Count);
                result = db.Select <Author>(rn => Sql.In(rn.City, new[] { "London", "Madrid", "Berlin" }));
                Assert.AreEqual(expected, result.Count);

                // select authors from Bogota and Cartagena : 7
                expected = 7;
                //... or Sql.In can  take List<Object>
                city = "Bogota";
                List <Object> cities = new List <Object>();
                cities.Add(city);
                cities.Add("Cartagena");
                ev.Where().Where(rn => Sql.In(rn.City, cities));
                result = db.Select(ev);
                Assert.AreEqual(expected, result.Count);
                result = db.Select <Author>(rn => Sql.In(rn.City, "Bogota", "Cartagena"));
                Assert.AreEqual(expected, result.Count);


                // select authors which name starts with A
                expected = 3;
                ev.Where().Where(rn => rn.Name.StartsWith("A"));
                result = db.Select(ev);
                Assert.AreEqual(expected, result.Count);
                result = db.Select <Author>(rn => rn.Name.StartsWith("A"));
                Assert.AreEqual(expected, result.Count);

                // select authors which name ends with Garzon o GARZON o garzon ( no case sensitive )
                expected = 3;
                var name = "GARZON";
                ev.Where().Where(rn => rn.Name.ToUpper().EndsWith(name));
                result = db.Select(ev);
                Assert.AreEqual(expected, result.Count);
                result = db.Select <Author>(rn => rn.Name.ToUpper().EndsWith(name));
                Assert.AreEqual(expected, result.Count);

                // select authors which name ends with garzon
                //A percent symbol ("%") in the LIKE pattern matches any sequence of zero or more characters
                //in the string.
                //An underscore ("_") in the LIKE pattern matches any single character in the string.
                //Any other character matches itself or its lower/upper case equivalent (i.e. case-insensitive matching).
                expected = 3;
                ev.Where().Where(rn => rn.Name.EndsWith("garzon"));
                result = db.Select(ev);
                Assert.AreEqual(expected, result.Count);
                result = db.Select <Author>(rn => rn.Name.EndsWith("garzon"));
                Assert.AreEqual(expected, result.Count);


                // select authors which name contains  Benedict
                expected = 2;
                name     = "Benedict";
                ev.Where().Where(rn => rn.Name.Contains(name));
                result = db.Select(ev);
                Assert.AreEqual(expected, result.Count);
                result = db.Select <Author>(rn => rn.Name.Contains("Benedict"));
                Assert.AreEqual(expected, result.Count);
                a.Name = name;
                result = db.Select <Author>(rn => rn.Name.Contains(a.Name));
                Assert.AreEqual(expected, result.Count);


                // select authors with Earnings <= 50
                expected = 3;
                var earnings = 50;
                ev.Where().Where(rn => rn.Earnings <= earnings);
                result = db.Select(ev);
                Assert.AreEqual(expected, result.Count);
                result = db.Select <Author>(rn => rn.Earnings <= 50);
                Assert.AreEqual(expected, result.Count);

                // select authors with Rate = 10 and city=Mexio
                expected = 1;
                city     = "Mexico";
                ev.Where().Where(rn => rn.Rate == 10 && rn.City == city);
                result = db.Select(ev);
                Assert.AreEqual(expected, result.Count);
                result = db.Select <Author>(rn => rn.Rate == 10 && rn.City == "Mexico");
                Assert.AreEqual(expected, result.Count);

                a.City = city;
                result = db.Select <Author>(rn => rn.Rate == 10 && rn.City == a.City);
                Assert.AreEqual(expected, result.Count);

                //  enough selecting, lets update;
                // set Active=false where rate =0
                expected = 2;
                var rate = 0;
                ev.Where().Where(rn => rn.Rate == rate).Update(rn => rn.Active);
                var rows = db.UpdateOnly(new Author()
                {
                    Active = false
                }, ev);
                Assert.AreEqual(expected, rows);

                // insert values  only in Id, Name, Birthday, Rate and Active fields
                expected = 4;
                db.InsertOnly(new Author()
                {
                    Active = false, Rate = 0, Name = "Victor Grozny", Birthday = DateTime.Today.AddYears(-18)
                }, rn => new { rn.Id, rn.Name, rn.Birthday, rn.Active, rn.Rate });
                db.InsertOnly(new Author()
                {
                    Active = false, Rate = 0, Name = "Ivan Chorny", Birthday = DateTime.Today.AddYears(-19)
                }, rn => new { rn.Id, rn.Name, rn.Birthday, rn.Active, rn.Rate });
                ev.Where().Where(rn => !rn.Active);
                result = db.Select(ev);
                Assert.AreEqual(expected, result.Count);

                //update comment for City == null
                expected = 2;
                ev.Where().Where(rn => rn.City == null).Update(rn => rn.Comments);
                rows = db.UpdateOnly(new Author()
                {
                    Comments = "No comments"
                }, ev);
                Assert.AreEqual(expected, rows);

                // delete where City is null
                expected = 2;
                rows     = db.Delete(ev);
                Assert.AreEqual(expected, rows);


                //   lets select  all records ordered by Rate Descending and Name Ascending
                expected = 14;
                ev.Where().OrderBy(rn => new { at = Sql.Desc(rn.Rate), rn.Name }); // clear where condition
                result = db.Select(ev);
                Assert.AreEqual(expected, result.Count);
                var author = result.FirstOrDefault();
                Assert.AreEqual("Claudia Espinel", author.Name);

                // select  only first 5 rows ....
                expected = 5;
                ev.Limit(5); // note: order is the same as in the last sentence
                result = db.Select(ev);
                Assert.AreEqual(expected, result.Count);


                // and finally lets select only Name and City (name will be "UPPERCASED" )

                ev.Select(rn => new { at = Sql.As(rn.Name.ToUpper(), "Name"), rn.City });
                Console.WriteLine(ev.SelectExpression);
                result = db.Select(ev);
                author = result.FirstOrDefault();
                Assert.AreEqual("Claudia Espinel".ToUpper(), author.Name);

                ev.Select(rn => new { at = Sql.As(rn.Name.ToUpper(), rn.Name), rn.City });
                Console.WriteLine(ev.SelectExpression);
                result = db.Select(ev);
                author = result.FirstOrDefault();
                Assert.AreEqual("Claudia Espinel".ToUpper(), author.Name);

                //paging :
                ev.Limit(0, 4);// first page, page size=4;
                result = db.Select(ev);
                author = result.FirstOrDefault();
                Assert.AreEqual("Claudia Espinel".ToUpper(), author.Name);

                ev.Limit(4, 4);// second page
                result = db.Select(ev);
                author = result.FirstOrDefault();
                Assert.AreEqual("Jorge Garzon".ToUpper(), author.Name);

                ev.Limit(8, 4);// third page
                result = db.Select(ev);
                author = result.FirstOrDefault();
                Assert.AreEqual("Rodger Contreras".ToUpper(), author.Name);

                // select distinct..
                ev.Limit().OrderBy(); // clear limit, clear orde
                ev.SelectDistinct(r => r.City);
                expected = 6;
                result   = db.Select(ev);
                Assert.AreEqual(expected, result.Count);

                // select distinct with limit
                ev.Limit(0, 4);
                ev.SelectDistinct(r => r.City);
                expected = 4;
                result   = db.Select(ev);
                Assert.AreEqual(expected, result.Count);

                ev.Select(r => Sql.As(Sql.Max(r.Birthday), "Birthday"));
                result = db.Select(ev);
                var expectedResult = authors.Max(r => r.Birthday);
                Assert.AreEqual(expectedResult, result[0].Birthday);

                ev.Select(r => Sql.As(Sql.Max(r.Birthday), r.Birthday));
                result         = db.Select(ev);
                expectedResult = authors.Max(r => r.Birthday);
                Assert.AreEqual(expectedResult, result[0].Birthday);

                var r1 = db.Single(ev);
                Assert.AreEqual(expectedResult, r1.Birthday);

                var r2 = db.Scalar <Author, DateTime>(e => Sql.Max(e.Birthday));
                Assert.AreEqual(expectedResult, r2);

                ev.Select(r => Sql.As(Sql.Min(r.Birthday), "Birthday"));
                result         = db.Select(ev);
                expectedResult = authors.Min(r => r.Birthday);
                Assert.AreEqual(expectedResult, result[0].Birthday);

                ev.Select(r => Sql.As(Sql.Min(r.Birthday), r.Birthday));
                result         = db.Select(ev);
                expectedResult = authors.Min(r => r.Birthday);
                Assert.AreEqual(expectedResult, result[0].Birthday);


                ev.Select(r => new { r.City, MaxResult = Sql.As(Sql.Min(r.Birthday), "Birthday") })
                .GroupBy(r => r.City)
                .OrderBy(r => r.City);
                result = db.Select(ev);
                var expectedStringResult = "Berlin";
                Assert.AreEqual(expectedStringResult, result[0].City);

                ev.Select(r => new { r.City, MaxResult = Sql.As(Sql.Min(r.Birthday), r.Birthday) })
                .GroupBy(r => r.City)
                .OrderBy(r => r.City);
                result = db.Select(ev);
                expectedStringResult = "Berlin";
                Assert.AreEqual(expectedStringResult, result[0].City);

                r1 = db.Single(ev);
                Assert.AreEqual(expectedStringResult, r1.City);

                var     expectedDecimal = authors.Max(e => e.Earnings);
                Decimal?r3 = db.Scalar <Author, Decimal?>(e => Sql.Max(e.Earnings));
                Assert.AreEqual(expectedDecimal, r3.Value);

                var    expectedString = authors.Max(e => e.Name);
                string r4             = db.Scalar <Author, String>(e => Sql.Max(e.Name));
                Assert.AreEqual(expectedString, r4);

                var      expectedDate = authors.Max(e => e.LastActivity);
                DateTime?r5           = db.Scalar <Author, DateTime?>(e => Sql.Max(e.LastActivity));
                Assert.AreEqual(expectedDate, r5);

                var      expectedDate51 = authors.Where(e => e.City == "Bogota").Max(e => e.LastActivity);
                DateTime?r51            = db.Scalar <Author, DateTime?>(
                    e => Sql.Max(e.LastActivity),
                    e => e.City == "Bogota");
                Assert.AreEqual(expectedDate51, r51);

                try
                {
                    var  expectedBool = authors.Max(e => e.Active);
                    bool r6           = db.Scalar <Author, bool>(e => Sql.Max(e.Active));
                    Assert.AreEqual(expectedBool, r6);
                }
                catch //(Exception e)
                {
                    //????
                    //if (dialect.Name == "PostgreSQL")
                    //    Console.WriteLine("OK PostgreSQL: " + e.Message);
                    //else
                    //    Console.WriteLine("**************  FAILED *************** " + e.Message);
                }



                // Tests for predicate overloads that make use of the expression visitor
                author = db.Single <Author>(q => q.Name == "Jorge Garzon");

                try
                {
                    author = db.Single <Author>(q => q.Name == "Does not exist");
                    Assert.Fail();
                }
                catch
                {
                    //"Expected exception thrown, OK? True"
                }

                author = db.Single <Author>(q => q.Name == "Does not exist");
                Assert.IsNull(author);

                author = db.Single <Author>(q => q.City == "Bogota");
                Assert.AreEqual("Angel Colmenares", author.Name);

                a.City = "Bogota";
                author = db.Single <Author>(q => q.City == a.City);
                Assert.AreEqual("Angel Colmenares", author.Name);

                // count test

                var  expectedCount = authors.Count();
                long r7            = db.Scalar <Author, long>(e => Sql.Count(e.Id));
                Assert.AreEqual(expectedCount, r7);

                expectedCount = authors.Count(e => e.City == "Bogota");
                r7            = db.Scalar <Author, long>(
                    e => Sql.Count(e.Id),
                    e => e.City == "Bogota");
                Assert.AreEqual(expectedCount, r7);

                ev.Update();// all fields will be updated
                // select and update
                expected = 1;
                var rr = db.Single <Author>(rn => rn.Name == "Luis garzon");
                rr.City     = "Madrid";
                rr.Comments = "Updated";
                ev.Where().Where(r => r.Id == rr.Id); // if omit,  then all records will be updated
                rows = db.UpdateOnly(rr, ev);         // == dbCmd.Update(rr) but it returns void
                Assert.AreEqual(expected, rows);

                expected = 0;
                ev.Where().Where(r => r.City == "Ciudad Gotica");
                rows = db.UpdateOnly(rr, ev);
                Assert.AreEqual(expected, rows);

                expected = db.Select <Author>(x => x.City == "Madrid").Count;
                author   = new Author()
                {
                    Active = false
                };
                rows = db.UpdateOnly(author, x => x.Active, x => x.City == "Madrid");
                Assert.AreEqual(expected, rows);

                expected = db.Select <Author>(x => x.Active == false).Count;
                rows     = db.Delete <Author>(x => x.Active == false);
                Assert.AreEqual(expected, rows);

                // Sql.In(empty array) and Sql.In(null) should evaluate to false rather than failing

                expected = 0;
                result   = db.Select <Author>(rn => Sql.In(rn.City, new string[0]));
                Assert.AreEqual(expected, result.Count);
                result = db.Select <Author>(rn => Sql.In(rn.City, (string[])null));
                Assert.AreEqual(expected, result.Count);
            }
        }
Example #46
0
        public static void Day7()
        {
            var filePath = CurrentDirectory.ToString() + "/Day8/resources/input.txt";
            var lines    = System.IO.File.ReadAllLines(filePath);

            List <int> instructions = lines.First().Select(char.ToString).Select(int.Parse).ToList();

            var layers     = GetLayers(instructions);
            var layerCount = layers.Values.First().Count;

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

            for (var i = 0; i < layerCount; i++)
            {
                count0s.Add(0);
            }


            foreach (var pixel in layers.Values)
            {
                for (var layer = 0; layer < layerCount; layer++)
                {
                    if (pixel[layer] == 0)
                    {
                        count0s[layer]++;
                    }
                }
            }

            var least0s = count0s.IndexOf(count0s.Min());
            int count1s = 0;

            foreach (var pixel in layers.Values)
            {
                if (pixel[least0s] == 1)
                {
                    count1s++;
                }
            }

            int count2s = 0;

            foreach (var pixel in layers.Values)
            {
                if (pixel[least0s] == 2)
                {
                    count2s++;
                }
            }
            Console.WriteLine("Day 8: Problem 1: " + count2s * count1s);

            var resolvedPicture = new Dictionary <(int, int), int>();

            foreach (var position in layers.Keys)
            {
                resolvedPicture.Add(position, DetermineColor(layers[position]));
            }

            Console.WriteLine("Day 8: Problem 2: ");

            for (var i = 0; i < HEIGHT; i++)
            {
                Console.WriteLine(String.Join("", resolvedPicture.Where((position) => position.Key.Item2 == i)
                                              .Select(position => position.Value == 0 ? " " : "1")
                                              .ToList()));
            }
        }
Example #47
0
        public ManorDataModel GetAllManorDataModel()
        {
            ManorDataModel      tempDataModel     = new ManorDataModel();
            List <IPeopleModel> tempPeopleModel   = new List <IPeopleModel>();
            List <VillageModel> tempVillageModels = new List <VillageModel>();

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

            for (int x = 1; x < _fiefService.ManorList.Count; x++)
            {
                tempDataModel.ManorPopulation += _fiefService.ManorList[x].ManorPopulation;
                tempDataModel.ManorAcres      += _fiefService.ManorList[x].ManorAcres;
                tempDataModel.ManorPasture    += _fiefService.ManorList[x].ManorPasture;
                tempDataModel.ManorArable     += _fiefService.ManorList[x].ManorArable;
                tempDataModel.ManorWoodland   += _fiefService.ManorList[x].ManorWoodland;
                tempDataModel.ManorFelling    += _fiefService.ManorList[x].ManorFelling;
                tempDataModel.ManorUseless    += _fiefService.ManorList[x].ManorUseless;

                wealth.Add(Convert.ToInt32(_fiefService.ManorList[x].ManorWealth));
            }

            tempDataModel.ManorWealth = wealth.Min()
                                        == wealth.Max()
                ? $"{wealth.Min()}"
                : $"{wealth.Min()} - {wealth.Max()}";

            for (int x = 1; x < _fiefService.ArmyList.Count; x++)
            {
                for (int y = 0; y < _fiefService.ArmyList[x].TemplarKnightsList.Count; y++)
                {
                    tempPeopleModel.Add(_fiefService.ArmyList[x].TemplarKnightsList[y]);
                }

                for (int y = 0; y < _fiefService.ArmyList[x].KnightsList.Count; y++)
                {
                    tempPeopleModel.Add(_fiefService.ArmyList[x].KnightsList[y]);
                }

                for (int y = 0; y < _fiefService.ArmyList[x].CavalryTemplarKnightsList.Count; y++)
                {
                    tempPeopleModel.Add(_fiefService.ArmyList[x].CavalryTemplarKnightsList[y]);
                }

                for (int y = 0; y < _fiefService.ArmyList[x].OfficerCaptainsList.Count; y++)
                {
                    tempPeopleModel.Add(_fiefService.ArmyList[x].OfficerCaptainsList[y]);
                }

                for (int y = 0; y < _fiefService.ArmyList[x].OfficerCorporalsList.Count; y++)
                {
                    tempPeopleModel.Add(_fiefService.ArmyList[x].OfficerCorporalsList[y]);
                }

                for (int y = 0; y < _fiefService.ArmyList[x].OfficerSergeantsList.Count; y++)
                {
                    tempPeopleModel.Add(_fiefService.ArmyList[x].OfficerSergeantsList[y]);
                }

                for (int y = 0; y < _fiefService.ManorList[x].ResidentsList.Count; y++)
                {
                    tempPeopleModel.Add(_fiefService.ManorList[x].ResidentsList[y]);
                }

                for (int y = 0; y < _fiefService.ManorList[x].VillagesCollection.Count; y++)
                {
                    tempVillageModels.Add(_fiefService.ManorList[x].VillagesCollection[y]);
                }
            }

            tempDataModel.ResidentsCollection = new ObservableCollection <IPeopleModel>(tempPeopleModel);
            tempDataModel.VillagesCollection  = new ObservableCollection <VillageModel>(tempVillageModels);

            return(tempDataModel);
        }
Example #48
0
        public static List <RoutePoint> Navigate(string From, string To, bool UseJumpGates, RoutingMode routingMode)
        {
            if (!(MapNodes.Keys.Contains(From) || MapNodes.Keys.Contains(To)))
            {
                return(null);
            }



            // clear the scores, values and parents from the list
            foreach (MapNode mapNode in MapNodes.Values)
            {
                mapNode.NearestToStart = null;
                mapNode.MinCostToStart = 0;
                mapNode.Visited        = false;

                switch (routingMode)
                {
                case RoutingMode.PreferLow:
                {
                    if (mapNode.HighSec)
                    {
                        mapNode.Cost = 1000;
                    }
                }
                break;

                case RoutingMode.Safest:
                {
                    if (!mapNode.HighSec)
                    {
                        mapNode.Cost = 1000;
                    }
                }
                break;

                case RoutingMode.Shortest:
                    mapNode.Cost = 1;
                    break;
                }
            }


            MapNode Start = MapNodes[From];
            MapNode End   = MapNodes[To];

            List <MapNode> OpenList   = new List <MapNode>();
            List <MapNode> ClosedList = new List <MapNode>();

            MapNode CurrentNode = null;

            // add the start to the open list
            OpenList.Add(Start);


            while (OpenList.Count > 0)
            {
                // get the MapNode with the lowest F score
                int lowest = OpenList.Min(mn => mn.MinCostToStart);
                CurrentNode = OpenList.First(mn => mn.MinCostToStart == lowest);

                // add the list to the closed list
                ClosedList.Add(CurrentNode);

                // remove it from the open list
                OpenList.Remove(CurrentNode);

                // walk the connections
                foreach (string connectionName in CurrentNode.Connections)
                {
                    MapNode CMN = MapNodes[connectionName];


                    if (CMN.Visited)
                    {
                        continue;
                    }

                    if (CMN.MinCostToStart == 0 || CurrentNode.MinCostToStart + CMN.Cost < CMN.MinCostToStart)
                    {
                        CMN.MinCostToStart = CurrentNode.MinCostToStart + CMN.Cost;
                        CMN.NearestToStart = CurrentNode;
                        if (!OpenList.Contains(CMN))
                        {
                            OpenList.Add(CMN);
                        }
                    }
                }


                if (UseJumpGates && CurrentNode.JBConnection != null)
                {
                    MapNode JMN = MapNodes[CurrentNode.JBConnection];
                    if (!JMN.Visited && JMN.MinCostToStart == 0 || CurrentNode.MinCostToStart + JMN.Cost < JMN.MinCostToStart)
                    {
                        JMN.MinCostToStart = CurrentNode.MinCostToStart + JMN.Cost;
                        JMN.NearestToStart = CurrentNode;
                        if (!OpenList.Contains(JMN))
                        {
                            OpenList.Add(JMN);
                        }
                    }
                }

                CurrentNode.Visited = true;
            }



            // build the path

            List <string> Route = new List <string>();

            CurrentNode = End;
            if (End.NearestToStart != null)
            {
                while (CurrentNode != null)
                {
                    Route.Add(CurrentNode.Name);
                    CurrentNode = CurrentNode.NearestToStart;
                }
                Route.Reverse();
            }

            List <RoutePoint> ActualRoute = new List <RoutePoint>();

            for (int i = 0; i < Route.Count; i++)
            {
                RoutePoint RP = new RoutePoint();
                RP.SystemName = Route[i];
                RP.GateToTake = GateType.StarGate;

                if (i < Route.Count - 1)
                {
                    MapNode mn = MapNodes[RP.SystemName];
                    if (mn.JBConnection != null && mn.JBConnection == Route[i + 1])
                    {
                        RP.GateToTake = GateType.Ansibex;
                    }
                }
                ActualRoute.Add(RP);
            }


            return(ActualRoute);
        }
        /// <summary>
        /// 获取该分区中心坐标
        /// </summary>
        /// <param name="SectionEntityData"></param>
        /// <returns></returns>
        public Vector GetCentre(Section_Entity_Data SectionEntityData)
        {
            //变量初始化
            Vector         Result    = new Vector();
            List <decimal> Tem_Dat_X = new List <decimal>();
            List <decimal> Tem_Dat_Y = new List <decimal>();

            //获取数据
            if (SectionEntityData.ArcLine.Count > 0)
            {
                for (int i = 0; i < SectionEntityData.ArcLine.Count; i++)
                {
                    if (SectionEntityData.ArcLine[i].Count >= 0)//判断数据大于零
                    {
                        Tem_Dat_X.Add(SectionEntityData.ArcLine[i].Max(o => o.Start_x));
                        Tem_Dat_X.Add(SectionEntityData.ArcLine[i].Min(o => o.Start_x));
                        Tem_Dat_X.Add(SectionEntityData.ArcLine[i].Max(o => o.End_x));
                        Tem_Dat_X.Add(SectionEntityData.ArcLine[i].Min(o => o.End_x));
                        Tem_Dat_Y.Add(SectionEntityData.ArcLine[i].Max(o => o.Start_y));
                        Tem_Dat_Y.Add(SectionEntityData.ArcLine[i].Min(o => o.Start_y));
                        Tem_Dat_Y.Add(SectionEntityData.ArcLine[i].Max(o => o.End_y));
                        Tem_Dat_Y.Add(SectionEntityData.ArcLine[i].Min(o => o.End_y));
                    }
                }
            }
            if (SectionEntityData.Circle.Count > 0)
            {
                Tem_Dat_X.Add(SectionEntityData.Circle.Max(o => o.Center_x));
                Tem_Dat_X.Add(SectionEntityData.Circle.Min(o => o.Center_x));
                Tem_Dat_Y.Add(SectionEntityData.Circle.Max(o => o.Center_y));
                Tem_Dat_Y.Add(SectionEntityData.Circle.Min(o => o.Center_y));
            }
            if (SectionEntityData.LWPolyline.Count > 0)
            {
                for (int i = 0; i < SectionEntityData.LWPolyline.Count; i++)
                {
                    if (SectionEntityData.LWPolyline[i].Count >= 0)//判断数据大于零
                    {
                        Tem_Dat_X.Add(SectionEntityData.LWPolyline[i].Max(o => o.Start_x));
                        Tem_Dat_X.Add(SectionEntityData.LWPolyline[i].Min(o => o.Start_x));
                        Tem_Dat_X.Add(SectionEntityData.LWPolyline[i].Max(o => o.End_x));
                        Tem_Dat_X.Add(SectionEntityData.LWPolyline[i].Min(o => o.End_x));
                        Tem_Dat_Y.Add(SectionEntityData.LWPolyline[i].Max(o => o.Start_y));
                        Tem_Dat_Y.Add(SectionEntityData.LWPolyline[i].Min(o => o.Start_y));
                        Tem_Dat_Y.Add(SectionEntityData.LWPolyline[i].Max(o => o.End_y));
                        Tem_Dat_Y.Add(SectionEntityData.LWPolyline[i].Min(o => o.End_y));
                    }
                }
            }
            //计算返回坐标
            if ((Tem_Dat_X.Count <= 0) || (Tem_Dat_Y.Count <= 0))
            {
                Result = new Vector(0, 0);
            }
            else
            {
                Result = new Vector((Tem_Dat_X.Max() + Tem_Dat_X.Min()) / 2, (Tem_Dat_Y.Max() + Tem_Dat_Y.Min()) / 2);
            }
            return(Result);
        }
Example #50
0
        static async Task GetListStatusesAsync(TwitterContext twitterCtx)
        {
            string ownerScreenName = "Linq2Twitr";
            string slug            = "linq-to-twitter";
            int    maxStatuses     = 30;
            int    lastStatusCount = 0;
            // last tweet processed on previous query
            ulong sinceID = 204251866668871681;
            ulong maxID;
            int   count      = 10;
            var   statusList = new List <Status>();

            // only count
            var listResponse =
                await
                    (from list in twitterCtx.List
                    where list.Type == ListType.Statuses &&
                    list.OwnerScreenName == ownerScreenName &&
                    list.Slug == slug &&
                    list.Count == count
                    select list)
                .SingleOrDefaultAsync();

            if (listResponse != null && listResponse.Statuses != null)
            {
                List <Status>?newStatuses = listResponse.Statuses;
                // first tweet processed on current query
                maxID = newStatuses.Min(status => status.StatusID) - 1;
                statusList.AddRange(newStatuses);

                do
                {
                    // now add sinceID and maxID
                    listResponse =
                        await
                            (from list in twitterCtx.List
                            where list.Type == ListType.Statuses &&
                            list.OwnerScreenName == ownerScreenName &&
                            list.Slug == slug &&
                            list.Count == count &&
                            list.SinceID == sinceID &&
                            list.MaxID == maxID
                            select list)
                        .SingleOrDefaultAsync();

                    if (listResponse == null)
                    {
                        break;
                    }

                    newStatuses = listResponse.Statuses;
                    // first tweet processed on current query
                    maxID = newStatuses?.Min(status => status.StatusID) - 1 ?? 0;
                    statusList.AddRange(newStatuses ?? new List <Status>());

                    lastStatusCount = newStatuses?.Count ?? 0;
                }while (lastStatusCount != 0 && statusList.Count < maxStatuses);

                for (int i = 0; i < statusList.Count; i++)
                {
                    Status status = statusList[i];

                    Console.WriteLine("{0, 4}. [{1}] User: {2}\nStatus: {3}",
                                      i + 1, status.StatusID, status.User?.Name, status.Text);
                }
            }
        }
Example #51
0
        static void Main(string[] args)
        {
            List <Chunk>   chunks      = new List <Chunk>();
            DateTimeOffset globalstart = DateTimeOffset.Now.AddMinutes(-25);

            globalstart = globalstart.AddSeconds(-globalstart.Second);
            DateTimeOffset endTime   = globalstart.AddMinutes(0).AddSeconds(20);
            DateTimeOffset startTime = globalstart.AddMinutes(0).AddSeconds(-15);

            for (int i = 0; i < 1; i++)
            {
                chunks.Add(new Chunk()
                {
                    ID = i, StartTime = globalstart.AddMinutes(i)
                });
            }

            var times = from d in chunks
                        where d.StartTime < startTime
                        select d.StartTime;

            //var maxTime = (from d in chunks
            //               where d.StartTime < startTime
            //               select d.StartTime).Max();

            var mt = (from c in chunks
                      select c.StartTime).Min();

            //if (mt > startTime)
            //    startTime = mt;

            var samplesChunks = (from c in chunks
                                 where c.StartTime <= endTime &&
                                 ((from d in chunks
                                   where d.StartTime <= startTime
                                   select d.StartTime).DefaultIfEmpty(chunks.Min(t => t.StartTime)).Max() <= c.StartTime)
                                 select c).OrderBy(c => c.StartTime);

            var samplesChunks1 = chunks
                                 .Where(c => c.StartTime <= endTime && c.StartTime >= chunks
                                        .Where(d => d.StartTime <= startTime)
                                        .Select(d => d.StartTime).Max());

            //var minTime = samplesChunks.Select(t => t.StartTime).Min();
            //var mintime1 = samplesChunks.Min(t => t.StartTime);

            Console.WriteLine(String.Format("startTime = {0}\nendTime = {1}", startTime.ToString(), endTime.ToString()));
            Console.WriteLine("From...Where...Select");
            foreach (var item in samplesChunks)
            {
                Console.WriteLine(String.Format("ID = {0}, Time = {1}", item.ID, item.StartTime.ToString()));
            }

            Console.WriteLine("Obj.Where.Select");
            foreach (var item in samplesChunks1)
            {
                Console.WriteLine(String.Format("ID = {0}, Time = {1}", item.ID, item.StartTime.ToString()));
            }

            //Console.WriteLine(String.Format("MinTime = {0}\nMinTime1 = {1}", minTime.ToString(), mintime1.ToString()));


            Console.ReadLine();
        }
        public void AggregatesTicksIntoSecondBars()
        {
            var timeProvider = new ManualTimeProvider(TimeZones.NewYork);
            var enumerator   = new TradeBarBuilderEnumerator(Time.OneSecond, TimeZones.NewYork, timeProvider);

            // noon new york time
            var currentTime = new DateTime(2015, 10, 08, 12, 0, 0);

            timeProvider.SetCurrentTime(currentTime);

            // add some ticks
            var ticks = new List <Tick>
            {
                new Tick(currentTime, "SPY", 199.55m, 199, 200)
                {
                    Quantity = 10
                },
                new Tick(currentTime, "SPY", 199.56m, 199.21m, 200.02m)
                {
                    Quantity = 5
                },
                new Tick(currentTime, "SPY", 199.53m, 198.77m, 199.75m)
                {
                    Quantity = 20
                },
                new Tick(currentTime, "SPY", 198.77m, 199.75m)
                {
                    Quantity = 0
                },
                new Tick(currentTime, "SPY", 199.73m, 198.77m, 199.75m)
                {
                    Quantity = 20
                },
                new Tick(currentTime, "SPY", 198.77m, 199.75m)
                {
                    Quantity = 0
                },
            };

            foreach (var tick in ticks)
            {
                enumerator.ProcessData(tick);
            }

            // even though no data is here, it will still return true
            Assert.IsTrue(enumerator.MoveNext());
            Assert.IsNull(enumerator.Current);

            // advance a second
            currentTime = currentTime.AddSeconds(1);
            timeProvider.SetCurrentTime(currentTime);

            Assert.IsTrue(enumerator.MoveNext());
            Assert.IsNotNull(enumerator.Current);

            // in the spirit of not duplicating the above code 5 times (OHLCV, we'll assert these ere as well)
            var bar = (TradeBar)enumerator.Current;

            Assert.AreEqual(currentTime.AddSeconds(-1), bar.Time);
            Assert.AreEqual(currentTime, bar.EndTime);
            Assert.AreEqual("SPY", bar.Symbol.Value);
            Assert.AreEqual(ticks.First().LastPrice, bar.Open);
            Assert.AreEqual(ticks.Max(x => x.LastPrice), bar.High);
            Assert.AreEqual(ticks.Min(x => x.LastPrice), bar.Low);
            Assert.AreEqual(ticks.Last().LastPrice, bar.Close);
            Assert.AreEqual(ticks.Sum(x => x.Quantity), bar.Volume);
        }
Example #53
0
        /// <summary>
        /// Fulfill a simple goal when needed. This is done by finding an action that has a more general version of the goal in its add list.
        /// If we find an action, we instantiate it and add it along with its preconditions to the stack (preconditions first).
        /// Some loopdetection is performed to see if we haven't already added a precondition of the action as this indicates a loop.
        /// Multiple actions are possible so if choosing one action ends in an unplannable situation (due to a loop or no choice of actions further down the line)
        /// we simply backtrack to the previous choice of actions and choose another. When looking for an optimal path, this backtracking is done for every choice so
        /// we can guarantee that we make the most optimal choice at any point of the execution.
        /// </summary>
        /// <param name="simpleGoal">The goal we wish to see fulfilled by choosing an action</param>
        /// <param name="plan">The current plan</param>
        /// <param name="optimal">A flag indicating if we're looking for the optimal plan or not</param>
        /// <param name="itemsToProcess">The stack of items to process containing goals and actions</param>
        /// <param name="previousStates">A list of previous states to be used in loop detection</param>
        /// <param name="currentBeliefs">The current set of beliefs</param>
        /// <param name="preconditions">A list of preconditions used in loop detection</param>
        /// <param name="actions">A list of executable actions of the agent</param>
        /// <returns>True if we find a plan that fulfills the goal and all remaining items in the stack, false otherwise</returns>
        private static bool FulFillSimpleGoal <TAction>(SimpleGoal simpleGoal, Plan <TAction> plan, bool optimal, Stack <IStackItem> itemsToProcess,
                                                        List <State> previousStates, List <Fact> currentBeliefs, List <Fact> preconditions, List <Action> actions) where TAction : Action
        {
            //only look for an action when the goal hasn't been achieved yet
            if (!simpleGoal.IsFulFilled(currentBeliefs))
            {
                //add the fact of the goal in the list of visited preconditions
                preconditions.Add(simpleGoal.Fact);
                //look for possible actions to execute
                var possibleActions = actions.Where(x => x.IsApplicableFor(simpleGoal, currentBeliefs));
                var iter            = possibleActions.GetEnumerator();

                //keep a list of plans and beliefsets for each action that is possible (for optimization later)
                var subPlansForAction = new List <Tuple <Plan <TAction>, List <Fact> > >();
                while (iter.MoveNext())
                {
                    var action = iter.Current;
                    //instantiate the action as much as possible
                    action = action.InstantiateFor(simpleGoal, currentBeliefs);

                    //perform loopdetection
                    var lstPre = action.Preconditions.ToList();
                    lstPre.Reverse();
                    var faulty = lstPre.Any(x => IsAlreadyACondition(x, preconditions));
                    if (!faulty)
                    {
                        //create the complex goal with the preconditions of the action
                        var complex = new ComplexGoal();
                        foreach (var precondition in lstPre)
                        {
                            complex.Goals.Add(new SimpleGoal(precondition, action));
                        }

                        //create a new stack but with action and complex goal added
                        var newStack = new Stack <IStackItem>(itemsToProcess.Reverse());
                        newStack.Push(action);
                        newStack.Push(complex);

                        //perform create plan for the new stack
                        (Plan <TAction> subPlanForAction, List <Fact> lstBeliefs) = CreatePlan <TAction>(newStack, currentBeliefs.ToList(), preconditions.ToList(),
                                                                                                         previousStates.ToList(), actions, optimal);

                        //the chosen action gives a valid plan so add the plan (and beliefset) to the possible plans we can choose from
                        if (subPlanForAction != null)
                        {
                            subPlansForAction.Add(Tuple.Create(subPlanForAction, lstBeliefs));
                            if (optimal)
                            {
                                break;
                            }
                        }
                    }
                }
                //no plan found for this goal and current beliefset so return null
                if (!subPlansForAction.Any())
                {
                    return(false);
                }
                else
                {
                    //we look for the minimal path (minimal number of steps) asuming that each step has an equal 'cost'
                    var minSteps = subPlansForAction.Min(x => x.Item1.Steps.Count());
                    var best     = subPlansForAction.First(x => x.Item1.Steps.Count() == minSteps);
                    //add the steps of the optimal subplan to this plan and update the current set of beliefs
                    plan.Steps.AddRange(best.Item1.Steps);
                    currentBeliefs = best.Item2;
                    //clear the stack as we already processed all items in the stack when looking for all subplans
                    itemsToProcess.Clear();
                }
            }
            return(true);
        }
Example #54
0
 public static double MinAbundance <T>(this List <T> features) where T : MSFeatureLight
 {
     return(features.Min(feature => feature.Abundance));
 }
Example #55
0
    // Takes a dictionary of keys: distance to wall and values: wall object
    // Returns closest wall
    private GameObject FindClosestWall(List <GameObject> walls, List <float> distance)
    {
        float minDistance = distance.Min();

        return(walls[distance.IndexOf(minDistance)]);
    }
Example #56
0
        static void Main(string[] args)
        {
            Category c1 = new Category()
            {
                Id = 1, Name = "Tools", Tier = 2
            };
            Category c2 = new Category()
            {
                Id = 2, Name = "Computers", Tier = 1
            };
            Category c3 = new Category()
            {
                Id = 3, Name = "Electronics", Tier = 1
            };

            List <Product> products = new List <Product>()
            {
                new Product()
                {
                    Id = 1, Name = "Computer", Price = 1100.0, Category = c2
                },
                new Product()
                {
                    Id = 2, Name = "Hammer", Price = 90.0, Category = c1
                },
                new Product()
                {
                    Id = 3, Name = "TV", Price = 1700.0, Category = c3
                },
                new Product()
                {
                    Id = 4, Name = "Notebook", Price = 1300.0, Category = c2
                },
                new Product()
                {
                    Id = 5, Name = "Saw", Price = 80.0, Category = c1
                },
                new Product()
                {
                    Id = 6, Name = "Tablet", Price = 700.0, Category = c2
                },
                new Product()
                {
                    Id = 7, Name = "Camera", Price = 700.0, Category = c3
                },
                new Product()
                {
                    Id = 8, Name = "Printer", Price = 350.0, Category = c3
                },
                new Product()
                {
                    Id = 9, Name = "MacBook", Price = 1800.0, Category = c2
                },
                new Product()
                {
                    Id = 10, Name = "Sound Bar", Price = 700.0, Category = c3
                },
                new Product()
                {
                    Id = 11, Name = "Level", Price = 70.0, Category = c1
                }
            };


            // var r1 = products.Where(p => p.Category.Tier == 1 && p.Price < 900);
            var r1 =
                from p in products
                where p.Category.Tier == 1 && p.Price < 900
                select p;

            Print("TIER 1 AND PRICE < 900:", r1);

            //var r2 = products.Where(p => p.Category.Name == "Tools").Select(p => p.Name);
            var r2 = from p in products
                     where p.Category.Name == "Tools"
                     select p.Name;

            Print("NAMES OF PRODUCTS FROM TOOLS:", r2);

            //var r3 = products.Where(p => p.Name[0] == 'C').Select(p => new { p.Name,p.Price, CategoryName = p.Category.Name});
            var r3 = from p in products
                     where p.Name[0] == 'C'
                     select new
            {
                p.Name,
                p.Price,
                categoryName = p.Category.Name
            };

            Print("NAMES STARTED WITH 'C' AND ANONYMOUS OBJECT:", r3);

            //   var r4 = products.Where(p => p.Category.Tier == 1).OrderBy(p => p.Price).ThenBy(p => p.Name);
            var r4 = from p in products
                     where p.Category.Tier == 1
                     orderby p.Name
                     orderby p.Price
                     select p;

            Print("TIER 1 ORDER BY PRICE THEN BY NAME", r4);

            var r5 = (from p in r4 select p).Skip(2).Take(4);

            Print("TIER 1 ORDER BY PRICE THEN BY NAME SKIP 2 TAKE 4", r5);

            var r6 = products.FirstOrDefault();

            Console.WriteLine("First or default test1: " + r6);

            var r7 = products.Where(p => p.Price > 7000.0).FirstOrDefault();

            Console.WriteLine("First or default test2: " + r7);
            Console.WriteLine();

            var r8 = products.Where(p => p.Id == 3).SingleOrDefault();

            Console.WriteLine("Single or default test1: " + r8);

            var r9 = products.Where(p => p.Id == 30).SingleOrDefault();

            Console.WriteLine("Single or default test2: " + r9);

            var r10 = products.Max(p => p.Price);

            Console.WriteLine("Max price: " + r10);
            var r11 = products.Min(p => p.Price);

            Console.WriteLine("Min price: " + r11);
            var r12 = products.Where(p => p.Category.Id == 1).Sum(p => p.Price);

            Console.WriteLine("Category 1 Sum prices: " + r12);
            var r13 = products.Where(p => p.Category.Id == 1).Average(p => p.Price);

            Console.WriteLine("Category 1 Average prices: " + r13);
            var r14 = products.Where(p => p.Category.Id == 5).Select(p => p.Price).DefaultIfEmpty(0.0).Average();

            Console.WriteLine("Category 5 Average prices: " + r14);
            var r15 = products.Where(p => p.Category.Id == 1).Select(p => p.Price).Aggregate(0.0, (x, y) => y + x);

            Console.WriteLine("Category 1 aggregate Sum: " + r15);
            Console.WriteLine();

            // var r16 = products.GroupBy(p => p.Category);
            var r16 = from p in products
                      group p by p.Category;

            foreach (IGrouping <Category, Product> group in r16)
            {
                Console.WriteLine("Category: " + group.Key.Name + ":");
                foreach (Product p in group)
                {
                    Console.WriteLine(p);
                }
                Console.WriteLine();
            }
        }
Example #57
0
        static void Main(string[] args)
        {
            Console.WriteLine("AoC 2018 - " + typeof(Day07).Namespace + ":");

            // First read input
            List <Step> ReadInput()
            {
                List <Step>  input  = new List <Step>();
                Regex        parts  = new Regex(@"^S.*([A-Z]).*([A-Z])");
                string       path   = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"..\..\input.txt");
                StreamReader reader = File.OpenText(path);
                string       line;

                while ((line = reader.ReadLine()) != null)
                {
                    MatchCollection matches = parts.Matches(line);
                    if (matches.Count > 0)
                    {
                        GroupCollection groups = matches[0].Groups;
                        Step            step   = new Step();
                        int             i      = 1;
                        step.prereqChar = groups[i++].Value[0];
                        step.followChar = groups[i++].Value[0];
                        input.Add(step);
                    }
                }
                return(input);
            }

            // Part A
            List <Node> BuildNodes(List <Step> steps)
            {
                Dictionary <char, Node> nodeDict = new Dictionary <char, Node>();

                foreach (Step s in steps)
                {
                    nodeDict[s.prereqChar] = new Node(s.prereqChar);
                    nodeDict[s.followChar] = new Node(s.followChar);
                }
                foreach (Step s in steps)
                {
                    nodeDict[s.followChar].prereq.Add(s.prereqChar);
                }
                return(nodeDict.Values.ToList());
            }

            List <Node> nodes  = BuildNodes(ReadInput());
            List <char> result = new List <char>();

            while (nodes.Any())
            {
                List <char> candidates = new List <char>();
                foreach (Node n in nodes)
                {
                    if (!n.prereq.Any())
                    {
                        candidates.Add(n.id);
                    }
                }
                candidates.Sort();
                if (candidates.Any())
                {
                    char c = candidates.First();
                    result.Add(c);
                    foreach (Node n in nodes)
                    {
                        n.prereq.Remove(c);
                    }
                    nodes.RemoveAll(n => n.id == c);
                }
            }
            string resultString = new string(result.ToArray());

            Console.WriteLine("Part A: Take steps in this order: " + resultString + ".");

            // Part B
            int totalSecs = 0;

            nodes = BuildNodes(ReadInput());
            const int     nWorkers = 5;
            const int     offsSecs = 60;
            List <Worker> workers  = new List <Worker>();

            while (nodes.Any())
            {
                List <char> candidates = new List <char>();
                foreach (Node n in nodes)
                {
                    if (!n.prereq.Any())
                    {
                        candidates.Add(n.id);
                    }
                }
                candidates.Sort();
                while (candidates.Any() && (workers.Count() < nWorkers))
                {
                    char c = candidates.First();
                    candidates.RemoveAt(0);
                    Worker w = new Worker
                    {
                        id       = c,
                        timeDone = totalSecs + offsSecs + (c - 'A' + 1)
                    };
                    workers.Add(w);
                    nodes.RemoveAll(n => n.id == c);
                }
                int tNext = workers.Min(w => w.timeDone);
                foreach (Worker w in workers)
                {
                    if (w.timeDone == tNext)
                    {
                        foreach (Node n in nodes)
                        {
                            n.prereq.Remove(w.id);
                        }
                    }
                }
                workers.RemoveAll(t => t.timeDone == tNext);
                totalSecs = tNext;
            }
            Console.WriteLine("Part B: All steps complete in " + totalSecs + " seconds.");
        }
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult temp = openFileDialog2.ShowDialog();

            if (temp == DialogResult.OK)
            {
                //  toolStripStatusLabel1.Text = "Opened a file";
                try {
                    myStream = openFileDialog2.OpenFile(); //open the file
                    if (myStream == null)
                    {
                        MessageBox.Show("myStream is NULL");
                    }
                    else
                    {
                        //read in all the lines
                        string       tempData = "";
                        StreamReader sr       = new StreamReader(myStream);
                        data.Clear();
                        intervalData1.Clear();
                        intervalData2.Clear();
                        while ((tempData = sr.ReadLine()) != null)
                        {
                            //tempData = sr.ReadLine();
                            if (tempData != "" && tempData[0] == '+') //positive value
                            {
                                tempData = tempData.Substring(1);     //eliminate the sign
                                if (tempData.Contains("+") == false && tempData.Contains("-") == false)
                                {
                                    data.Add(double.Parse(tempData, System.Globalization.CultureInfo.InvariantCulture));
                                }
                                //  debugMessages.Text = debugMessages.Text + data[data.Count - 1] + "\r\n";
                            }
                            else if (tempData != "" && tempData[0] == '-') //negative value
                            {
                                tempData = tempData.Substring(1);          //eliminate the sign
                                if (tempData.Contains("+") == false && tempData.Contains("-") == false)
                                {
                                    data.Add(double.Parse(tempData, System.Globalization.CultureInfo.InvariantCulture));
                                    data[data.Count - 1] = -1.0 * data[data.Count - 1];
                                }
                                // debugMessages.Text = debugMessages.Text+ data[data.Count - 1]+"\r\n";
                            }
                            //else {
                            //    debugMessages.Text += "Invalid characters found, please check text file formatting." + Environment.NewLine;
                            //    MessageBox.Show("Invalid characters found, please check text file formatting.");
                            //}
                            //debugMessages.Text = debugMessages.Text + data.Count.ToString() + "\r\n";
                        }
                        sr.Close();
                        debugMessages.Text = debugMessages.Text + "File successfully read in." + Environment.NewLine;
                        debugMessages.Text = debugMessages.Text + "Number of data points: " + data.Count.ToString() + Environment.NewLine;
                        XMinBox.Text       = 0.ToString();
                        YMinBox.Text       = data.Min().ToString();
                        XMaxBox.Text       = (data.Count - 1).ToString();
                        YMaxBox.Text       = data.Max().ToString();
                    }
                }
                catch (Exception error) {
                    MessageBox.Show(error.Message); //show the error
                }
            }
            else if (temp == DialogResult.Cancel)
            {
                // toolStripStatusLabel1.Text = "Canceled opening a file";
            }
        }
Example #59
0
        static void Main(string[] args)
        {
            //parsing data, assumes file is always in the same format and string lengths
            List <Point> points    = new List <Point>();
            var          dataLines = File.ReadAllText(@"DataPoints.txt").Trim().Split('\n');

            foreach (string line in dataLines)
            {
                var x  = int.Parse(line.Substring(10, 6));
                var y  = int.Parse(line.Substring(18, 6));
                var xv = int.Parse(line.Substring(36, 2));
                var yv = int.Parse(line.Substring(40, 2));

                points.Add(new Point()
                {
                    X_Position = x,
                    Y_Position = y,
                    X_Velocity = xv,
                    Y_Velocity = yv
                });
            }

            var mapWidth  = Int32.MaxValue;
            var mapHeight = Int32.MaxValue;
            var found     = false;
            var correct   = "n";

            while (found == false)
            {
                foreach (var point in points)
                {
                    point.FastForward();
                }

                //calculate new map size
                int xMin = points.Min(s => s.X_Position);
                int xMax = points.Max(s => s.X_Position);
                int yMin = points.Min(s => s.Y_Position);
                int yMax = points.Max(s => s.Y_Position);

                int width  = xMax - xMin;
                int height = yMax - yMin;

                //assumes points are close together for message to appear
                if (mapWidth <= 100 && mapHeight <= 50)
                {
                    //possible map so generate it and display it
                    Console.WriteLine("New Map");
                    StringBuilder map = new StringBuilder();
                    for (int y = yMin; y <= yMax; y++)
                    {
                        for (int x = xMin; x <= xMax; x++)
                        {
                            map.Append(points.Any(p => p.pointExists(x, y)) ? "#" : ".");
                        }

                        map.AppendLine();
                    }
                    Console.WriteLine(map);
                    Console.WriteLine("correct map? ");
                    correct = Console.ReadLine();
                    if (correct == "y")
                    {
                        found = true;
                    }
                }

                //set the current map size
                mapWidth  = width;
                mapHeight = height;
            }
            Console.ReadLine();
        }
Example #60
0
    IEnumerator Start()
    {
        map = GetComponent <MapReader>();
        while (!map.isReady)
        {
            yield return(null);
        }
        foreach (var way in map.ways)
        {
            if (way.typeOfBuilding != null && way.childrenIDs.Count > 1)
            {
                MapNode firstNode  = map.mapNodes[way.childrenIDs[0]]; //first point
                MapNode secondNode = map.mapNodes[way.childrenIDs[1]]; //second point
                Vector3 sum        = Vector3.zero;
                buildingVertices = new List <Vector3>();
                buildingVertices.Add(new Vector3((float)firstNode.X - map.bounds.centre.x, 0, (float)firstNode.Y - map.bounds.centre.z));

                ChoosePrefab(way);
                if (chosenPrefab == null)
                {
                    continue;
                }

                /*if (chosenPrefab == housePrefab)
                 *  chosenPrefab.transform.localScale = new Vector3(0.3f, 0.3f, 0.3f);
                 * else if(chosenPrefab == policePrefab)
                 *  chosenPrefab.transform.localScale = new Vector3(0.12f, 0.12f, 0.06f);
                 * else
                 *  chosenPrefab.transform.localScale = new Vector3(0.12f,0.12f,0.12f);*/

                float minBuildingHeight = GetHeight((float)(firstNode.X - map.bounds.centre.x), (float)(firstNode.Y - map.bounds.centre.z));
                distances = new float[way.childrenIDs.Count - 1];
                sections  = new Vector3[way.childrenIDs.Count - 1];

                for (int i = 1; i < way.childrenIDs.Count; i++)
                {
                    MapNode n1 = map.mapNodes[way.childrenIDs[i - 1]];
                    MapNode n2 = map.mapNodes[way.childrenIDs[i]];

                    float x1 = (float)(n1.X - map.bounds.centre.x);
                    float z1 = (float)(n1.Y - map.bounds.centre.z);
                    float x2 = (float)(n2.X - map.bounds.centre.x);
                    float z2 = (float)(n2.Y - map.bounds.centre.z);

                    Vector3 v1 = new Vector3(x1, 0, z1);
                    Vector3 v2 = new Vector3(x2, 0, z2);

                    buildingVertices.Add(v2);

                    sum += v1;

                    float pointHeight = GetHeight(x2, z2);
                    if (pointHeight < minBuildingHeight)
                    {
                        minBuildingHeight = pointHeight;
                    }

                    //float distance = Vector3.Distance(v1, v2);
                    //distances[i - 1] = distance;
                    sections[i - 1] = v2 - v1;
                }

                float minX = buildingVertices.Min(vec => vec.x);
                //Vector3 minXvec = buildingVertices.First(vec => vec.x == minX);
                float maxX = buildingVertices.Max(vec => vec.x);
                //Vector3 maxXvec = buildingVertices.First(vec => vec.x == maxX);
                float minZ = buildingVertices.Min(vec => vec.z);
                //Vector3 minZvec = buildingVertices.First(vec => vec.z == minZ);
                float maxZ = buildingVertices.Max(vec => vec.z);
                //Vector3 maxZvec = buildingVertices.First(vec => vec.z == maxZ);


                List <float> xDistances = new List <float>();
                List <float> zDistances = new List <float>();

                for (int i = 0; i < sections.Length; i++)
                {
                    if (Math.Abs(sections[i].x) > Math.Abs(sections[i].z))
                    {
                        xDistances.Add(sections[i].magnitude);
                    }
                    else
                    {
                        zDistances.Add(sections[i].magnitude);
                    }
                }

                xDistances.Sort();
                xDistances.Reverse();
                zDistances.Sort();
                zDistances.Reverse();

                Vector3 centre = sum / (way.childrenIDs.Count - 1);
                centre.y = minBuildingHeight;

                Vector3 rot = sections[0];
                Vector3 v   = sections[0];
                Vector3 u   = sections[1];


                for (int i = 1; i < sections.Length; i++)
                {
                    if (Vector3.Angle(sections[i - 1], sections[i]) > 89 && Vector3.Angle(sections[i - 1], sections[i]) < 91)
                    {
                        v = sections[i - 1];
                        u = sections[i];
                    }
                }

                if (Mathf.Abs(v.x / v.z) > 1)
                {
                    rot = u;
                }
                else if (Mathf.Abs(u.x / u.z) > 1)
                {
                    rot = v;
                }

                GameObject go = Instantiate(chosenPrefab, centre, Quaternion.LookRotation(rot, Vector3.up));
                go.transform.localScale = new Vector3(go.transform.localScale.x * xDistances.Sum(), go.transform.localScale.y, go.transform.localScale.z * zDistances.Sum());
                //go.transform.localScale = new Vector3(go.transform.localScale.x*xDistances[0], go.transform.localScale.y*Mathf.Min(xDistances[0],zDistances[0]), go.transform.localScale.z*zDistances[0]);
                //go.transform.localScale = new Vector3(go.transform.localScale.x*(maxZvec-minXvec).magnitude,go.transform.localScale.y*Mathf.Min(xDistances[0],zDistances[0]),go.transform.localScale.x*());
                //go.transform.localScale = new Vector3(go.transform.localScale.x*(xDistances.Sum()/2), go.transform.localScale.y*20f, go.transform.localScale.z*zDistances.Sum()/2);
                //go.transform.localScale = new Vector3(go.transform.localScale.x*(maxX-minX), go.transform.localScale.y*Mathf.Min(xDistances[0],zDistances[0]), go.transform.localScale.x*(maxZ-minZ));
                Bounds modelBounds = go.GetComponent <MeshRenderer>().bounds;
                float  scaleX      = (maxX - minX) / modelBounds.size.x;
                float  scaleZ      = (maxZ - minZ) / modelBounds.size.z;

                go.transform.localScale = new Vector3(go.transform.localScale.x * scaleX, go.transform.localScale.y * 20f, go.transform.localScale.z * scaleZ);
            }
        }
    }