public int Column(float column) { return(UnitConverter.ConvertUnitsToPixels(this.Dpi, column, Unit.Column)); }
public void MilesToKilometers_GivenSingleValue_ReturnsCorrectString(string input, string expected) { var converter = new UnitConverter(); Assert.Equal(expected, converter.MilesToKilometers(input).Single()); }
public int Cm(float cm) { return(UnitConverter.ConvertUnitsToPixels(this.Dpi, cm, Unit.Cm)); }
public int Point(float point) { return(UnitConverter.ConvertUnitsToPixels(this.Dpi, point, Unit.Point)); }
public void TryConvertByAbbreviation_ReturnsTrueOnSuccessAndOutputsResult(double expectedValue, double inputValue, string quantityTypeName, string fromUnit, string toUnit) { Assert.True(UnitConverter.TryConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, out double result), "TryConvertByAbbreviation() return value."); Assert.Equal(expectedValue, result); }
public int Inch(float inches) { return(UnitConverter.ConvertUnitsToPixels(this.Dpi, inches, Unit.Inch)); }
//builds a street from the center of a large unit to the edge in the given direction private void buildMidCurve(TULarge lu, Vector2 outsideConPoint, Dir dir, TransportUnit powMid, PSide side) //powmid is the mid unit that contains the large's conpoint { int gix = 0, giy = 0; //goal index x and y of the goal mid unit float outSlope = GridMath.findSlope(lu.conPoint, outsideConPoint); //find the average slope from this conPoint to the outsideConPoint Debug.DrawLine(UnitConverter.getWP(new SurfacePos(PSide.TOP, lu.conPoint.x, lu.conPoint.y), 10000, sideLength), UnitConverter.getWP(new SurfacePos(PSide.TOP, outsideConPoint.x, outsideConPoint.y), 10000, sideLength), Color.blue, Mathf.Infinity); //determine the goal mid unit if (dir == Dir.RIGHT) { //find the index of the goal mid unit float goalPosX = (lu.indexI + 1) * sideLengthLarge; //the x value of the very right side of the large unit in mid units float goalPosY = GridMath.findY(goalPosX, lu.conPoint, outSlope); //the y value on the line between teh two conpoints GridMath.findMidIndexfromPoint(new Vector2(goalPosX - 0.5f, goalPosY), midTUWidth, out gix, out giy); TransportUnit goalMid = buildMid(gix, giy, side); goalMid.conRight = true; goalMid.RightLev = 1; //Debug.DrawLine(UnitConverter.getWP(new SurfacePos(PSide.TOP, lu.conPoint.x, lu.conPoint.y), 10000, 1024), // UnitConverter.getWP(new SurfacePos(PSide.TOP, goalPosX, goalPosY), 10000, 1024), Color.blue, Mathf.Infinity); } else if (dir == Dir.LEFT) { //find the index of the goal mid unit float goalPosX = (lu.indexI) * sideLengthLarge; //the x value of the very right side of the large unit in mid units float goalPosY = GridMath.findY(goalPosX, lu.conPoint, outSlope); //the y value on the line between teh two conpoints GridMath.findMidIndexfromPoint(new Vector2(goalPosX + 0.5f, goalPosY), midTUWidth, out gix, out giy); //buildMid(gix, giy, side).conLeft=true; } else if (dir == Dir.UP) { //find the index of the goal mid unit float goalPosY = (lu.indexJ + 1) * sideLengthLarge; //the x value of the very right side of the large unit in mid units float goalPosX = GridMath.findX(goalPosY, lu.conPoint, outSlope); //the y value on the line between teh two conpoints GridMath.findMidIndexfromPoint(new Vector2(goalPosX, goalPosY - 0.5f), midTUWidth, out gix, out giy); TransportUnit goalMid = buildMid(gix, giy, side); goalMid.conUp = true; goalMid.UpLev = 1; } else if (dir == Dir.DOWN) { //find the index of the goal mid unit float goalPosY = (lu.indexJ) * sideLengthLarge; //the x value of the very right side of the large unit in mid units float goalPosX = GridMath.findX(goalPosY, lu.conPoint, outSlope); //the y value on the line between teh two conpoints GridMath.findMidIndexfromPoint(new Vector2(goalPosX, goalPosY + 0.5f), midTUWidth, out gix, out giy); } //the x and y index of the mid unit last created in the loop(starts as if pows were last created) //int lastix = powIndexX, lastiy = powIndexY; TransportUnit lastMid = powMid; while (true) { //the difference in indexes between the current and goal mid units int xdif = gix - lastMid.indexI; int ydif = giy - lastMid.indexJ; //the direction to move in this loop iteration(1=x 2=y) int movedir; //if they are both not on the goal index, pick a random one to change if (xdif != 0 && ydif != 0) { movedir = lu.rng.NextDouble() > 0.5 ? 1:2; } else if (xdif != 0) { movedir = 1; } else if (ydif != 0) { movedir = 2; } else //if they are both zero we are done maybe? { break; //? } //the index of the mid unit to be created int curix = lastMid.indexI, curiy = lastMid.indexJ; //if moving in the x direction if (movedir == 1) { if (xdif > 0) { curix++; } else { curix--; } } else //movedir==2 { if (ydif > 0) { curiy++; } else { curiy--; } } //create or retrieve the new mid unit TransportUnit curMid = buildMid(curix, curiy, side); //set its conpoint if it has not already been set curMid.setConPoint(new Vector2((curix + (float)lu.rng.NextDouble()) * midTUWidth, (curiy + (float)lu.rng.NextDouble()) * midTUWidth)); //MyDebug.placeMarker(UnitConverter.getWP(new SurfacePos(PSide.TOP, curMid.conPoint.x, curMid.conPoint.y), 10000, 1024), 5); connectUnits(curMid, lastMid, 1); lastMid = curMid; } }
public void LengthValueFromDIPToMicron_Should_Succeed() { var value = UnitConverter.LengthValueFromDIPToMicron(100d); Assert.IsTrue(value > 0); }
private static IEnumerable <double> MakeStatistic(IEnumerable <MetricDatum> data, StandardUnit unit, Func <StatisticSet, double> func) { return(data.Select(d => d.StatisticValues == null ? UnitConverter.Convert(d.Value).From(d.Unit).To(unit) : UnitConverter.Convert(func(d.StatisticValues)).From(d.Unit).To(unit))); }
//populates a large unit with mid units private void populateLarge(TULarge lu, SurfaceUnit lus) { //Debug.Log("built " + lus); //clear the index list indexList.Clear(); //find the mid unit that the large unit's conpoint falls in int powIndexX, powIndexY; GridMath.findMidIndexfromPoint(lu.conPoint, midTUWidth, out powIndexX, out powIndexY); TransportUnit powMid = buildMid(powIndexX, powIndexY, lus.side); powMid.conPoint = lu.conPoint; //same conpoint, or could change to not be, doesn't really matter powMid.conSet = true; TULarge rightLU = getLarge(new SurfaceUnit(lus.side, lus.u + 1, lus.v)); TULarge leftLU = getLarge(new SurfaceUnit(lus.side, lus.u - 1, lus.v)); TULarge upLU = getLarge(new SurfaceUnit(lus.side, lus.u, lus.v + 1)); TULarge downLU = getLarge(new SurfaceUnit(lus.side, lus.u, lus.v - 1)); //Vector2 conPointRight = rightLU.conPoint; //determine in which direction the streets should be built bool conRight = lu.conRight; bool conLeft = false; bool conUp = lu.conUp; bool conDown = false; //check for null large units if (leftLU != null) { conLeft = leftLU.conRight; } if (downLU != null) { conDown = downLU.conUp; } //list of the index of all the mid transport units that are connected in some way if (conRight) { buildMidCurve(lu, rightLU.conPoint, Dir.RIGHT, powMid, lus.side); } if (conLeft) { buildMidCurve(lu, leftLU.conPoint, Dir.LEFT, powMid, lus.side); } if (conUp) { buildMidCurve(lu, upLU.conPoint, Dir.UP, powMid, lus.side); } if (conDown) { buildMidCurve(lu, downLU.conPoint, Dir.DOWN, powMid, lus.side); } //build some level 2 streets coming off the level 1 streets or other level 2 streets int numStreets = 80; //(int)(Random.value*5); for (int i = 0; i < numStreets; i++) { int startNum = lu.rng.Next(0, indexList.Count); TransportUnit startMid = indexList[startNum]; buildLev2(lu, startMid, lu.rng.Next(2, 80), lus.side); } Vector3 topright = UnitConverter.getWP(new SurfacePos(lus.side, (lu.indexI + 1) * sideLengthLarge, (lu.indexJ + 1) * sideLengthLarge), 10000, sideLength); Vector3 topleft = UnitConverter.getWP(new SurfacePos(lus.side, (lu.indexI) * sideLengthLarge, (lu.indexJ + 1) * sideLengthLarge), 10000, sideLength); Vector3 botright = UnitConverter.getWP(new SurfacePos(lus.side, (lu.indexI + 1) * sideLengthLarge, (lu.indexJ) * sideLengthLarge), 10000, sideLength); Vector3 botleft = UnitConverter.getWP(new SurfacePos(lus.side, (lu.indexI) * sideLengthLarge, (lu.indexJ) * sideLengthLarge), 10000, sideLength); Debug.DrawLine(topleft, botleft, Color.red, Mathf.Infinity); Debug.DrawLine(topleft, topright, Color.red, Mathf.Infinity); Debug.DrawLine(topright, botright, Color.red, Mathf.Infinity); Debug.DrawLine(botright, botleft, Color.red, Mathf.Infinity); lu.populated = true; }
public bool WriteInPort(int port, string contentInHex) { Data = UnitConverter.HexToBinary(contentInHex); UpdateGui?.Invoke(); return(true); }
public double Convert(QuantityValue fromValue, Enum fromUnitValue, Enum toUnitValue) { return(UnitConverter.Convert(fromValue, fromUnitValue, toUnitValue)); }
public void LengthValueFromMicronToDIP_Should_Succeed() { var value = UnitConverter.LengthValueFromMicronToDIP(100); Assert.IsTrue(value > double.Epsilon); }
public static void ExportActiveView(IActiveView pView, long iOutputResolution, long lResampleRatio, string sExportType, string sOutputDir, string sOutputName, Boolean bClipToGraphicsExtent = true, IEnvelope pEnvelope = null) { //解决文件名错误 IActiveView docActiveView = pView; IExport docExport; long iPrevOutputImageQuality; IOutputRasterSettings docOutputRasterSettings; IEnvelope PixelBoundsEnv; tagRECT exportRECT; tagRECT DisplayBounds; IDisplayTransformation docDisplayTransformation; IPageLayout docPageLayout; IEnvelope docMapExtEnv; if (pEnvelope == null) pEnvelope = GetGraphicsExtent(pView); long hdc; long tmpDC; //string sNameRoot; long iScreenResolution; bool bReenable = false; IEnvelope docGraphicsExtentEnv; IUnitConverter pUnitConvertor; if (GetFontSmoothing()) { bReenable = true; DisableFontSmoothing(); if (GetFontSmoothing()) { //font smoothing is NOT successfully disabled, error out. return; } //else font smoothing was successfully disabled. } // The Export*Class() type initializes a new export class of the desired type. if (String.Compare(sExportType,"PDF",true) == 0) { docExport = new ExportPDFClass(); } else if (String.Compare(sExportType,"EPS",true) == 0) { docExport = new ExportPSClass(); } else if (String.Compare(sExportType,"AI",true) == 0) { docExport = new ExportAIClass(); } else if (String.Compare(sExportType,"BMP",true) == 0) { docExport = new ExportBMPClass(); } else if (String.Compare(sExportType,"TIFF",true) == 0) { docExport = new ExportTIFFClass(); } else if (String.Compare(sExportType,"SVG",true) == 0) { docExport = new ExportSVGClass(); } else if (String.Compare(sExportType,"PNG",true) == 0) { docExport = new ExportPNGClass(); } else if (String.Compare(sExportType,"GIF",true) == 0) { docExport = new ExportGIFClass(); } else if (String.Compare(sExportType,"EMF",true) == 0) { docExport = new ExportEMFClass(); } else if (String.Compare(sExportType,"JPEG",true) == 0 || String.Compare(sExportType,"JPG",true) == 0) { docExport = new ExportJPEGClass(); } else { MessageBox.Show("!!不支持的格式 " + sExportType + ", 默认导出 EMF."); sExportType = "EMF"; docExport = new ExportEMFClass(); } // save the previous output image quality, so that when the export is complete it will be set back. docOutputRasterSettings = docActiveView.ScreenDisplay.DisplayTransformation as IOutputRasterSettings; iPrevOutputImageQuality = docOutputRasterSettings.ResampleRatio; if (docExport is IExportImage) { // always set the output quality of the DISPLAY to 1 for image export formats SetOutputQuality(docActiveView, 1); } else { // for vector formats, assign the desired ResampleRatio to control drawing of raster layers at export time SetOutputQuality(docActiveView, lResampleRatio); } //set the name root for the export // sNameRoot = "ExportActiveViewSampleOutput"; //set the export filename (which is the nameroot + the appropriate file extension) docExport.ExportFileName = sOutputDir + "\\" + sOutputName + "." + docExport.Filter.Split('.')[1].Split('|')[0].Split(')')[0]; tmpDC = GetDC(0); iScreenResolution = GetDeviceCaps((int)tmpDC, 88); //88 is the win32 const for Logical pixels/inch in X) ReleaseDC(0, (int)tmpDC); docExport.Resolution = iOutputResolution; if (docActiveView is IPageLayout) { //get the bounds of the "exportframe" of the active view. DisplayBounds = docActiveView.ExportFrame; //set up pGraphicsExtent, used if clipping to graphics extent. docGraphicsExtentEnv = pEnvelope; } else { //Get the bounds of the deviceframe for the screen. docDisplayTransformation = docActiveView.ScreenDisplay.DisplayTransformation; DisplayBounds = docDisplayTransformation.get_DeviceFrame(); } PixelBoundsEnv = new Envelope() as IEnvelope; if (bClipToGraphicsExtent && (docActiveView is IPageLayout)) { docGraphicsExtentEnv = pEnvelope; docPageLayout = docActiveView as PageLayout; pUnitConvertor = new UnitConverter(); //assign the x and y values representing the clipped area to the PixelBounds envelope PixelBoundsEnv.XMin = 0; PixelBoundsEnv.YMin = 0; PixelBoundsEnv.XMax = pUnitConvertor.ConvertUnits(docGraphicsExtentEnv.XMax, docPageLayout.Page.Units, esriUnits.esriInches) * docExport.Resolution - pUnitConvertor.ConvertUnits(docGraphicsExtentEnv.XMin, docPageLayout.Page.Units, esriUnits.esriInches) * docExport.Resolution; PixelBoundsEnv.YMax = pUnitConvertor.ConvertUnits(docGraphicsExtentEnv.YMax, docPageLayout.Page.Units, esriUnits.esriInches) * docExport.Resolution - pUnitConvertor.ConvertUnits(docGraphicsExtentEnv.YMin, docPageLayout.Page.Units, esriUnits.esriInches) * docExport.Resolution; //'assign the x and y values representing the clipped export extent to the exportRECT exportRECT.bottom = (int)(PixelBoundsEnv.YMax) + 1; exportRECT.left = (int)(PixelBoundsEnv.XMin); exportRECT.top = (int)(PixelBoundsEnv.YMin); exportRECT.right = (int)(PixelBoundsEnv.XMax) + 1; //since we're clipping to graphics extent, set the visible bounds. docMapExtEnv = docGraphicsExtentEnv; } else { double tempratio = iOutputResolution / iScreenResolution; double tempbottom = DisplayBounds.bottom * tempratio; double tempright = DisplayBounds.right * tempratio; //'The values in the exportRECT tagRECT correspond to the width //and height to export, measured in pixels with an origin in the top left corner. exportRECT.bottom = (int)Math.Truncate(tempbottom); exportRECT.left = 0; exportRECT.top = 0; exportRECT.right = (int)Math.Truncate(tempright); //populate the PixelBounds envelope with the values from exportRECT. // We need to do this because the exporter object requires an envelope object // instead of a tagRECT structure. PixelBoundsEnv.PutCoords(exportRECT.left, exportRECT.top, exportRECT.right, exportRECT.bottom); //since it's a page layout or an unclipped page layout we don't need docMapExtEnv. docMapExtEnv = null; } // Assign the envelope object to the exporter object's PixelBounds property. The exporter object // will use these dimensions when allocating memory for the export file. docExport.PixelBounds = PixelBoundsEnv; // call the StartExporting method to tell docExport you're ready to start outputting. hdc = docExport.StartExporting(); // Redraw the active view, rendering it to the exporter object device context instead of the app display. // We pass the following values: // * hDC is the device context of the exporter object. // * exportRECT is the tagRECT structure that describes the dimensions of the view that will be rendered. // The values in exportRECT should match those held in the exporter object's PixelBounds property. // * docMapExtEnv is an envelope defining the section of the original image to draw into the export object. docActiveView.Output((int)hdc, (int)docExport.Resolution, ref exportRECT, docMapExtEnv, null); //finishexporting, then cleanup. docExport.FinishExporting(); docExport.Cleanup(); MessageBox.Show("成功导出地图: " + docExport.ExportFileName, "提示"); //set the output quality back to the previous value SetOutputQuality(docActiveView, iPrevOutputImageQuality); if (bReenable) { EnableFontSmoothing(); bReenable = false; if (!GetFontSmoothing()) { //error: cannot reenable font smoothing. MessageBox.Show("Unable to reenable Font Smoothing", "Font Smoothing error"); } } docMapExtEnv = null; PixelBoundsEnv = null; }
//will return a TransportUnit object from the requested a base unit //OH YES THIS USES RECURSION OH MAN!!!!!!!!!!!!!!!! I'M SO PROUD OF MYSELF!!!!! public TUBase getBase(SurfaceUnit su) { //quick test check, see getMid\ if (su.u < -halfSideLength || su.u >= halfSideLength || su.v < -halfSideLength || su.v >= halfSideLength) { return(null); } //if(su.side==PSide.NONE) // return null; //the base unit to be returned eventually TUBase bu = null; //if the base unit exists in the list, return it if (baseTUs.TryGetValue(su, out bu)) { return(bu); } //if the base unit is not in the list, check if a mid unit is //the coordinates of the mid unit SurfaceUnit mus = getMidSU(su); //retrieve the actual mid unit (or not if it will never exist) TransportUnit mu = getMid(mus); //if the mid unit will never exist, the base unit will never exist if (mu == null) { return(null); } //if the mu has already been populated, the base unit will never exist if (mu.populated) { return(null); } else { //populate it /*int startu = mus.u*midTUWidth; * int startv = mus.v*midTUWidth; * for(int i = startu; i<startu+midTUWidth; i++) * { * for(int j = startv; j<startv+midTUWidth; j++) * { * //create a new base unit, set its properties, and add it to the base list * TUBase newTU = new TUBase(); * newTU.conUp = Random.value>0.5f; * newTU.conRight = Random.value>0.5f; * newTU.conPoint = new Vector2(i + Random.value, j + Random.value); * newTU.conPointWorld = UnitConverter.getWP(new SurfacePos(su.side, newTU.conPoint.x, newTU.conPoint.y), * WorldManager.curPlanet.radius, sideLength); * * baseTUs.Add(new SurfaceUnit(su.side, i, j), newTU); * } * }*/ Dictionary <SurfaceUnit, TUBase> bases = midfill.populate(mu, mus); foreach (KeyValuePair <SurfaceUnit, TUBase> pair in bases) { //Debug.Log(su.side+" " + pair.Key.u + " " + pair.Key.v); SurfaceUnit newKey = new SurfaceUnit(su.side, pair.Key.u, pair.Key.v); //if the key is not already in the list, add it if (!baseTUs.ContainsKey(newKey)) { //find the world connection point Vector3 conPointWorld = UnitConverter.getWP(new SurfacePos(su.side, pair.Value.conPoint.x, pair.Value.conPoint.y), UniverseSystem.curPlanet.radius, sideLength); conPointWorld = planet.noise.altitudePos(conPointWorld); //Debug.Log(su.side+" " + pair.Key.u + " " + pair.Key.v + " "); pair.Value.conPointWorld = conPointWorld; baseTUs.Add(newKey, pair.Value); } //Debug.Log(pair.Key); } mu.populated = true; //use recursion to return to the top of the function and get the base unit from the list(or not if it was not generated) return(getBase(su)); } }
public void TriangulateFace(Autodesk.Revit.DB.Face vFace, Transform instTransform) { try { //setup utility class LuxExporter.UnitConverter Converter = new UnitConverter(); //process face Mesh vMesh = vFace.Triangulate(); //check if we have a quad mesh (4 edges to a face) if (vMesh.Vertices.Count == 4) { //increase face counter iNumberOfFaces++; //found quad Data.NumberOfVerticesinFace = 4; //loop through all vertices and add foreach (XYZ ii in vMesh.Vertices) { XYZ point = ii; XYZ transformedPoint; //transform geometry (only required in nested families / or elements like baluster if (instTransform == null) { transformedPoint = point; } else { transformedPoint = instTransform.OfPoint(point); } //get the normal XYZ NormalAtPoint; IntersectionResult IntResult= vFace.Project(ii); if (IntResult != null) { UV UVatPoint = IntResult.UVPoint; NormalAtPoint = new XYZ(vFace.ComputeNormal(UVatPoint).X, vFace.ComputeNormal(UVatPoint).Y, vFace.ComputeNormal(UVatPoint).Z); } else { //this needs fixing!!! NormalAtPoint = new XYZ(0, 0, 0); } //convert to meter transformedPoint = Converter.ConvertPointCoordToMeter(transformedPoint); //NormalAtPoint = Converter.ConvertPointCoordToMeter(NormalAtPoint); //add to ply class Data.AddVertice(transformedPoint,NormalAtPoint); } } else { // set pointer Data.NumberOfVerticesinFace = 3; //export all triangles in face for (int i = 0; i < vMesh.NumTriangles; i++) { //increase face counter iNumberOfFaces++; MeshTriangle objTriangular = vMesh.get_Triangle(i); for (int iPointsCounter = 0; iPointsCounter < 3; iPointsCounter++) { XYZ point = objTriangular.get_Vertex(iPointsCounter); XYZ transformedPoint; //transform geometry (only required in nested families / or elements like baluster if (instTransform == null) { transformedPoint = point; } else { transformedPoint = instTransform.OfPoint(point); } XYZ NormalAtPoint; //get the normal IntersectionResult IntResult = vFace.Project(point); if (IntResult!=null) { UV UVatPoint = IntResult.UVPoint; NormalAtPoint = new XYZ(vFace.ComputeNormal(UVatPoint).X,vFace.ComputeNormal(UVatPoint).Y,vFace.ComputeNormal(UVatPoint).Z); } else { //this needs fixing NormalAtPoint = new XYZ(0, 0, 0); } //convert to meter transformedPoint = Converter.ConvertPointCoordToMeter(transformedPoint); //NormalAtPoint = Converter.ConvertPointCoordToMeter(NormalAtPoint); //add to ply class Data.AddVertice(transformedPoint,NormalAtPoint); } } } } catch (Exception ex) { System.Windows.Forms.MessageBox.Show("Error in module PLY_by_material::TriangulateMesh "+ex.Message); throw; } }
public static Temperature AmbientTemperature(TemperatureUnit TemperatureUnit) { return(UnitConverter.ConvertMeasure(new Temperature(20, Celsius), TemperatureUnit)); }
public void TryConvertByAbbreviation_ReturnsFalseForInvalidInput(double inputValue, string quantityTypeName, string fromUnit, string toUnit) { Assert.False(UnitConverter.TryConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, out double result)); Assert.Equal(0, result); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Name = Intent.Extras.GetString("name"); Address = Intent.Extras.GetString("address"); DatasetName = Intent.Extras.GetString("datasetName"); DatasetAlias = Intent.Extras.GetString("datasetAlias"); TimestampOffset = Intent.Extras.GetLong("timestampOffset"); var sourceUnit = Intent.Extras.GetString("datasetSourceUnit"); var targetUnit = Intent.Extras.GetString("datasetTargetUnit"); Title = $"{Name} ({Address})"; try { Converter = UnitConverter.Create(sourceUnit, targetUnit); Api = new ApiClient(Address); Api.Call <Api.Responses.Dataset>(new Api.Requests.Dataset(DatasetName, null, null), Canceller.Token) .ContinueWith(t => { if (t.IsCanceled) { return; } if (t.IsFaulted) { Log.Error(TAG, $"Failed to fetch dataset {DatasetName} with error {t.Exception.Flatten().InnerException}."); Toast.MakeText(this, "Failed to get performance information.", ToastLength.Short).Show(); return; } RunOnUiThread(() => { // Change units. var dataset = t .Result .dataset .Select(d => new DataPoint { Timestamp = d.Timestamp - TimestampOffset, Value = Converter.ChangeUnits(d.Value), }) .ToArray(); var minValue = dataset.Min(d => d.Value); var min = dataset.First(d => d.Value == minValue); var maxValue = dataset.Max(d => d.Value); var max = dataset.First(d => d.Value == maxValue); var width = maxValue - minValue; var datasetMap = dataset.ToDictionary(d => new BarModel { Value = d.Value, ValueCaptionHidden = true, }); var chart = new BarChartView(this) { ItemsSource = datasetMap.Keys, BarWidth = 3, BarOffset = 1, MinimumValue = min.Value - width / 2, MaximumValue = max.Value + width / 2, }; chart.AutoLevelsEnabled = false; chart.AddLevelIndicator(min.Value, StringizeValue(min.Value)); chart.AddLevelIndicator(max.Value, StringizeValue(max.Value)); chart.BarClick += (sender, args) => { DataPoint data = null; if (!datasetMap.TryGetValue(args.Bar, out data)) { return; } new AlertDialog.Builder(this) .SetCancelable(false) .SetTitle(UIConversion.FromMilliseconds(data.Timestamp).ToString()) .SetMessage(StringizeValue(data.Value)) .SetPositiveButton("OK", (s, e) => { }) .Create() .Show(); }; SetContentView(chart, new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent) ); }); }); } catch (Exception e) { Toast.MakeText(this, $"Failed to get performance information for {DatasetName} for {Title}", ToastLength.Short).Show(); Log.Error(TAG, $"Failed to start activity for dataset {DatasetName} with error {e}."); Finish(); } }
/// <summary> /// Encodes the image to the specified stream from the <see cref="ImageFrame{TPixel}"/>. /// </summary> /// <typeparam name="TPixel">The pixel format.</typeparam> /// <param name="image">The <see cref="ImageFrame{TPixel}"/> to encode from.</param> /// <param name="stream">The <see cref="Stream"/> to encode the image data to.</param> public void Encode <TPixel>(Image <TPixel> image, Stream stream) where TPixel : struct, IPixel <TPixel> { Guard.NotNull(image, nameof(image)); Guard.NotNull(stream, nameof(stream)); this.configuration = image.GetConfiguration(); ImageMetadata metadata = image.Metadata; BmpMetadata bmpMetadata = metadata.GetFormatMetadata(BmpFormat.Instance); this.bitsPerPixel = this.bitsPerPixel ?? bmpMetadata.BitsPerPixel; short bpp = (short)this.bitsPerPixel; int bytesPerLine = 4 * (((image.Width * bpp) + 31) / 32); this.padding = bytesPerLine - (int)(image.Width * (bpp / 8F)); // Set Resolution. int hResolution = 0; int vResolution = 0; if (metadata.ResolutionUnits != PixelResolutionUnit.AspectRatio) { if (metadata.HorizontalResolution > 0 && metadata.VerticalResolution > 0) { switch (metadata.ResolutionUnits) { case PixelResolutionUnit.PixelsPerInch: hResolution = (int)Math.Round(UnitConverter.InchToMeter(metadata.HorizontalResolution)); vResolution = (int)Math.Round(UnitConverter.InchToMeter(metadata.VerticalResolution)); break; case PixelResolutionUnit.PixelsPerCentimeter: hResolution = (int)Math.Round(UnitConverter.CmToMeter(metadata.HorizontalResolution)); vResolution = (int)Math.Round(UnitConverter.CmToMeter(metadata.VerticalResolution)); break; case PixelResolutionUnit.PixelsPerMeter: hResolution = (int)Math.Round(metadata.HorizontalResolution); vResolution = (int)Math.Round(metadata.VerticalResolution); break; } } } int infoHeaderSize = BmpInfoHeader.SizeV4; var infoHeader = new BmpInfoHeader( headerSize: infoHeaderSize, height: image.Height, width: image.Width, bitsPerPixel: bpp, planes: 1, imageSize: image.Height * bytesPerLine, clrUsed: 0, clrImportant: 0, xPelsPerMeter: hResolution, yPelsPerMeter: vResolution) { RedMask = Rgba32RedMask, GreenMask = Rgba32GreenMask, BlueMask = Rgba32BlueMask, Compression = BmpCompression.BitFields }; if (this.bitsPerPixel == BmpBitsPerPixel.Pixel32) { infoHeader.AlphaMask = Rgba32AlphaMask; } var fileHeader = new BmpFileHeader( type: BmpConstants.TypeMarkers.Bitmap, fileSize: BmpFileHeader.Size + infoHeaderSize + infoHeader.ImageSize, reserved: 0, offset: BmpFileHeader.Size + infoHeaderSize); #if NETCOREAPP2_1 Span <byte> buffer = stackalloc byte[infoHeaderSize]; #else byte[] buffer = new byte[infoHeaderSize]; #endif fileHeader.WriteTo(buffer); stream.Write(buffer, 0, BmpFileHeader.Size); infoHeader.WriteV4Header(buffer); stream.Write(buffer, 0, infoHeaderSize); this.WriteImage(stream, image.Frames.RootFrame); stream.Flush(); }
private void displayNutrInfo() { //check if there is a quantity if (Quantity != "") { //remove old info nutTable.Clear(); var db = DataAccessor.getDataAccessor(); //get selected food with nutrient info var foodItem = db.getFoodItem(selectedResult.food_no, UnitConverter.getMultiplier(getQuantifier(), selectedResult.food_no) * Convert.ToDouble(Quantity)); //remove extra omega values, only want totals foodItem.stripExtraOmegs(); //add preliminary table titles var colTitle = new StackLayout() { Orientation = StackOrientation.Horizontal }; colTitle.Children.Add(new Label() //nutrients { Text = "Nutrient", WidthRequest = 150, HorizontalOptions = LayoutOptions.StartAndExpand, //TextColor = (Color)App.Current.Resources["BtnBkgColor"], FontAttributes = FontAttributes.Bold }); colTitle.Children.Add(new Label() { Text = "Amount", //HorizontalOptions = LayoutOptions.StartAndExpand, HorizontalOptions = LayoutOptions.EndAndExpand, //TextColor = (Color)App.Current.Resources["BtnBkgColor"], FontAttributes = FontAttributes.Bold }); //////TODO show what these nutrient values are as percentages of the DRI //colTitle.Children.Add(new Label() //{ // Text = "DRI %", // HorizontalOptions = LayoutOptions.End, // TextColor = (Color)App.Current.Resources["BtnBkgColor"], // FontAttributes = FontAttributes.Bold //}); //add to table nutTable.Add(new ViewCell() { View = colTitle }); ////////////////// //add each nutrient into table foreach (var item in foodItem.nutrients) { //create a new stack to put in table var layout = new StackLayout() { Orientation = StackOrientation.Horizontal }; //stack contains nutrient name layout.Children.Add(new Label() { Text = item.DisplayName, HorizontalOptions = LayoutOptions.StartAndExpand, WidthRequest = 150, //Style = App.Current.Resources["LabelStyle"] as Style }); //stack contains nutrient quantity layout.Children.Add(new Label() { Text = Convert.ToString(Math.Round(item.quantity, 4)), HorizontalOptions = LayoutOptions.EndAndExpand, //Style = App.Current.Resources["LabelStyle"] as Style }); ///////////TODO add DRI %'s //layout.Children.Add(new Label() //{ // Text = Convert.ToString(Math.Round(item.quantity, 4)), // HorizontalOptions = LayoutOptions.End, // Style = App.Current.Resources["LabelStyle"] as Style //}); //add nutrient to xaml table nutTable.Add(new ViewCell() { View = layout }); } } }
public int Mm(float mm) { return(UnitConverter.ConvertUnitsToPixels(this.Dpi, mm, Unit.Mm)); }
public ValidationResult Validate() { var val = new ValidationResult(); //var magic = 0; //example #13 p175 #region creating model var model = new Model(); var l = UnitConverter.In2M(40); var w = UnitConverter.In2M(10); var h = UnitConverter.In2M(5); var t = UnitConverter.In2M(0.25); var e = UnitConverter.Ksi2Pas(10000); //10'000 ksi var no = 0.3; var n = 9; var xSpan = l / (n - 1); var nodes = new Node[n][]; for (var i = 0; i < n; i++) { var x = i * xSpan; nodes[i] = new Node[7]; nodes[i][0] = new Node(x, 0, 0); nodes[i][1] = new Node(x, w / 2, 0); nodes[i][2] = new Node(x, w, 0); nodes[i][3] = new Node(x, w / 2, h / 2); nodes[i][4] = new Node(x, 0, h); nodes[i][5] = new Node(x, w / 2, h); nodes[i][6] = new Node(x, w, h); model.Nodes.AddRange(nodes[i]); } var pairs = new int[6][]; pairs[0] = new int[] { 0, 1 }; pairs[1] = new int[] { 1, 2 }; pairs[2] = new int[] { 1, 3 }; pairs[3] = new int[] { 3, 5 }; pairs[4] = new int[] { 4, 5 }; pairs[5] = new int[] { 5, 6 }; var mat = new Materials.UniformIsotropicMaterial(e, no); var sec = new Sections.UniformParametric2DSection(t); for (var i = 0; i < n - 1; i++) { for (int j = 0; j < 6; j++) { var n11 = nodes[i][pairs[j][0]]; var n12 = nodes[i][pairs[j][1]]; var n21 = nodes[i + 1][pairs[j][0]]; var n22 = nodes[i + 1][pairs[j][1]]; { var elm1 = new TriangleElement() { Material = mat, Section = sec }; elm1.Nodes[0] = n11; elm1.Nodes[1] = n12; elm1.Nodes[2] = n21; model.Elements.Add(elm1); var elm2 = new TriangleElement() { Material = mat, Section = sec }; elm2.Nodes[0] = n21; elm2.Nodes[1] = n22; elm2.Nodes[2] = n12; model.Elements.Add(elm2); } } } //loading nodes.Last()[0].Loads.Add(new NodalLoad(new Force(0, UnitConverter.Kip2N(1.6), 0, 0, 0, 0))); nodes.Last()[6].Loads.Add(new NodalLoad(new Force(0, -UnitConverter.Kip2N(1.6), 0, 0, 0, 0))); nodes[0].ToList().ForEach(i => i.Constraints = Constraints.Fixed); #endregion model.Trace.Listeners.Add(new BriefFiniteElementNet.Common.ConsoleTraceListener()); new ModelWarningChecker().CheckModel(model); //ModelVisualizerControl.VisualizeInNewWindow(model); model.Solve(); var A = nodes.Last()[2]; var B = nodes.Last()[4]; var C = nodes.First()[1]; var D = nodes.First()[0]; var E = nodes.Last()[6]; /* * for (int i = 0; i < nodes.Last().Length; i++) * { * nodes.Last()[i].Label = i.ToString(); * } */ /**/ A.Label = "A"; B.Label = "B"; C.Label = "C"; D.Label = "D"; E.Label = "E"; /**/ val.Title = "I Beam torsion with triangle element"; var da = 1 / 0.0254 * A.GetNodalDisplacement().Displacements; // [inch] var db = 1 / 0.0254 * B.GetNodalDisplacement().Displacements; // [inch] var sap2000Da = new Vector(-0.014921, 0.085471, 0.146070); //tbl 7.14 var sap2000Db = new Vector(-0.014834, -0.085475, -0.144533); //tbl 7.14 var abaqusDa = new Vector(-15.4207E-03, 88.2587E-03, 150.910E-03); //node 9 var abaqusDb = new Vector(-15.3246E-03, -88.2629E-03, -148.940E-03); //node 5 Console.WriteLine("Err at A against abaqus (displacement): {0:0.00}%", GetError(da, abaqusDa)); Console.WriteLine("Err at B against abaqus (displacement): {0:0.00}%", GetError(db, abaqusDb)); { var e81 = model.Elements[85] as TriangleElement; var stress = e81.GetLocalInternalStress(LoadCase.DefaultLoadCase, 1 / 6.0, 1 / 6.0, 0); } for (int i = 0; i < model.Elements.Count; i++) { model.Elements[i].Label = i.ToString(); } throw new NotImplementedException(); }
public int Meter(float m) { return(UnitConverter.ConvertUnitsToPixels(this.Dpi, m, Unit.M)); }
public void ConvertByName_QuantityCaseInsensitive() { Assert.Equal(0, UnitConverter.ConvertByName(0, "length", "Meter", "Centimeter")); }
public int Pica(float pica) { return(UnitConverter.ConvertUnitsToPixels(this.Dpi, pica, Unit.Pica)); }
public void ConvertByName_UnitTypeCaseInsensitive() { Assert.Equal(0, UnitConverter.ConvertByName(0, "Length", "meter", "Centimeter")); }
public int Twip(float twip) { return(UnitConverter.ConvertUnitsToPixels(this.Dpi, twip, Unit.Twip)); }
public void ConvertByName_ThrowsUnitNotFoundExceptionOnUnknownQuantity(double inputValue, string quantityTypeName, string fromUnit, string toUnit) { Assert.Throws <UnitNotFoundException>(() => UnitConverter.ConvertByName(inputValue, quantityTypeName, fromUnit, toUnit)); }
private void UserControl_Loaded(object sender, RoutedEventArgs e) { if (_loaded) return; _conv = new UnitConverter(); _conv.FillTreeview(TreeSource); _currentheader = ""; _loaded = true; }
public void ConvertByAbbreviation_ConvertsTheValueToGivenUnit(double expectedValue, double inputValue, string quantityTypeName, string fromUnit, string toUnit) { Assert.Equal(expectedValue, UnitConverter.ConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit)); }
//function processing the meash public void TriangulateTopoMesh(Autodesk.Revit.DB.Mesh vMesh) { //setup utility class LuxExporter.UnitConverter Converter = new UnitConverter(); // set pointer Data.NumberOfVerticesinFace = 3; //export all triangles for (int i = 0; i < vMesh.NumTriangles; i++) { //increase face counter iNumberOfFaces++; //create a triangle MeshTriangle objTriangular = vMesh.get_Triangle(i); //calculate normal of triangle LuxExporter.NormalOfTriangle NormalofT = new NormalOfTriangle(); XYZ NormalAtPoint = NormalofT.calcNormal(objTriangular.get_Vertex(0), objTriangular.get_Vertex(1), objTriangular.get_Vertex(2)); for (int iPointsCounter = 0; iPointsCounter < 3; iPointsCounter++) { XYZ point = objTriangular.get_Vertex(iPointsCounter); //convert to meter point = Converter.ConvertPointCoordToMeter(point); //add to ply class Data.AddVertice(point, NormalAtPoint); } } }
public void ConvertByAbbreviation_ThrowsUnitNotFoundExceptionOnUnknownFromOrToUnitAbbreviation(double inputValue, string quantityTypeName, string fromUnit, string toUnit) { Assert.Throws <UnitNotFoundException>(() => UnitConverter.ConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit)); }
private void ExportActiveViewParameterized(long iOutputResolution, long lResampleRatio, string ExportType, string sOutputDir,string sOutputFileName, Boolean bClipToGraphicsExtent) { IActiveView docActiveView = m_hookHelper.ActiveView; IExport docExport; long iPrevOutputImageQuality; IOutputRasterSettings docOutputRasterSettings; IEnvelope PixelBoundsEnv; tagRECT exportRECT; tagRECT DisplayBounds; IDisplayTransformation docDisplayTransformation; IPageLayout docPageLayout; IEnvelope docMapExtEnv; long hdc; long tmpDC; long iScreenResolution; bool bReenable = false; IEnvelope docGraphicsExtentEnv; IUnitConverter pUnitConvertor; if (GetFontSmoothing()) { bReenable = true; DisableFontSmoothing(); if (GetFontSmoothing()) { return; } } if (ExportType == "PDF") { docExport = new ExportPDFClass(); } else if (ExportType == "EPS") { docExport = new ExportPSClass(); } else if (ExportType == "AI") { docExport = new ExportAIClass(); } else if (ExportType == "BMP") { docExport = new ExportBMPClass(); } else if (ExportType == "TIFF") { docExport = new ExportTIFFClass(); } else if (ExportType == "SVG") { docExport = new ExportSVGClass(); } else if (ExportType == "PNG") { docExport = new ExportPNGClass(); } else if (ExportType == "GIF") { docExport = new ExportGIFClass(); } else if (ExportType == "EMF") { docExport = new ExportEMFClass(); } else if (ExportType == "JPEG") { docExport = new ExportJPEGClass(); } else { MessageBox.Show("��֧�ֵ��������� " + ExportType + ", Ĭ�ϵ���ΪEMF��ʽ������"); ExportType = "EMF"; docExport = new ExportEMFClass(); } docOutputRasterSettings = docActiveView.ScreenDisplay.DisplayTransformation as IOutputRasterSettings; iPrevOutputImageQuality = docOutputRasterSettings.ResampleRatio; if (docExport is IExportImage) { SetOutputQuality(docActiveView, 1); } else { SetOutputQuality(docActiveView, lResampleRatio); } docExport.ExportFileName = sOutputFileName + "." + docExport.Filter.Split('.')[1].Split('|')[0].Split(')')[0]; tmpDC = GetDC(0); iScreenResolution = GetDeviceCaps((int)tmpDC, 88); //88 is the win32 const for Logical pixels/inch in X) ReleaseDC(0, (int)tmpDC); frmSetResolution mSetResolution = new frmSetResolution(iOutputResolution); mSetResolution.ShowDialog(); iOutputResolution = mSetResolution.m_Resolution ; docExport.Resolution = iOutputResolution; if (docActiveView is IPageLayout) { DisplayBounds = docActiveView.ExportFrame; docGraphicsExtentEnv = GetGraphicsExtent(docActiveView); } else { docDisplayTransformation = docActiveView.ScreenDisplay.DisplayTransformation; DisplayBounds = docDisplayTransformation.get_DeviceFrame(); } PixelBoundsEnv = new Envelope() as IEnvelope; if (bClipToGraphicsExtent && (docActiveView is IPageLayout)) { docGraphicsExtentEnv = GetGraphicsExtent(docActiveView); docPageLayout = docActiveView as PageLayout; pUnitConvertor = new UnitConverter(); PixelBoundsEnv.XMin = 0; PixelBoundsEnv.YMin = 0; PixelBoundsEnv.XMax = pUnitConvertor.ConvertUnits(docGraphicsExtentEnv.XMax, docPageLayout.Page.Units, esriUnits.esriInches) * docExport.Resolution - pUnitConvertor.ConvertUnits(docGraphicsExtentEnv.XMin, docPageLayout.Page.Units, esriUnits.esriInches) * docExport.Resolution; PixelBoundsEnv.YMax = pUnitConvertor.ConvertUnits(docGraphicsExtentEnv.YMax, docPageLayout.Page.Units, esriUnits.esriInches) * docExport.Resolution - pUnitConvertor.ConvertUnits(docGraphicsExtentEnv.YMin, docPageLayout.Page.Units, esriUnits.esriInches) * docExport.Resolution; exportRECT.bottom = (int)(PixelBoundsEnv.YMax) + 1; exportRECT.left = (int)(PixelBoundsEnv.XMin); exportRECT.top = (int)(PixelBoundsEnv.YMin); exportRECT.right = (int)(PixelBoundsEnv.XMax) + 1; docMapExtEnv = docGraphicsExtentEnv; } else { double tempratio = iOutputResolution / iScreenResolution; double tempbottom = DisplayBounds.bottom * tempratio; double tempright = DisplayBounds.right * tempratio; exportRECT.bottom = (int)Math.Truncate(tempbottom); exportRECT.left = 0; exportRECT.top = 0; exportRECT.right = (int)Math.Truncate(tempright); PixelBoundsEnv.PutCoords(exportRECT.left, exportRECT.top, exportRECT.right, exportRECT.bottom); docMapExtEnv = null; } docExport.PixelBounds = PixelBoundsEnv; try { hdc = docExport.StartExporting(); docActiveView.Output((int)hdc, (int)docExport.Resolution, ref exportRECT, docMapExtEnv, null); docExport.FinishExporting(); docExport.Cleanup(); MessageBox.Show("�ɹ����� " + sOutputDir + sOutputFileName + "." + docExport.Filter.Split('.')[1].Split('|')[0].Split(')')[0] + ".", "�����ͼͼƬ", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch { MessageBox.Show("�����ͼͼƬ�����г������⣡", "�����ͼͼƬ", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } finally { SetOutputQuality(docActiveView, iPrevOutputImageQuality); if (bReenable) { EnableFontSmoothing(); bReenable = false; if (!GetFontSmoothing()) { MessageBox.Show("Unable to reenable Font Smoothing", "Font Smoothing error"); } } docMapExtEnv = null; PixelBoundsEnv = null; } }
/// <summary> /// A method for retrieving the contents from provided address. /// Throws an exception if provided address is not found within current VirtualMemory instance. /// </summary> /// <param name="decimalAddress">The address (decimal) to read from memory</param> /// <exception cref="IndexOutOfRangeException">If invalid address</exception> /// <returns>string representation of contents in current VirtualMemory in Binary.</returns> public string GetContentsInBin(int decimalAddress) { return(UnitConverter.HexToBinary(GetContentsInHex(decimalAddress))); }