static void Main() { IEnumerable <int> intArr =new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; IEnumerable<double> dblArr =new[] { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9 }; Console.WriteLine("Sum of: "); Console.WriteLine("Integer array: {0}", intArr.Sum()); Console.WriteLine("Double array: {0}", dblArr.Sum()); Console.WriteLine(); Console.WriteLine("Product of: "); Console.WriteLine("Integer array: {0}", intArr.Product()); Console.WriteLine("Double array: {0}", dblArr.Product()); Console.WriteLine(); Console.WriteLine("Average of: "); Console.WriteLine("Integer array: {0}", intArr.Average()); Console.WriteLine("Double array: {0}", dblArr.Average()); Console.WriteLine(); Console.WriteLine("Min of: "); Console.WriteLine("Integer array: {0}", intArr.Min()); Console.WriteLine("Double array: {0}", dblArr.Min()); Console.WriteLine(); Console.WriteLine("Max of: "); Console.WriteLine("Integer array: {0}", intArr.Max()); Console.WriteLine("Double array: {0}", dblArr.Max()); }
public static int DamerauLevenshteinDistance(this string s, string t) { var sLength = s.Length; var tLength = t.Length; var matrix = new int[sLength + 1, tLength + 1]; for (var i = 0; i <= sLength; i++) { matrix[i, 0] = i; } for (var i = 0; i <= tLength; i++) { matrix[0, i] = i; } for (var i = 1; i <= sLength; i++) { for (var j = 1; j <= tLength; j++) { var cost = t[j - 1] == s[i - 1] ? 0 : 1; var vals = new[] { matrix[i - 1, j] + 1, matrix[i, j - 1] + 1, matrix[i - 1, j - 1] + cost }; matrix[i, j] = vals.Min(); if (i > 1 && j > 1 && s[i - 1] == t[j - 2] && s[i - 2] == t[j - 1]) { matrix[i, j] = Math.Min(matrix[i, j], matrix[i - 2, j - 2] + cost); } } } return matrix[sLength, tLength]; }
public Rect TransformBounds (Rect rect) { var inverse = this; var points = new [] { inverse.TransformPoint (rect.TopLeft), inverse.TransformPoint (rect.TopRight), inverse.TransformPoint (rect.BottomLeft) , inverse.TransformPoint (rect.BottomRight) }; var x1 = points.Min (p => p.X); var y1 = points.Min (p => p.Y); var x2 = points.Max (p => p.X); var y2 = points.Max (p => p.Y); return new Rect (x1, y1, x2 - x1, y2 - y1); }
protected virtual DateTime GetTakenDate(string filePath) { DateTime[] dates = new[] { File.GetCreationTime(filePath), File.GetLastWriteTime(filePath) }; return dates.Min(); }
static void Main() { var elements = new[] { "a", "b" }; Console.WriteLine(elements.Average()); Console.WriteLine(elements.Min()); Console.WriteLine(elements.Max()); Console.WriteLine(elements.Sum()); string a = "a"; string b = "b"; Console.WriteLine(a * b); }
private static void Main() { var strBldr = new StringBuilder("Some test string"); Console.WriteLine(strBldr.Substring(6, 4)); IEnumerable<int> testEnum = new[] { 2, 5, 6, 8 }; Console.WriteLine(testEnum.Average()); Console.WriteLine(testEnum.Max()); Console.WriteLine(testEnum.Min()); }
public void ResolveTie_GivenMultipleCompetitors_ReturnsTheMinimumCompetitor() { // Arrange var competitors = new[] {3, 6, 8, 1, 9}; var minCompetitor = competitors.Min(); // Act var result = minPrioritisingTieBreaker.ResolveTie(competitors); // Assert result.Should().Be(minCompetitor); }
public void CanValidateUsingProperties() { var validatorById = new OrderedValidator<GenericParameter, int>(g => g.ID); Assert.IsTrue(validatorById.Validate( TestingDataFactory.Ordered.CreateOrderedData().Collection).IsValid); Assert.IsTrue(validatorById.Validate(TestingDataFactory.Ordered.CreateOrderedDataWithDuplicates().Collection).IsValid); Assert.IsTrue(validatorById.Validate( TestingDataFactory.Ordered.CreateEmptyData().Collection).IsValid); Assert.IsFalse(validatorById.Validate( TestingDataFactory.Ordered.CreateUnorderedData().Collection).IsValid); Assert.IsFalse(validatorById.Validate( TestingDataFactory.Ordered.CreateUnorderedDataWithDuplicates().Collection).IsValid); var x = new[] { 1, 2, 3 }; x.Min(); }
static void Main() { var numbers = new[] { 3, 5, 12, 15, 30, 35 }; Console.WriteLine("Sum: {0}", numbers.Sum()); Console.WriteLine("Product: {0}", numbers.Product()); Console.WriteLine("Min: {0}", numbers.Min()); Console.WriteLine("Max: {0}", numbers.Max()); Console.WriteLine("Average: {0}", numbers.Average()); Console.WriteLine(); }
public override string WriteTable(out int itemCount) { itemCount = -1; if (!_exportDateInitialized) throw new Exception("Sales export date was not initialized."); if (Rows.Count < 1) return "no data"; _progress.StartTask("Parsing data", "items", null, Rows.Count); var iPId = _rules.Fields.GetHeaderIndex(FieldName.OrderProductId); var iCId = _rules.Fields.GetHeaderIndex(FieldName.OrderCustomerId); var iQuan = _rules.Fields.GetHeaderIndex(FieldName.OrderQuantity); var iDate = _rules.Fields.GetHeaderIndex(FieldName.OrderDate); var indexes = new[] { iPId, iCId, iQuan, iDate }; if (indexes.Min<int>() < 0) return string.Format("bad header: {0}", Header.Aggregate((w, j) => string.Format("{0},{1}", w, j))); var minCols = indexes.Max<int>(); var sales = new List<SalesRecord>(); try { sales.AddRange(from cols in Rows where (cols.Count > 0 && cols.Count > minCols) select new SalesRecord { ProductId = cols[iPId], CustomerId = cols[iCId], Quantity = cols[iQuan], Date = cols[iDate], }); DateTime testDate; sales = sales.Where(s => !Input.TryGetDate(out testDate, s.Date, _rules.OrderDateReversed) || (testDate.Year.Equals(_exportDate.Year) && testDate.Month.Equals(_exportDate.Month))) .ToList(); } catch (Exception ex) { return ex.Message; } if (sales.Count < 1) return "no data"; //Migration slaves need to map each product id in sales to its replacement id _cart.MigrateSlaveOrders(ref sales); itemCount = sales.Count; var filename = String.Format(CartExtractor.SalesFilenameFormat, _exportDate.ToString("yyyy-MM")); _progress.UpdateTable(itemCount, -1, "Writing table"); return TableAccess.Instance.WriteTable(_rules.Alias, filename, sales); }
public void CompareTest() { var p1 = new Prefix(_prefixConfig, "DEV", "iphone"); var p2 = new Prefix(_prefixConfig, "DEV"); var p3 = new Prefix(_prefixConfig, "stageB"); var p4 = new Prefix(_prefixConfig, "DEV", "iphone"); var p5 = new Prefix(_prefixConfig, "ios", "iphone"); var prefixes = new [] {p1, p2, p3, p4, p5}; var max = prefixes.Max(); var min = prefixes.Min(); Assert.AreEqual(max, p1); Assert.AreEqual(min, p3); Assert.IsTrue(p2.CompareTo(p5) < 0); }
public void ExampleTest() { int[] a = new[] {0, 0, 4, 2, 4, 5}; //Throwing possible exceptions if (a == null) throw new ArgumentNullException(); if(a.Min()<0) throw new ArgumentOutOfRangeException(); if(a.Length==0) throw new ArgumentException(); //Looking for max value and create array int maxValue = a.Max(); int[] result = new int[maxValue + 1]; // And now the counting operation foreach (int i1 in a) { result[i1]++; } Assert.AreEqual(new[] {2, 0, 1, 0, 2, 1}, result); int[] a1 = new[] {5, 0, 2, 4, 0, 4}; //Throwing possible exceptions if (a1 == null) throw new ArgumentNullException(); if(a1.Min()<0) throw new ArgumentOutOfRangeException(); if(a1.Length==0) throw new ArgumentException(); //Looking for max value and create array int maxValue1 = a1.Max(); int[] result1 = new int[maxValue1 + 1]; // And now the counting operation foreach (int i2 in a1) { result1[i2]++; } Assert.AreEqual(new[] {2, 0, 1, 0, 2, 1}, result1); }
/*2. Implement a set of extension methods for IEnumerable<T> that implement the following group functions: * sum, product, min, max, average.*/ static void Main() { List<int> listInt = new List<int> { 1, 2, 3, 4, 5 }; double[] testDouble = new[] { 4.5, 6.0, 5.7, 34.7 }; //sum = 50.9 Console.WriteLine("---list <int>---"); Console.WriteLine("Sum: {0}", listInt.Sum()); Console.WriteLine("Average: {0}", listInt.Average()); Console.WriteLine("Product: {0}", listInt.Product()); Console.WriteLine("Minimum: {0}", listInt.Min()); Console.WriteLine("Minimum: {0}", listInt.Max()); Console.WriteLine("---double---"); Console.WriteLine("Sum: {0}", testDouble.Sum()); Console.WriteLine("Average: {0}", testDouble.Average()); Console.WriteLine("Product: {0}", testDouble.Product()); Console.WriteLine("Minimum: {0}", testDouble.Min()); Console.WriteLine("Minimum: {0}", testDouble.Max()); List<int> testEmpty = new List<int>(); Console.WriteLine(testEmpty.Sum()); //return error when enumaration is empty, does not work about array(return 0) }
static void Main() { var items = new[] { 1.2, 2.3, 3.4 }; Console.Write("Elements: "); foreach (var item in items) { Console.Write("{0} ", item); } Console.WriteLine(); Console.WriteLine("Sum: " + items.Sum()); Console.WriteLine("Product: " + items.Product()); Console.WriteLine("Min: " + items.Min()); Console.WriteLine("Max: " + items.Max()); Console.WriteLine("Average: " + items.Average()); }
public override string WriteTable(out int itemCount) { itemCount = -1; var iPId = _rules.Fields.GetHeaderIndex(FieldName.InventoryProductId); var iQuan = _rules.Fields.GetHeaderIndex(FieldName.InventoryQuantity); var indexes = new[] { iPId, iQuan }; if (indexes.Min<int>() < 0) return string.Format("(bad header: {0})", Header.Aggregate((w, j) => string.Format("{0},{1}", w, j))); var maxIndex = indexes.Max<int>(); _progress.StartTask("Parsing data", "items", null, Rows.Count); var data = new List<InventoryRecord>(); try { data.AddRange(from cols in Rows where cols.Count() > maxIndex select new InventoryRecord(cols[iPId], cols[iQuan])); } catch (Exception ex) { return ex.Message; } _progress.EndTask(-1, "completed"); if (data.Count < 1) return "no data"; itemCount = data.Count; _progress.UpdateTable(itemCount, -1, "Writing table"); var status = TableAccess.Instance.WriteTable(_rules.Alias, CartExtractor.InventoryFilename, data); _progress.UpdateTable(itemCount, -1, status); //Now the real work begins --convert new inventory data to DynamicUpdate Exclusions ProcessInventory(data); return status; }
/// <summary> /// Returns the length of ribbon required to wrap the specified present. /// </summary> /// <param name="present">The present to calculate the required length of ribbon for.</param> /// <returns>The length of ribbon, in feet, required to wrap the present.</returns> private static int GetRibbonLength(Present present) { var perimetersOfSides = new[] { (present.Length + present.Width) * 2, (present.Width + present.Height) * 2, (present.Height + present.Length) * 2, }; int smallestPerimeter = perimetersOfSides.Min(); int lengthForBow = present.Height * present.Length * present.Width; return smallestPerimeter + lengthForBow; }
/// <summary> /// Returns the area of wrapping paper required to wrap the specified present. /// </summary> /// <param name="present">The present to calculate the required area of wrapping paper for.</param> /// <returns>The area of wrapping paper, in square feet, required to wrap the present.</returns> private static int GetWrappingPaperArea(Present present) { int surfaceArea = (2 * present.Length * present.Width) + (2 * present.Width * present.Height) + (2 * present.Height * present.Length); var areasOfSides = new[] { present.Length * present.Width, present.Width * present.Height, present.Height * present.Length, }; int extra = areasOfSides.Min(); return surfaceArea + extra; }
/// <summary> /// Gets the hue as a 0-360 value, representing the degree of rotation /// </summary> /// <param name="color">Color to get the hue of</param> /// <returns>Hue as a 0-360 value, representing the degree of rotation</returns> public static float GetHue(this Color color) { // Any shade of white has no hue if (color.R == color.G && color.G == color.B) { return 0; } float hue = 0; float red = (float)color.R / 255.0f; float green = (float)color.G / 255.0f; float blue = (float)color.B / 255.0f; float[] colorArray = new[] { red, green, blue }; float max = colorArray.Max(); float min = colorArray.Min(); float delta = max - min; if (red.Equals(max)) { hue = (green - blue) / delta; } else if (green.Equals(max)) { hue = 2 + ((blue - red) / delta); } else { hue = 4 + ((red - green) / delta); } return ((hue * 60) + 360) % 360; }
public void MaxMin_Work_For_Classes() { var ints = new[] {0, 2, 5, 3}.Select(i => i == 0 ? null : (object) i); Assert.AreEqual(5, ints.Max(Comparer<object>.Default), "Max"); Assert.AreEqual(2, ints.Min(Comparer<object>.Default), "Min"); }
public override string WriteTable(out int itemCount) { itemCount = -1; string filename; int iId, iName; switch (_group) { case DataGroup.CategoryNames: if (!_rules.Fields.Att1Enabled || _rules.UseDepartmentsAsCategories) return "rule is turned off"; filename = CartExtractor.Att1Filename; iId = _rules.Fields.GetHeaderIndex(FieldName.Att1NameId); iName = _rules.Fields.GetHeaderIndex(FieldName.Att1NameName); break; case DataGroup.ManufacturerNames: if (!_rules.Fields.Att2Enabled) return "rule is turned off"; if (!_rules.ExtractAtt2Names) return "export is not required"; filename = CartExtractor.Att2Filename; iId = _rules.Fields.GetHeaderIndex(FieldName.Att2NameId); iName = _rules.Fields.GetHeaderIndex(FieldName.Att2NameName); break; case DataGroup.DepartmentNames: if (!_rules.ExportDepartmentNames && !_rules.UseDepartmentsAsCategories) return "export is not required"; filename = _rules.UseDepartmentsAsCategories ? CartExtractor.Att1Filename : CartExtractor.DepartmentFilename; iId = _rules.Fields.GetHeaderIndex(FieldName.DepartmentNameId); iName = _rules.Fields.GetHeaderIndex(FieldName.DepartmentNameName); break; default: throw new Exception("cannot write attribute table for " + _group.ToString()); } var indexes = new[] { iId, iName }; if (indexes.Min<int>() < 0) return string.Format("(bad header: {0})", Header.Aggregate((w, j) => string.Format("{0},{1}", w, j))); var minCols = indexes.Max<int>(); var errMsg = new StringBuilder(); var attributes = new List<AttributeRecord>(); try { attributes.AddRange(from cols in Rows where cols.Count() > minCols select new AttributeRecord { Id = cols[iId], Name = _cart.CleanUpTitle(cols[iName].Replace(",", "")) //remove commas }); } catch (Exception ex) { errMsg.Append(string.Format("Error: {0}\n", Input.GetExMessage(ex))); } finally { if (BoostLog.Instance != null && errMsg.Length > 0) BoostLog.Instance.WriteEntry(EventLogEntryType.Warning, errMsg.ToString(), "", _rules.Alias); } if (attributes.Count < 1) return "no data"; itemCount = attributes.Count; _progress.UpdateTable(itemCount, -1, "Writing table"); if (_group.Equals(DataGroup.DepartmentNames)) { _cart.Departments.Clear(); //Departments.AddRange(attributes.Select(x => new ??? (x.id, x.Name))); foreach (var entry in attributes) { try { _cart.Departments.Add(entry.Id, entry.Name); } catch (Exception ex) //duplicate Id? { if (BoostLog.Instance != null) BoostLog.Instance.WriteEntry(EventLogEntryType.Warning, string.Format("Error adding Department ({0}: {1}", entry.Id, entry.Name), ex, _rules.Alias); } } } return TableAccess.Instance.WriteTable(_rules.Alias, filename, attributes); }
/// <summary> /// Выполняет операцию кроссовера к генам двух особей /// </summary> /// <param name="alpha">Инициирующий</param> /// <param name="beta">Инициируемый</param> /// <returns>Потомок</returns> private Organism Crossover(Organism alpha, Organism beta) { try { if (alpha.GenesCount != beta.GenesCount) { throw new ArgumentOutOfRangeException("alpha", @"Chromosome lengths must be different"); } int length = alpha.GenesCount; var offspring = new Organism {Factors = alpha.Factors}; //Сгенерируем точки кроссовера var crossoverPoints = new[] {_random.Next(length), _random.Next(length)}; int crossoverStart = crossoverPoints.Min(); //Начало отрезка - меньшая точка int crossoverEnd = crossoverPoints.Max(); //Конец - большая //Получаем новую хромосому, заменяя гены инициируемого организма в [start; end] генами из инициирующего. // A {Ai..As..Ae..An} + B {Bi..Bs..Be..Bn} = Descendant {Bi..Bs-1,As..Ae,Be+1..Bn} for (int i = 0; i < length; i++) if ((i >= crossoverStart) && (i <= crossoverEnd)) offspring.AddGene(alpha.GetGene(i)); else offspring.AddGene(beta.GetGene(i)); offspring.Factors = offspring.GenerateFactors(); return offspring; } catch (Exception e) { throw new Exception("Cant crossover", e); } }
/// <summary> /// Возвращает потомка хромосомы A и B (порядок не важен) /// Так же мутирует один ген потомка с определенной вероятностью. /// </summary> /// <param name="chromosomeA">Хромосома A</param> /// <param name="chromosomeB">Хромосома B</param> /// <param name="random">ГПСЧ</param> /// <returns>Хромосома A+B</returns> private string CrossOver(string chromosomeA, string chromosomeB, Random random) { int length = chromosomeA.Length; //длина хромосомы string offspring = ""; //потомок //С вероятностью 0.5 инициирующей особью будет A if (random.NextDouble() <= 0.5) { // A <-> B string t = chromosomeA; chromosomeA = chromosomeB; chromosomeB = t; } //Сгенерируем точки кроссовера: var points = new[] {random.Next(length), random.Next(length)}; int start = points.Min(); //Начало отрезка - меньшая точка int end = points.Max(); //Конец - большая //Получаем новую хромосому, заменяя гены инициируемой хромосомы в [start; end] генами из инициирующей. // A {Ai..As..Ae..An} + B {Bi..Bs..Be..Bn} = Descendant {Bi..Bs-1,As..Ae,Be+1..Bn} for (int i = 0; i < length; i++) { if (i >= start && i <= end) offspring += chromosomeA[i]; else offspring += chromosomeB[i]; } char[] chars = offspring.ToCharArray(); for (int index = 0; index < chars.Length; index++) { if (random.NextDouble() <= _mutationRate) { chars[index] = (chars[index] == '0') ? '1' : '0'; } } //Мутируем один ген с вероятностью MutatuonRate return offspring; }
public void MaxMin_Work_For_Structs() { var ints = new[] {0, 5, 3, 0}; Assert.AreEqual(5, ints.Max(Comparer<int>.Default), "Max"); Assert.AreEqual(0, ints.Min(Comparer<int>.Default), "Min"); }
static double trajectoryTime(double d, double v, double a) { // d = v*t + a/2*t^2 // a/2 * t^2 + v * t - d = 0 => t = -v/2/(a/2) +- SQRT(v^2 - 4*(a/2)*(-d)) / (2*a/2) => t = -v/a +- SQRT(v^2 + 2ad) / a // A * x^2 + B * x + C = 0 => x = -B/2A +- SQRT(B^2-4AC) / 2A // x = t, A = a/2, B = v, C = -d if (a == 0) { return d / v; } else { var sqrt = Math.Abs(Math.Sqrt(v * v + 2 * a * d) / a); var result1 = -v / a + sqrt; var result2 = -v / a - sqrt; var validTimes = new[] { result1, result2 }.Where(x => x >= 0); var shortest_time = validTimes.Any() ? validTimes.Min() : 0; return shortest_time; } }
/// <summary> /// This function will calculate what sums it should advise to the user. /// </summary> private void calcAdvise() { int[] numbers = new[] { percPlus, percMinus, percTimes, percDevide }; int min = numbers.Min(); if (min == percPlus) { adviseSums = "plus"; return; } if (min == percMinus) { adviseSums = "minus"; return; } if (min == percTimes) { adviseSums = "times"; return; } if (min == percDevide) { adviseSums = "devide"; return; } }
public void NegativeNumberExceptionTest() { bool catchException = false; try { int[] a = new[] {5, -5, 6}; //Throwing possible exceptions if (a == null) throw new ArgumentNullException(); if(a.Min()<0) throw new ArgumentOutOfRangeException(); if(a.Length==0) throw new ArgumentException(); //Looking for max value and create array int maxValue = a.Max(); int[] result = new int[maxValue + 1]; // And now the counting operation foreach (int i1 in a) { result[i1]++; } int[] temp = result; } catch (ArgumentOutOfRangeException) { catchException = true; } if (catchException) Assert.Pass(); else Assert.Fail(); }
public HttpResponseMessage Draw(double? minLon, double? maxLon, double? minLat, double? maxLat, int? maxImgWidth, int? maxImgHeight) { var shapefilePath = HostingEnvironment.MapPath("~/App_Data/builtupp_usa/builtupp_usa.shp"); ITransformation<GeographicCoordinate, Point2> transformation = null; var targetCrs = EpsgMicroDatabase.Default.GetCrs(3005); LongitudeDegreeRange dataLongitudeRange; Range dataLatitudeRange; using (var shapeFile = Shapefile.Open(shapefilePath)) { dataLongitudeRange = new LongitudeDegreeRange(shapeFile.Extent.MinX, shapeFile.Extent.MaxX); dataLatitudeRange = new Range(shapeFile.Extent.MinY, shapeFile.Extent.MaxY); var dataCrs = EpsgMicroDatabase.Default.GetCrs(4326); var pathGenerator = new EpsgCrsCoordinateOperationPathGenerator(); var paths = pathGenerator.Generate(dataCrs, targetCrs); var compiler = new StaticCoordinateOperationCompiler(); var firstTransfom = paths.Select(p => { return compiler.Compile(p); }).First(x => x != null); transformation = firstTransfom as ITransformation<GeographicCoordinate, Point2>; if (transformation == null && firstTransfom is IEnumerable<ITransformation>) transformation = new CompiledConcatenatedTransformation<GeographicCoordinate, Point2>((IEnumerable<ITransformation>)firstTransfom); } var geoMbrMin = new GeographicCoordinate(minLat ?? dataLatitudeRange.Low, minLon ?? dataLongitudeRange.Start); var geoMbrMax = new GeographicCoordinate(maxLat ?? dataLatitudeRange.High, maxLon ?? dataLongitudeRange.End); var geoMbrTL = new GeographicCoordinate(geoMbrMax.Latitude, geoMbrMin.Longitude); var geoMbrTR = new GeographicCoordinate(geoMbrMin.Latitude, geoMbrMax.Longitude); var projectedMbrPoints = new[] { geoMbrMin, geoMbrMax, geoMbrTL, geoMbrTR, new GeographicCoordinate(geoMbrMin.Latitude, Math.Abs(geoMbrMin.Longitude + geoMbrMax.Longitude) / 2.0) } .Select(transformation.TransformValue) .ToArray(); var projectedExtent = new Mbr( new Point2(projectedMbrPoints.Min(x => x.X), projectedMbrPoints.Min(x => x.Y)), new Point2(projectedMbrPoints.Max(x => x.X), projectedMbrPoints.Max(x => x.Y)) ); var geogMapOrigin = new GeographicCoordinate(dataLatitudeRange.Mid, dataLongitudeRange.Mid); var mapOrigin = transformation.TransformValue(geogMapOrigin); var mapOffset = new Vector2(0/*-(mapOrigin.X - projectedExtent.X.Mid)*/, projectedExtent.Height / 2.0); var imageSizeLimits = new Vector2(maxImgWidth ?? 300, maxImgHeight ?? 300); if (imageSizeLimits.X > 4096 || imageSizeLimits.Y > 4096) throw new ArgumentException("Image size too large"); var dataRatio = new Vector2(projectedExtent.Width / imageSizeLimits.X, projectedExtent.Height / imageSizeLimits.Y); var lowCorner = projectedExtent.Min; Vector2 desiredImageSize; double imageScaleFactor; if (dataRatio.Y < dataRatio.X) { imageScaleFactor = imageSizeLimits.X / projectedExtent.Width; desiredImageSize = new Vector2(imageSizeLimits.X, (int)(projectedExtent.Height * imageScaleFactor)); } else { imageScaleFactor = imageSizeLimits.Y / projectedExtent.Height; desiredImageSize = new Vector2((int)(projectedExtent.Width * imageScaleFactor), imageSizeLimits.Y); } using (var image = new System.Drawing.Bitmap((int)desiredImageSize.X, (int)desiredImageSize.Y)) using (var graphics = Graphics.FromImage(image)) { graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; var shapeSource = new PointShapefileShapeSource(shapefilePath); var shapeReader = new ShapeReader(shapeSource); using (var shapeEnumerator = shapeReader.GetEnumerator()) { var sourceCoordinates = ReadPagesToGeographicCoordinate(shapeEnumerator).SelectMany(x => x); var pointColor = Color.Black; var circleFillBrush = new SolidBrush(Color.FromArgb(64,16,64,128)); var featureRadius = 3.0; var featureDiameter = featureRadius * 2; var featureDiameterFloat = (float)featureDiameter; var topLeftOffset = new Vector2(-featureRadius,-featureRadius); foreach (var transformedPoint in transformation.TransformValues(sourceCoordinates)) { var offsetPoint = transformedPoint.Difference(lowCorner).Add(mapOffset); var scaledPoint = offsetPoint.GetScaled(imageScaleFactor); var screenPoint = new Point2(scaledPoint.X, image.Height - scaledPoint.Y); var drawTopLeft = screenPoint.Add(topLeftOffset); graphics.FillEllipse(circleFillBrush, (float)drawTopLeft.X, (float)drawTopLeft.Y, featureDiameterFloat, featureDiameterFloat); } } var result = new HttpResponseMessage(HttpStatusCode.OK); byte[] imageBytes; using (var memoryStream = new MemoryStream()) { image.Save(memoryStream, ImageFormat.Png); imageBytes = memoryStream.ToArray(); } result.Content = new ByteArrayContent(imageBytes); result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png"); return result; } }
/// <summary> /// Transforms the rectangle with the current matrix. /// </summary> /// <remarks> /// This returns a rectangle that encompasses the specified <paramref name="rect"/> after it is translated. /// When rotating, this means that the new rectangle may be larger in size to encompass the translated rectangle. /// </remarks> /// <returns>A new rectangle that encompasses the translated <paramref name="rect"/>.</returns> /// <param name="matrix">Matrix to transform each point of the rectangle.</param> /// <param name="rect">Rectangle to transform.</param> public static RectangleF TransformRectangle(this IMatrix matrix, RectangleF rect) { var points = new[] { matrix.TransformPoint(rect.TopLeft), matrix.TransformPoint(rect.TopRight), matrix.TransformPoint(rect.BottomLeft), matrix.TransformPoint(rect.BottomRight) }; return RectangleF.FromSides(points.Min(r => r.X), points.Min(r => r.Y), points.Max(r => r.X), points.Max(r => r.Y)); }
public string try_find_log_syntax(string[] lines) { if ( lines.Length < 5) return UNKNOWN_SYNTAX; string syntax = ""; // see if we have $(file) first int pos1 = lines[0].IndexOf("\\"), pos2 = lines[0].IndexOf("\\"); if ( pos1 < 20 && pos2 < 20) syntax += "$file "; List<int> times = new List<int>(), dates = new List<int>(), levels = new List<int>(); foreach ( string line in lines) { times.Add( time_or_date_pos(line, ':')); int by_minus = time_or_date_pos(line, '-'); int by_div = time_or_date_pos(line, '/'); dates.Add(by_minus > 0 ? by_minus : by_div); int info = line.IndexOf(" INFO "); int err = line.IndexOf(" ERROR "); int fatal = line.IndexOf(" FATAL "); int dbg = line.IndexOf(" DEBUG "); int warn = line.IndexOf(" WARN "); if ( info > 0) levels.Add(info); else if ( err > 0) levels.Add(err); else if ( fatal > 0) levels.Add(fatal); else if ( dbg > 0) levels.Add(dbg); else if ( warn > 0) levels.Add(warn); } int[] all = new[] { times.Count, dates.Count, levels.Count }; int min = all.Min(), max = all.Max(); if (max - min > 1) // one of the times/dates/levels did not work return UNKNOWN_SYNTAX; // at this point, we might have one line that was not fully parsed (thus, not all : time/date/level are parsed -> thus, we should ignore it) if (max - min == 1) { if ( times.Count == max) times.RemoveAt(min); if ( dates.Count == max) dates.RemoveAt(min); if ( levels.Count == max) levels.RemoveAt(min); } bool ok = is_consistently_sorted(times,dates) != 0 && is_consistently_sorted(times,levels) != 0 && is_consistently_sorted(dates,levels) != 0; if ( !ok) // full line is a message return UNKNOWN_SYNTAX; List< Tuple<string,List<int>> > sorted = new List<Tuple<string,List<int>>>(); // ... better to take the second line, since the first line might not be complete string first_line = lines.Length > 1 ? lines[1] : lines[0]; List<int> end_indexes = new List<int>(); if (is_consistently_present(times)) { int len = end_of_time_index(first_line, times[0]) - times[0]; end_indexes.Add(times[0] + len); sorted.Add(new Tuple<string, List<int>>("$time[" + times[0] + "," + len + "]", times)); } if (is_consistently_present(dates)) { int len = end_of_date_index(first_line, dates[0]) - dates[0]; end_indexes.Add(dates[0] + len); sorted.Add(new Tuple<string, List<int>>("$date[" + dates[0] + "," + len + "]", dates)); } if (is_consistently_present(levels)) { int len = 5; end_indexes.Add(levels[0] + 1 + len); sorted.Add(new Tuple<string, List<int>>("$level[" + (levels[0] + 1) + "," + len + "]", levels)); } sorted.Sort( (x,y) => is_consistently_sorted(x.Item2,y.Item2) ); foreach ( Tuple<string,List<int>> sli in sorted) syntax += sli.Item1 + " "; end_indexes.Sort(); if (end_indexes.Count > 0) { int start_msg = end_indexes.Last() + 1; // account for logs that have a starting line at beginning of msg if (first_line[start_msg] == '-') ++start_msg; while (start_msg < first_line.Length && Char.IsWhiteSpace(first_line[start_msg])) ++start_msg; syntax += "$msg[" + start_msg + "]"; } else syntax += UNKNOWN_SYNTAX; return syntax; }
public static Hsla ToHsla( this Rgba color ) { var r = color.Red / 255.0; var g = color.Green / 255.0; var b = color.Blue / 255.0; var a = color.Alpha / 255.0; var rgb = new[] {r, g, b}; var min = rgb.Min(); var max = rgb.Max(); var maxLessMin = max - min; var hsla = new Hsla { Hue = 0, Saturation = 0, Lightness = 0, Alpha = a }; var l = ( max + min ) / 2.0; if( l <= 0 ) return hsla; var s = maxLessMin; if( s > 0 ) { s /= l <= 0.5 ? max + min : 2.0 - maxLessMin; } else { return hsla; } var r2 = ( max - r ) / maxLessMin; var g2 = ( max - g ) / maxLessMin; var b2 = ( max - b ) / maxLessMin; double h; if( r == max ) { h = ( g == min ? 5.0 + b2 : 1.0 - g2 ); } else if( g == max ) { h = ( b == min ? 1.0 + r2 : 3.0 - b2 ); } else { h = ( r == min ? 3.0 + g2 : 5.0 - r2 ); } h /= 6.0; return new Hsla { Hue = h, Saturation = s, Lightness = l, Alpha = a }; }