double.ToString()

Here are the examples of the csharp api double.ToString() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1411 Examples 7

19 View Source File : HotKeyControl.cs
License : MIT License
Project Creator : 3RD-Dimension

private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (!machine.Connected)
                return;     

            string currentHotPressed = HotKeys.KeyProcess(sender, e); // Get Keycode
            if (currentHotPressed == null) return; // If currentHotPressed is null, Return (to avoid continuing with  blank)

            if (currentHotPressed == "Left" || currentHotPressed == "Right" || currentHotPressed == "Up" || currentHotPressed == "Down")
            {
                viewport.IsPanEnabled = false;
                viewport.IsRotationEnabled = false;
                viewport.IsMoveEnabled = false;
            }

            if (machine.Mode == Machine.OperatingMode.Manual)
            {
                if (machine.BufferState > 0 || machine.Status != "Idle")
                    return;

                string direction = null;

                if (currentHotPressed == HotKeys.hotkeyCode["JogXPos"])
                    direction = "X";
                else if (currentHotPressed == HotKeys.hotkeyCode["JogXNeg"])
                    direction = "X-";
                else if (currentHotPressed == HotKeys.hotkeyCode["JogYPos"])
                    direction = "Y";
                else if (currentHotPressed == HotKeys.hotkeyCode["JogYNeg"])
                    direction = "Y-";
                else if (currentHotPressed == HotKeys.hotkeyCode["JogZPos"])
                    direction = "Z";
                else if (currentHotPressed == HotKeys.hotkeyCode["JogZNeg"])
                    direction = "Z-";
                else if (currentHotPressed == HotKeys.hotkeyCode["RTOrigin"]) // Return to Origin ie back to all axis Zero position
                    ButtonManualReturnToZero.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                else if (currentHotPressed == HotKeys.hotkeyCode["FSStop"]) // Jog Cancel
                    machine.JogCancel();

                if (direction != null)
                {
                    manualJogSendCommand(direction);
                }
            }

            viewport.IsPanEnabled = true;
            viewport.IsRotationEnabled = true;
            viewport.IsMoveEnabled = true;

            // Emergency Reset
            if (machine.Connected && currentHotPressed == HotKeys.hotkeyCode["EmgStop"])
                machine.SoftReset();
            // Cycle Start - Only allowed if Connected, and not currently sending a file
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["CycleStart"])
                ButtonFileStart.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
            // Reload File (Re-Do)
            else if (machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["ReDoReload"]) // Only if not currently sending
                ReloadCurrentFile();
            else if (machine.Mode == Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["FSStop"]) // Put machine on Hold if sending a file
                ButtonFilePause.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
            // Spindle and Flood  (firmware takes care if it will enable or disable so just need to know if it is connected to controller to turn on Manually.           
            else if (machine.Connected && currentHotPressed == HotKeys.hotkeyCode["SpindleOnOff"]) // Spindle Toggle
                SpindleControl();
            else if (machine.Connected && currentHotPressed == HotKeys.hotkeyCode["CoolantOnOff"]) // Coolant Toggle
                FloodControl();
            else if (machine.Connected && currentHotPressed == HotKeys.hotkeyCode["MistOnOff"]) // Mist Toggle
                MistControl();

            // Need to save back to Settings otherwise will not register unless it is focused, maybe try Focus() first....
            
            // JOG RATE AXIS X
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["JRateIncX"])
            {
                double currentJogRate = Convert.ToDouble(TextBoxJogFeedX.Text);
                double newJogRate = currentJogRate + Properties.Settings.Default.JogFeedXIncDec;
                TextBoxJogFeedX.Text = newJogRate.ToString();
                Properties.Settings.Default.JogFeedX = newJogRate;
            }           
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["JRateDecX"])
            {
                double currentJogRate = Convert.ToDouble(TextBoxJogFeedX.Text);
                double newJogRate = currentJogRate - Properties.Settings.Default.JogFeedXIncDec;
                if (newJogRate < Properties.Settings.Default.JogFeedXIncDec)
                    newJogRate = Properties.Settings.Default.JogFeedXIncDec;
                TextBoxJogFeedX.Text = newJogRate.ToString();
                Properties.Settings.Default.JogFeedX = newJogRate;
            }
            // JOG RATE AXIS Y
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["JRateIncY"])
            {
                double currentJogRate = Convert.ToDouble(TextBoxJogFeedY.Text);
                double newJogRate = currentJogRate + Properties.Settings.Default.JogFeedYIncDec;
                TextBoxJogFeedY.Text = newJogRate.ToString();
                Properties.Settings.Default.JogFeedY = newJogRate;
            }
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["JRateDecY"])
            {
                double currentJogRate = Convert.ToDouble(TextBoxJogFeedY.Text);
                double newJogRate = currentJogRate - Properties.Settings.Default.JogFeedYIncDec;
                if (newJogRate < Properties.Settings.Default.JogFeedYIncDec)
                    newJogRate = Properties.Settings.Default.JogFeedYIncDec;
                TextBoxJogFeedY.Text = newJogRate.ToString();
                Properties.Settings.Default.JogFeedY = newJogRate;
            }
            // JOG RATE AXIS Z
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["JRateIncZ"])
            {
                double currentJogRate = Convert.ToDouble(TextBoxJogFeedZ.Text);
                double newJogRate = currentJogRate + Properties.Settings.Default.JogFeedZIncDec;
                TextBoxJogFeedZ.Text = newJogRate.ToString();
                Properties.Settings.Default.JogFeedZ = newJogRate;
            }
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["JRateDecZ"])
            {
                double currentJogRate = Convert.ToDouble(TextBoxJogFeedZ.Text);
                double newJogRate = currentJogRate - Properties.Settings.Default.JogFeedZIncDec;
                if (newJogRate < Properties.Settings.Default.JogFeedZIncDec)
                    newJogRate = Properties.Settings.Default.JogFeedZIncDec;
                TextBoxJogFeedZ.Text = newJogRate.ToString();
                Properties.Settings.Default.JogFeedZ = newJogRate;
            }

            // JOG DISTANCE X
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["JDistIncX"])
            {
                double currentJogDist = Convert.ToDouble(TextBoxJogDistanceX.Text);
                double newJogDist = currentJogDist + Properties.Settings.Default.JogDistXIncDec;
                TextBoxJogDistanceX.Text = newJogDist.ToString();
                Properties.Settings.Default.JogDistanceX = newJogDist;
            }
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["JDistDecX"])
            {
                double currentJogDist = Convert.ToDouble(TextBoxJogDistanceX.Text);
                double newJogDist = currentJogDist - Properties.Settings.Default.JogDistXIncDec;
                if (newJogDist < Properties.Settings.Default.JogDistXIncDec)  
                    newJogDist = Properties.Settings.Default.JogDistXIncDec;
                TextBoxJogDistanceX.Text = newJogDist.ToString();
                Properties.Settings.Default.JogDistanceX = newJogDist;
            }

            // JOG DISTANCE Y
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["JDistIncY"])
            {
                double currentJogDist = Convert.ToDouble(TextBoxJogDistanceY.Text);
                double newJogDist = currentJogDist + Properties.Settings.Default.JogDistYIncDec;
                TextBoxJogDistanceY.Text = newJogDist.ToString();
                Properties.Settings.Default.JogDistanceY = newJogDist;
            }
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["JDistDecY"])
            {
                double currentJogDist = Convert.ToDouble(TextBoxJogDistanceY.Text);
                double newJogDist = currentJogDist - Properties.Settings.Default.JogDistYIncDec;
                if (newJogDist < Properties.Settings.Default.JogDistYIncDec)
                    newJogDist = Properties.Settings.Default.JogDistYIncDec;
                TextBoxJogDistanceY.Text = newJogDist.ToString();
                Properties.Settings.Default.JogDistanceY = newJogDist;
            }

            // JOG DISTANCE Z
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["JDistIncZ"])
            {
                double currentJogDist = Convert.ToDouble(TextBoxJogDistanceZ.Text);
                double newJogDist = currentJogDist + Properties.Settings.Default.JogDistZIncDec;
                TextBoxJogDistanceZ.Text = newJogDist.ToString();
                Properties.Settings.Default.JogDistanceZ = newJogDist;
            }
            else if (machine.Connected && machine.Mode != Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["JDistDecZ"])
            {
                double currentJogDist = Convert.ToDouble(TextBoxJogDistanceZ.Text);
                double newJogDist = currentJogDist - Properties.Settings.Default.JogDistZIncDec;
                if (newJogDist < Properties.Settings.Default.JogDistZIncDec)
                    newJogDist = Properties.Settings.Default.JogDistZIncDec;
                TextBoxJogDistanceZ.Text = newJogDist.ToString();
                Properties.Settings.Default.JogDistanceZ = newJogDist;
            }
            
            // Feed Rate
            // FeedRateIncrement & SpindleIncrement False = 1% Inc and Dec, True = 10% Inc and Dec
            else if (machine.Mode == Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["FRateInc"]) // Feed Rate Incease
            {
                if (Properties.Settings.Default.FeedRateIncrement == true) // 10% Increase
                {
                    Feed10Inc.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                }
                else if (Properties.Settings.Default.FeedRateIncrement == false) // 1% Increase
                {
                    Feed1Inc.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                }
            }
            else if (machine.Mode == Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["FRateDec"]) // Feed Rate Incease
            {               
                if (Properties.Settings.Default.FeedRateIncrement == true) // 10% Decrease
                {
                    Feed10Dec.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                }
                else if (Properties.Settings.Default.FeedRateIncrement == false) // 1% Decrease
                {
                    Feed1Dec.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                }
            }
            // Spindle Increase and Decrease
            else if (machine.Mode == Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["SpindleInc"]) // Spindle Incease
            {
                if (Properties.Settings.Default.FeedRateIncrement == true) // 10% Increase
                {
                    Spindle10Inc.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                }
                else if (Properties.Settings.Default.FeedRateIncrement == false) // 1% Increase
                {
                    Spindle1Inc.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                }
            }
            else if (machine.Mode == Machine.OperatingMode.SendFile && currentHotPressed == HotKeys.hotkeyCode["SprindleDec"]) // Spindle Incease
            {
                if (Properties.Settings.Default.FeedRateIncrement == true) // 10% Decrease
                {
                    Spindle10Dec.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                }
                else if (Properties.Settings.Default.FeedRateIncrement == false) // 1% Decrease
                {
                    Spindle1Dec.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                }
            }
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : 3RD-Dimension

private void ButtonSaveViewport_Click(object sender, RoutedEventArgs e)
		{
			List<double> coords = new List<double>();

			coords.AddRange(new Vector3(viewport.Camera.Position).Array);
			coords.AddRange(new Vector3(viewport.Camera.LookDirection).Array);

			Properties.Settings.Default.ViewPortPos = string.Join(";", coords.Select(d => d.ToString()));
		}

19 View Source File : JsonData.cs
License : MIT License
Project Creator : 404Lcc

public override string ToString ()
        {
            switch (type) {
            case JsonType.Array:
                return "JsonData array";

            case JsonType.Boolean:
                return inst_boolean.ToString ();

            case JsonType.Double:
                return inst_double.ToString ();

            case JsonType.Int:
                return inst_int.ToString ();

            case JsonType.Long:
                return inst_long.ToString ();

            case JsonType.Object:
                return "JsonData object";

            case JsonType.String:
                return inst_string;
            }

            return "Uninitialized JsonData";
        }

19 View Source File : PointCloudToMeshComponentFull.cs
License : GNU Lesser General Public License v3.0
Project Creator : 9and3

protected override void SolveInstance(IGH_DataAccess DA) {

            int Downsample = 5000;
            int NormalsNeighbours = 100;
            bool debug = false;

            int maximumDeptOfReconstructionSurfaceTree = 8;
            int targetWidthOfTheFinestLevelOctree = 0;
            double ratioBetweenReconCubeAndBBCubeStd = 1.1;
            bool ReconstructorUsingLinearInterpolation = false;

            DA.GetData(1, ref Downsample);
            DA.GetData(2, ref NormalsNeighbours);
            DA.GetData(3, ref debug);
            DA.GetData(4, ref maximumDeptOfReconstructionSurfaceTree);
            DA.GetData(5, ref targetWidthOfTheFinestLevelOctree);
            DA.GetData(6, ref ratioBetweenReconCubeAndBBCubeStd);
            DA.GetData(7, ref ReconstructorUsingLinearInterpolation);

            //Guid to PointCloud
            //PointCloud c = new PointCloud();
            PointCloudGH c = new PointCloudGH();

            string debugInfo = debug ? "1" : "0";
            

            if (DA.GetData(0, ref c)) {
                if (!c.IsValid) return;
                if (c.Value.Count==0) return;
                Downsample = Math.Min(Downsample, c.Value.Count);

               // var watch = System.Diagnostics.Stopwatch.StartNew();
                // the code that you want to measure comes here

                /////////////////////////////////////////////////////////////////
                //Get Directory
                /////////////////////////////////////////////////////////////////
                string replacedemblyLocation = System.Reflection.replacedembly.GetExecutingreplacedembly().Location;
                string replacedemblyPath = System.IO.Path.GetDirectoryName(replacedemblyLocation);


                /////////////////////////////////////////////////////////////////
                //write PointCloud to PLY
                /////////////////////////////////////////////////////////////////
                PlyReaderWriter.PlyWriter.SavePLY(c.Value, replacedemblyPath + @"\in.ply");
                //Rhino.RhinoApp.WriteLine("PointCloudToMesh. Saved Input: " + replacedemblyPath + @"\in.ply");
                //watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());

                /////////////////////////////////////////////////////////////////
                //Ply to Mesh to Obj
                /////////////////////////////////////////////////////////////////
                //watch = System.Diagnostics.Stopwatch.StartNew();
                //tring argument = replacedemblyPath + "TestVisualizer.exe " + "-1 " + "100";//--asci 
                string argument = " "+Downsample.ToString()+ " " + NormalsNeighbours.ToString() + " " + debugInfo + " " + maximumDeptOfReconstructionSurfaceTree.ToString() + " " + targetWidthOfTheFinestLevelOctree.ToString() + " " + ratioBetweenReconCubeAndBBCubeStd.ToString() + " " + Convert.ToInt32(ReconstructorUsingLinearInterpolation).ToString();
                //--asci 
                                                                                                                  // Rhino.RhinoApp.WriteLine("PointCloudToMesh. Arguments: " + argument );



                // Rhino.RhinoApp.WriteLine("PointCloudToMesh. Directory: " + replacedemblyPath + @"\TestVisualizer.exe");

                if (debug) {
                    var proc = new System.Diagnostics.Process {
                        StartInfo = new System.Diagnostics.ProcessStartInfo {
                            FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
                            Arguments = argument,
                            //UseShellExecute = false,
                            //RedirectStandardOutput = true,
                            CreateNoWindow = false,
                            // WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                            WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
                        }
                    };

                    proc.Start();
                 
                    proc.WaitForExit();
                } else {
                    var proc = new System.Diagnostics.Process {
                        StartInfo = new System.Diagnostics.ProcessStartInfo {
                            FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
                            Arguments = argument,
                            //UseShellExecute = false,
                            //RedirectStandardOutput = true,
                            CreateNoWindow = true,
                             WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                            WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
                        }
                    };
                    proc.Start();
                    proc.WaitForExit();
                }

               // watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());

                /////////////////////////////////////////////////////////////////
                //Read Obj
                /////////////////////////////////////////////////////////////////
                ///

                //Outputs
               // watch = System.Diagnostics.Stopwatch.StartNew();

                // Initialize
                var obj = new ObjParser.Obj();

                // Read Wavefront OBJ file
                //obj.LoadObj(@"C:\libs\windows\out.obj");
            

                //PlyReaderWriter.PlyLoader plyLoader = new PlyReaderWriter.PlyLoader();
                //Mesh mesh3D = plyLoader.load(replacedemblyPath + @"\out.ply")[0];


                //Rhino.RhinoApp.WriteLine(replacedemblyPath + @"\windows\out.obj");
                obj.LoadObj(replacedemblyPath + @"\out.obj");

                Mesh mesh3D = new Mesh();
                foreach (ObjParser.Types.Vertex v in obj.VertexList) {
                    mesh3D.Vertices.Add(new Point3d(v.X, v.Y, v.Z));
                    mesh3D.VertexColors.Add(System.Drawing.Color.FromArgb((int)(v.r * 255), (int)(v.g * 255), (int)(v.b * 255)  ));
                }
 
                int num = checked(mesh3D.Vertices.Count - 1);

                foreach (ObjParser.Types.Face f in obj.FaceList) {

                    string[] lineData = f.ToString().Split(' ');
                    string[] v0 = lineData[1].Split('/');
                    string[] v1 = lineData[2].Split('/');
                    string[] v2 = lineData[3].Split('/');

                    MeshFace mf3D = new MeshFace(Convert.ToInt32(v0[0]) - 1, Convert.ToInt32(v1[0]) - 1, Convert.ToInt32(v2[0]) - 1);
                    if (mf3D.IsValid())
                        if (!(mf3D.A > num || mf3D.B > num || mf3D.C > num || mf3D.D > num))
                            mesh3D.Faces.AddFace(mf3D);


                }








                DA.SetData(0, mesh3D);

                /////////////////////////////////////////////////////////////////
                //Output Iso Values
                /////////////////////////////////////////////////////////////////
                string[] lines = System.IO.File.ReadAllLines(replacedemblyPath + @"\out.txt");
                double[] iso = new double[lines.Length];
                for (int i = 0; i < lines.Length; i++) { 
                    iso[i] = Convert.ToDouble(lines[i]);
                }
                //watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds/1000.0).ToString());

                DA.SetDataList(1, iso);

            }


        }

19 View Source File : Field.cs
License : MIT License
Project Creator : a1xd

public void SetToTyping()
        {
            if (State != FieldState.Typing)
            {
                Box.BackColor = Color.White;
                Box.ForeColor = Color.Black;

                PreviousState = State;
                State = FieldState.Typing;
            }

            Box.Text = Data.ToString();
        }

19 View Source File : AttackServer.cs
License : Apache License 2.0
Project Creator : AantCoder

public void Finish()
        {
            Loger.Log($"Server AttackServer {Attacker.Public.Login} -> {Host.Public.Login} Finish StartTime sec = " 
                + (StartTime == DateTime.MinValue ? "-" : (DateTime.UtcNow - StartTime).TotalSeconds.ToString())
                + (VictoryAttacker == null ? "" : VictoryAttacker.Value ? " VictoryAttacker" : " VictoryHost")
                + (TestMode ? " TestMode" : "")
                + (TerribleFatalError ? " TerribleFatalError" : ""));
            Attacker.AttackData = null;
            Host.AttackData = null;
        }

19 View Source File : OVRGradleGeneration.cs
License : MIT License
Project Creator : absurd-joy

public void OnPostprocessBuild(BuildReport report)
	{
#if UNITY_ANDROID
		if(autoIncrementVersion)
		{
			if((report.summary.options & BuildOptions.Development) == 0)
			{
				PlayerSettings.Android.bundleVersionCode++;
				UnityEngine.Debug.Log("Incrementing version code to " + PlayerSettings.Android.bundleVersionCode);
			}
		}

		bool isExporting = true;
		foreach (var step in report.steps)
		{
			if (step.name.Contains("Compile scripts")
				|| step.name.Contains("Building scenes")
				|| step.name.Contains("Writing replacedet files")
				|| step.name.Contains("Preparing APK resources")
				|| step.name.Contains("Creating Android manifest")
				|| step.name.Contains("Processing plugins")
				|| step.name.Contains("Exporting project")
				|| step.name.Contains("Building Gradle project"))
			{
				OVRPlugin.SendEvent("build_step_" + step.name.ToLower().Replace(' ', '_'),
					step.duration.TotalSeconds.ToString(), "ovrbuild");
#if BUILDSESSION
				UnityEngine.Debug.LogFormat("build_step_" + step.name.ToLower().Replace(' ', '_') + ": {0}", step.duration.TotalSeconds.ToString());
#endif
				if(step.name.Contains("Building Gradle project"))
				{
					isExporting = false;
				}
			}
		}
		OVRPlugin.AddCustomMetadata("build_step_count", report.steps.Length.ToString());
		if (report.summary.outputPath.Contains("apk")) // Exclude Gradle Project Output
		{
			var fileInfo = new System.IO.FileInfo(report.summary.outputPath);
			OVRPlugin.AddCustomMetadata("build_output_size", fileInfo.Length.ToString());
		}
#endif
		if (!report.summary.outputPath.Contains("OVRGradleTempExport"))
		{
			OVRPlugin.SendEvent("build_complete", (System.DateTime.Now - buildStartTime).TotalSeconds.ToString(), "ovrbuild");
#if BUILDSESSION
			UnityEngine.Debug.LogFormat("build_complete: {0}", (System.DateTime.Now - buildStartTime).TotalSeconds.ToString());
#endif
		}

#if UNITY_ANDROID
		if (!isExporting)
		{
			// Get the hosts path to Android SDK
			if (adbTool == null)
			{
				adbTool = new OVRADBTool(OVRConfig.Instance.GetAndroidSDKPath(false));
			}

			if (adbTool.isReady)
			{
				// Check to see if there are any ADB devices connected before continuing.
				List<string> devices = adbTool.GetDevices();
				if(devices.Count == 0)
				{
					return;
				}

				// Clear current logs on device
				Process adbClearProcess;
				adbClearProcess = adbTool.RunCommandAsync(new string[] { "logcat --clear" }, null);

				// Add a timeout if we cannot get a response from adb logcat --clear in time.
				Stopwatch timeout = new Stopwatch();
				timeout.Start();
				while (!adbClearProcess.WaitForExit(100))
				{
					if (timeout.ElapsedMilliseconds > 2000)
					{
						adbClearProcess.Kill();
						return;
					}
				}

				// Check if existing ADB process is still running, kill if needed
				if (adbProcess != null && !adbProcess.HasExited)
				{
					adbProcess.Kill();
				}

				// Begin thread to time upload and install
				var thread = new Thread(delegate ()
				{
					TimeDeploy();
				});
				thread.Start();
			}
		}
#endif
	}

19 View Source File : SolarAnalysisManager.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

public static void CreateTestFaces(IList<Reference> faceSelection, IList<Reference> mreplacedSelection, double replacedysysGridSize, UIDoreplacedent uidoc, View view)
        {
            double totalUVPoints = 0;
            double totalUVPointsWith2PlusHours = 0;

            if (faceSelection == null) {
                return;
            }

            var testFaces = CreateEmptyTestFaces(faceSelection, uidoc.Doreplacedent);

            var stopwatch = new Stopwatch();
            stopwatch.Start();

            // not required when using ReferenceIntersector 
            var solids = SolidsFromReferences(mreplacedSelection, uidoc.Doreplacedent);

            // create a ReferenceIntersection
            var ids = mreplacedSelection.Select(s => s.ElementId).ToList();
            var referenceIntersector = new ReferenceIntersector(ids, FindReferenceTarget.All, view as View3D);

            Transaction t = new Transaction(uidoc.Doreplacedent);
            t.Start("testSolarVectorLines");

            ////create colour scheme
            SolarreplacedysisColourSchemes.CreatereplacedysisScheme(SolarreplacedysisColourSchemes.DefaultColours, uidoc.Doreplacedent, "Direct Sunlight Hours", true);
            var schemeId = SolarreplacedysisColourSchemes.CreatereplacedysisScheme(SolarreplacedysisColourSchemes.DefaultColours, uidoc.Doreplacedent, "Direct Sunlight Hours - No Legend", false);

            foreach (DirectSunTestFace testFace in testFaces) {
                var boundingBox = testFace.Face.GetBoundingBox();
                double boundingBoxUTotal = boundingBox.Max.U - boundingBox.Min.U;
                double boundingBoxVTotal = boundingBox.Max.V - boundingBox.Min.V;
                double gridDivisionsU = boundingBoxUTotal > 2 * replacedysysGridSize ? (boundingBoxUTotal / replacedysysGridSize) : 2;
                double gridDivisionsV = boundingBoxVTotal > 2 * replacedysysGridSize ? (boundingBoxVTotal / replacedysysGridSize) : 2;
                double gridSizeU = boundingBoxUTotal / gridDivisionsU;
                double gridSizeV = boundingBoxVTotal / gridDivisionsV;

                for (double u = boundingBox.Min.U + (gridSizeU / 2); u <= boundingBox.Max.U; u += gridSizeU) {
                    for (double v = boundingBox.Min.V + (gridSizeV / 2); v <= boundingBox.Max.V; v += gridSizeV) {
                        UV uv = new UV(u, v);

                        if (testFace.Face.IsInside(uv)) {
                            SunAndShadowSettings setting = view.SunAndShadowSettings;
                            double interval = 1;
                            switch (setting.TimeInterval)
                            {
                                case SunStudyTimeInterval.Hour:
                                    interval = 1;
                                    break;
                                case SunStudyTimeInterval.Minutes30:
                                    interval = 0.5;
                                    break;
                                case SunStudyTimeInterval.Minutes15:
                                    interval = 0.25;
                                    break;
                                case SunStudyTimeInterval.Minutes45:
                                    interval = 0.75;
                                    break;
                            }

                            var hoursOfSun = (setting.NumberOfFrames - 1) * interval;
                            //// Autodesk makes active frame starts from 1..
                            for (int activeFrame = 1; activeFrame <= setting.NumberOfFrames; activeFrame++) {
                                setting.ActiveFrame = activeFrame;
                                var start = testFace.Face.Evaluate(uv);
                                start = start.Add(testFace.Face.ComputeNormal(uv).Normalize() / 16);
                                var sunDirection = GetSunDirectionalVector(uidoc.ActiveView, GetProjectPosition(uidoc.Doreplacedent), out var _);
                                var end = start.Subtract(sunDirection.Multiply(1000));

                                //// use this only for testing.
                                //// BuildingCoder.Creator.CreateModelLine(uidoc.Doreplacedent, start, end);
                                
                                var line = Line.CreateBound(start, end);

                                // Brute Force
                                // remove if ReferenceIntersector is faster...
                                foreach (var solid in solids)
                                {
                                    try
                                    {
                                        var solidInt = solid.IntersectWithCurve(line, new SolidCurveIntersectionOptions());
                                        if (solidInt.SegmentCount > 0)
                                        {
                                            hoursOfSun = hoursOfSun - interval;
                                            break;
                                        }
                                    }
                                    catch (Exception exception)
                                    {
                                        Console.WriteLine(exception.Message);
                                    }
                                }
                            }
                            totalUVPoints++;

                            if (hoursOfSun >= 2)
                            {
                                totalUVPointsWith2PlusHours++;
                            }

                            testFace.AddValueAtPoint(uv, hoursOfSun);

                            ////dump to file
                            ////string path = @"c:\temp\UVHours.txt";
                            ////using (StreamWriter sw = File.AppendText(path))
                            ////{
                            ////    sw.WriteLine(uv.U + "," + uv.V + "," + hoursOfSun);
                            ////}
                        }
                    }
                }
            }

            var sfm = DirectSunTestFace.GetSpatialFieldManager(uidoc.Doreplacedent);
            sfm.Clear();

            foreach (var testFace in testFaces) {
                testFace.CreatereplacedysisSurface(uidoc, sfm);
            }

            view.replacedysisDisplayStyleId = schemeId;

            t.Commit();
            stopwatch.Stop();
            var percent = totalUVPointsWith2PlusHours / totalUVPoints * 100;
            var percentString = percent.ToString();
            SCaddinsApp.WindowManager.ShowMessageBox("Summary", "Time elepsed " + stopwatch.Elapsed.ToString() + @"(hh:mm:ss:uu), Percent above 2hrs: " + percentString);
        }

19 View Source File : IssuedTokenProvider.cs
License : MIT License
Project Creator : actions

public async Task<IssuedToken> GetTokenAsync(
            IssuedToken failedToken,
            CancellationToken cancellationToken)
        {
            IssuedToken currentToken = this.CurrentToken;
            VssTraceActivity traceActivity = VssTraceActivity.Current;
            Stopwatch aadAuthTokenTimer = Stopwatch.StartNew();
            try
            {
                VssHttpEventSource.Log.AuthenticationStart(traceActivity);

                if (currentToken != null)
                {
                    VssHttpEventSource.Log.IssuedTokenRetrievedFromCache(traceActivity, this, currentToken);
                    return currentToken;
                }
                else
                {
                    GetTokenOperation operation = null;
                    try
                    {
                        GetTokenOperation operationInProgress;
                        operation = CreateOperation(traceActivity, failedToken, cancellationToken, out operationInProgress);
                        if (operationInProgress == null)
                        {
                            return await operation.GetTokenAsync(traceActivity).ConfigureAwait(false);
                        }
                        else
                        {
                            return await operationInProgress.WaitForTokenAsync(traceActivity, cancellationToken).ConfigureAwait(false);
                        }
                    }
                    finally
                    {
                        lock (m_thisLock)
                        {
                            m_operations.Remove(operation);
                        }

                        operation?.Dispose();
                    }
                }
            }
            finally
            {
                VssHttpEventSource.Log.AuthenticationStop(traceActivity);

                aadAuthTokenTimer.Stop();
                TimeSpan getTokenTime = aadAuthTokenTimer.Elapsed;

                if(getTokenTime.TotalSeconds >= c_slowTokenAcquisitionTimeInSeconds)
                {
                    // It may seem strange to preplaced the string value of TotalSeconds into this method, but testing
                    // showed that ETW is persnickety when you register a method in an EventSource that doesn't
                    // use strings or integers as its parameters. It is easier to simply give the method a string
                    // than figure out to get ETW to reliably accept a double or TimeSpan.
                    VssHttpEventSource.Log.AuthorizationDelayed(getTokenTime.TotalSeconds.ToString());
                }
            }
        }

19 View Source File : Main.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence

private void DisplayBox_MouseMove(object sender, MouseEventArgs e)
        {
            pivotX = 1419 / 2;
            pivotY = 1075 / 2;
            textBox1.Text = pivotX.ToString() + ";" + pivotY.ToString() + ":" +
                DisplayBox.Width.ToString() + ";" + DisplayBox.Height.ToString();
            var result = DrawGraphics.DrawBitmap(e, this.DisplayBox, vectorPointsList, 340, 250);
            DrawGrids();
            DrawAngleAxis(result);
            DisplayBox.Refresh();
        }

19 View Source File : Program.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence

static void Main(string[] args)
        {
            bool DonotLoadGrid = true;
            var grid = new List<IList<double>>();
            if (!DonotLoadGrid)
            {
                Console.WriteLine("Loading Stream: " + DateTime.Now.ToString());
                var sr = new StreamReader(@"C:\data\table.csv");

                while (!sr.EndOfStream)
                {
                    var line = sr.ReadLine();
                    var fieldValues = line.Split(',');
                    var fields = new List<double>();
                    var rdm = new Random(100000);
                    foreach (var field in fieldValues)
                    {
                        var res = 0d;
                        var add = double.TryParse(field, out res) == true ? res : rdm.NextDouble();
                        fields.Add(add);
                    }
                    grid.Add(fields);
                }
                Console.WriteLine("Grid loaded successfully!! " + DateTime.Now.ToString());
            }
            var keepProcessing = true;
            while (keepProcessing)
            {
                Console.WriteLine(DateTime.Now.ToString());
                Console.WriteLine("Enter Expression:");
                var expression = Console.ReadLine();
                if (expression.ToLower() == "exit")
                {
                    keepProcessing = false;
                }
                else
                {
                    try
                    {
                        if(expression.Equals("zspread"))
                        {
                            var result = ConnectedInstruction.GetZSpread(grid,3,503);
                        }
                        if (expression.Substring(0, 19).ToLower().Equals("logisticregression "))
                        {
                            keepProcessing = true;
                            var paths = expression.Split(' '); 
                            #region Python
                                var script [email protected]"
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score

creditData = pd.read_csv("+paths[1][email protected]")

print(creditData.head())
print(creditData.describe())
print(creditData.corr())

features = creditData[['income', 'age', 'loan']]
target = creditData.default

feature_train, feature_test, target_train, target_test = train_test_split(features, target, test_size = 0.3)

model = LogisticRegression()
model.fit = model.fit(feature_train, target_train)
predictions = model.fit.predict(feature_test)

print(confusion_matrix(target_test, predictions))
print(accuracy_score(target_test, predictions))
";
                            var sw = new StreamWriter(@"c:\data\logistic.py");
                            sw.Write(script);
                            sw.Close();
                            #endregion
                            ProcessStartInfo start = new ProcessStartInfo();
                            Console.WriteLine("Starting Python Engine...");
                            start.FileName = @"C:\Users\rajiyer\PycharmProjects\TestPlot\venv\Scripts\python.exe";
                            start.Arguments = string.Format("{0} {1}", @"c:\data\logistic.py", args);
                            start.UseShellExecute = false;
                            start.RedirectStandardOutput = true;
                            Console.WriteLine("Starting Process..."+ DateTime.Now.ToString());
                            using (Process process = Process.Start(start))
                            {
                                using (StreamReader reader = process.StandardOutput)
                                {
                                    string result = reader.ReadToEnd();
                                    Console.Write(result);
                                }
                            }
                            Console.WriteLine("Process Succeeded..." + DateTime.Now.ToString());
                        }
                        if(expression.Substring(0,12) == "videoreplacedyse")
                        {
                            #region python
                            var python = @"
from keras.preprocessing.image import img_to_array
import imutils
import cv2
from keras.models import load_model
import numpy as np
import geocoder
#import mysql.connector as con

#mydb = con.connect(
#  host=""localhost"",
#  user=""yourusername"",
#  preplacedwd=""yourpreplacedword"",
# database=""mydatabase""
#)
#mycursor = mydb.cursor()

g = geocoder.ip('me')

# parameters for loading data and images
detection_model_path = 'C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Sentiment replacedysis\\Emotion-recognition-master\\haarcascade_files\\haarcascade_frontalface_default.xml'
emotion_model_path = 'C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Sentiment replacedysis\\Emotion-recognition-master\\models\\_mini_XCEPTION.102-0.66.hdf5'

# hyper-parameters for bounding boxes shape
# loading models
face_detection = cv2.CascadeClreplacedifier(detection_model_path)
emotion_clreplacedifier = load_model(emotion_model_path, compile = False)
EMOTIONS = [""angry"", ""disgust"", ""scared"", ""happy"", ""sad"", ""surprised"",
""neutral""]


# feelings_faces = []
# for index, emotion in enumerate(EMOTIONS):
# feelings_faces.append(cv2.imread('emojis/' + emotion + '.png', -1))

# starting video streaming
cv2.namedWindow('your_face')
camera = cv2.VideoCapture(0)
f = open(""C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Probability.txt"", ""a+"")

while True:
frame = camera.read()[1]
#reading the frame
frame = imutils.resize(frame, width = 300)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_detection.detectMultiScale(gray, scaleFactor = 1.1, minNeighbors = 5, minSize = (30, 30), flags = cv2.CASCADE_SCALE_IMAGE)


canvas = np.zeros((250, 300, 3), dtype = ""uint8"")
frameClone = frame.copy()
if len(faces) > 0:
faces = sorted(faces, reverse = True,
key = lambda x: (x[2] - x[0]) * (x[3] - x[1]))[0]
(fX, fY, fW, fH) = faces
# Extract the ROI of the face from the grayscale image, resize it to a fixed 28x28 pixels, and then prepare
# the ROI for clreplacedification via the CNN
roi = gray[fY: fY + fH, fX: fX + fW]
roi = cv2.resize(roi, (64, 64))
roi = roi.astype(""float"") / 255.0
roi = img_to_array(roi)
roi = np.expand_dims(roi, axis = 0)



preds = emotion_clreplacedifier.predict(roi)[0]
emotion_probability = np.max(preds)
label = EMOTIONS[preds.argmax()]
else: continue



for (i, (emotion, prob)) in enumerate(zip(EMOTIONS, preds)):
# construct the label text
text = ""{}: {:.2f}%"".format(emotion, prob * 100)
#sql = ""INSERT INTO predData (Metadata, Probability) VALUES (%s, %s)""
#val = (""Meta"", prob * 100)
f.write(text)
#str1 = ''.join(str(e) for e in g.latlng)
#f.write(str1)
#mycursor.execute(sql, val)
#mydb.commit()
# draw the label + probability bar on the canvas
# emoji_face = feelings_faces[np.argmax(preds)]

                
w = int(prob * 300)
cv2.rectangle(canvas, (7, (i * 35) + 5),
(w, (i * 35) + 35), (0, 0, 255), -1)
cv2.putText(canvas, text, (10, (i * 35) + 23),
cv2.FONT_HERSHEY_SIMPLEX, 0.45,
(255, 255, 255), 2)
cv2.putText(frameClone, label, (fX, fY - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)
cv2.rectangle(frameClone, (fX, fY), (fX + fW, fY + fH),
(0, 0, 255), 2)


#    for c in range(0, 3):
#        frame[200:320, 10:130, c] = emoji_face[:, :, c] * \
#        (emoji_face[:, :, 3] / 255.0) + frame[200:320,
#        10:130, c] * (1.0 - emoji_face[:, :, 3] / 255.0)


cv2.imshow('your_face', frameClone)
cv2.imshow(""Probabilities"", canvas)
if cv2.waitKey(1) & 0xFF == ord('q'):
break

camera.release()
cv2.destroyAllWindows()
";
                            var sw = new StreamWriter(@"c:\data\face.py");
                            sw.Write(python);
                            sw.Close();
                            #endregion
                            ProcessStartInfo start = new ProcessStartInfo();
                            Console.WriteLine("Starting Python Engine...");
                            start.FileName = @"C:\Users\rajiyer\PycharmProjects\TestPlot\venv\Scripts\python.exe";
                            start.Arguments = string.Format("{0} {1}", @"c:\data\face.py", args);
                            start.UseShellExecute = false;
                            start.RedirectStandardOutput = true;
                            Console.WriteLine("Starting Process..." + DateTime.Now.ToString());
                            using (Process process = Process.Start(start))
                            {
                                using (StreamReader reader = process.StandardOutput)
                                {
                                    string result = reader.ReadToEnd();
                                    Console.Write(result);
                                }
                            }
                            Console.WriteLine("Process Succeeded..." + DateTime.Now.ToString());
                        }
                        if (expression.Substring(0,12).ToLower().Equals("kaplanmeier "))
                        {
                            keepProcessing = true;
                            var columnsOfconcern = expression.Split(' ');
                            Console.WriteLine("Preparing...");
                            var observations = new List<PairedObservation>();
                            var ca = GetColumn(grid,int.Parse(columnsOfconcern[1]));
                            var cb = GetColumn(grid, int.Parse(columnsOfconcern[2]));
                            var cc = GetColumn(grid, int.Parse(columnsOfconcern[3]));
                            for(int i=0;i<ca.Count;i++)
                            {
                                observations.Add(new PairedObservation((decimal)ca[i], (decimal)cb[i], (decimal)cc[i]));
                            }
                            var kp = new KaplanMeier(observations);
                        }
                        if (expression.Equals("write"))
                        {
                            keepProcessing = true;
                            ConnectedInstruction.WritetoCsvu(grid, @"c:\data\temp.csv");
                        }
                        if (expression.Substring(0, 9) == "getvalue(")
                        {
                            keepProcessing = true;
                            Regex r = new Regex(@"\(([^()]+)\)*");
                            var res = r.Match(expression);
                            var val = res.Value.Split(',');
                            try
                            {
                                var gridVal = grid[int.Parse(val[0].Replace("(", "").Replace(")", ""))]
                                    [int.Parse(val[1].Replace("(", "").Replace(")", ""))];
                                Console.WriteLine(gridVal.ToString() + "\n");
                            }
                            catch (ArgumentOutOfRangeException)
                            {
                                Console.WriteLine("Hmmm,... apologies, can't seem to find that within range...");
                            }
                        }
                        else
                        {
                            keepProcessing = true;
                            Console.WriteLine("Process Begin:" + DateTime.Now.ToString());
                            var result = ConnectedInstruction.ParseExpressionAndRunAgainstInMemmoryModel(grid, expression);
                            Console.WriteLine("Process Ended:" + DateTime.Now.ToString());
                        }
                    }
                    catch (ArgumentOutOfRangeException)
                    {

                    }
                }
            }
        }

19 View Source File : Score.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public override string ToString() => Value.ToString();

19 View Source File : BigDecimal.cs
License : MIT License
Project Creator : AdamWhiteHat

public static BigDecimal Parse(double input)
		{
			return Parse(input.ToString());
		}

19 View Source File : BigDecimal.cs
License : MIT License
Project Creator : AdamWhiteHat

public static BigDecimal Divide(BigDecimal dividend, BigDecimal divisor)
		{
			if (divisor == BigDecimal.Zero) throw new DivideByZeroException();

			dividend.Normalize();
			divisor.Normalize();

			//	if (dividend > divisor) { return Divide_Positive(dividend, divisor); }

			if (BigDecimal.Abs(dividend) == 1)
			{
				double doubleDivisor = double.Parse(divisor.ToString());
				doubleDivisor = (1d / doubleDivisor);

				return BigDecimal.Parse(doubleDivisor.ToString());
			}

			string remString = "";
			string mantissaString = "";
			string dividendMantissaString = dividend.Mantissa.ToString();
			string divisorMantissaString = divisor.Mantissa.ToString();

			int dividendMantissaLength = dividend.DecimalPlaces;
			int divisorMantissaLength = divisor.DecimalPlaces;
			var exponentChange = dividend.Exponent - divisor.Exponent; //(dividendMantissaLength - divisorMantissaLength);

			int counter = 0;
			BigDecimal result = 0;
			BigInteger remainder = 0;
			result.Mantissa = BigInteger.DivRem(dividend.Mantissa, divisor.Mantissa, out remainder);
			while (remainder != 0 && result.SignifigantDigits < divisor.SignifigantDigits)
			{
				while (BigInteger.Abs(remainder) < BigInteger.Abs(divisor.Mantissa))
				{
					remainder *= 10;
					result.Mantissa *= 10;
					counter++;
					remString = remainder.ToString();
					mantissaString = result.Mantissa.ToString();
				}
				result.Mantissa = result.Mantissa + BigInteger.DivRem(remainder, divisor.Mantissa, out remainder);

				remString = remainder.ToString();
				mantissaString = result.Mantissa.ToString();
			}

			result.Exponent = exponentChange - counter;
			return result;
		}

19 View Source File : OrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio

public static int FetchSubjectRatingProductCount(this OrganizationServiceContext serviceContext, Guid subjectId, double? minRating, double? maxRating)
		{
			var fetchXml = XDoreplacedent.Parse(@"
				<fetch mapping=""logical"" aggregate=""true"">
					<enreplacedy name=""product"">
						<attribute name=""productid"" aggregate=""count"" alias=""count"" />
						<filter type=""and"">
							<condition attribute=""subjectid"" operator=""eq"" />
							<condition attribute=""adx_ratingaverage"" operator=""ge"" />
							<condition attribute=""adx_ratingaverage"" operator=""lt"" />
							<condition attribute=""statecode"" operator=""eq"" value=""0"" />
						</filter>
					</enreplacedy>
				</fetch>");

			var subjectIdAttribute = fetchXml.XPathSelectElement("//condition[@attribute='subjectid']");

			if (subjectIdAttribute == null)
			{
				throw new InvalidOperationException("Unable to select the subjectid filter element.");
			}

			subjectIdAttribute.SetAttributeValue("value", subjectId.ToString());

			var minRatingAttribute = fetchXml.XPathSelectElement("//condition[@attribute='adx_ratingaverage' and @operator='ge']");

			if (minRatingAttribute == null)
			{
				throw new InvalidOperationException(string.Format("Unable to select {0} element.", "adx_ratingaverage gte filter"));
			}

			if (minRating.HasValue)
			{
				minRatingAttribute.SetAttributeValue("value", minRating.ToString());
			}
			else
			{
				minRatingAttribute.Remove();
			}

			var maxRatingAttribute = fetchXml.XPathSelectElement("//condition[@attribute='adx_ratingaverage' and @operator='lt']");

			if (maxRatingAttribute == null)
			{
				throw new InvalidOperationException(string.Format("Unable to select {0} element.", "adx_ratingaverage lt"));
			}
			
			if (maxRating.HasValue)
			{
				maxRatingAttribute.SetAttributeValue("value", maxRating.ToString());
			}
			else
			{
				maxRatingAttribute.Remove();
			}

			var response = (RetrieveMultipleResponse)serviceContext.Execute(new RetrieveMultipleRequest
			{
				Query = new FetchExpression(fetchXml.ToString())
			});

			return response.EnreplacedyCollection.Enreplacedies.First().GetAttributeAliasedValue<int>("count");
		}

19 View Source File : OrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio

public static int FetchSubjectBrandRatingProductCount(this OrganizationServiceContext serviceContext, Guid subjectId, Guid brandId, double? minRating, double? maxRating)
		{
			var fetchXml = XDoreplacedent.Parse(@"
				<fetch mapping=""logical"" aggregate=""true"">
					<enreplacedy name=""product"">
						<attribute name=""productid"" aggregate=""count"" alias=""count"" />
						<filter type=""and"">
							<condition attribute=""subjectid"" operator=""eq"" />
							<condition attribute=""adx_brand"" operator=""eq"" />
							<condition attribute=""adx_ratingaverage"" operator=""ge"" />
							<condition attribute=""adx_ratingaverage"" operator=""lt"" />
							<condition attribute=""statecode"" operator=""eq"" value=""0"" />
						</filter>
					</enreplacedy>
				</fetch>");

			var subjectIdAttribute = fetchXml.XPathSelectElement("//condition[@attribute='subjectid']");

			if (subjectIdAttribute == null)
			{
				throw new InvalidOperationException("Unable to select the subjectid filter element.");
			}

			subjectIdAttribute.SetAttributeValue("value", subjectId.ToString());

			var brandIdAttribute = fetchXml.XPathSelectElement("//condition[@attribute='adx_brand']");

			if (brandIdAttribute == null)
			{
				throw new InvalidOperationException(string.Format("Unable to select {0} element.", "adx_brand filter"));
			}

			brandIdAttribute.SetAttributeValue("value", brandId);

			var minRatingAttribute = fetchXml.XPathSelectElement("//condition[@attribute='adx_ratingaverage' and @operator='ge']");

			if (minRatingAttribute == null)
			{
				throw new InvalidOperationException(ResourceManager.GetString("ADX_Ratingaveragegte_Filter_Element_Select_Exception"));
			}

			if (minRating.HasValue)
			{
				minRatingAttribute.SetAttributeValue("value", minRating.ToString());
			}
			else
			{
				minRatingAttribute.Remove();
			}

			var maxRatingAttribute = fetchXml.XPathSelectElement("//condition[@attribute='adx_ratingaverage' and @operator='lt']");

			if (maxRatingAttribute == null)
			{
				throw new InvalidOperationException(string.Format("Unable to select {0} element.", "adx_ratingaverage lt"));
			}
			
			if (maxRating.HasValue)
			{
				maxRatingAttribute.SetAttributeValue("value", maxRating.ToString());
			}
			else
			{
				maxRatingAttribute.Remove();
			}
			
			var response = (RetrieveMultipleResponse)serviceContext.Execute(new RetrieveMultipleRequest
			{
				Query = new FetchExpression(fetchXml.ToString())
			});

			return response.EnreplacedyCollection.Enreplacedies.First().GetAttributeAliasedValue<int>("count");
		}

19 View Source File : Profiler.cs
License : The Unlicense
Project Creator : aeroson

public override string ToString()
		{
			return AverageValue.ToString();
		}

19 View Source File : Planet.cs
License : The Unlicense
Project Creator : aeroson

void LateUpdate()
	{
		if (markedForRegeneration)
		{
			markedForRegeneration = false;
			ReGeneratePlanet();
			return;
		}

		var frameStart = Stopwatch.StartNew();

		double targetFrameTime = 1.0f / 60; // set here instead of Application.targetFrameRate, so frame time is limited only by this script
		double currentFrameTime = 1.0f * Time.unscaledDeltaTime;
		averageFrameTime.AddSample(currentFrameTime);
		long timeBudgetInTicks = (long)(TimeSpan.TicksPerSecond * (targetFrameTime - averageFrameTime.AverageValue));
		var timeBudget = new TimeSpan(timeBudgetInTicks);
		if (timeBudget.TotalMilliseconds > 10) timeBudget = new TimeSpan(0, 0, 0, 0, 10);
		if (timeBudget.TotalMilliseconds < 1) timeBudget = new TimeSpan(0, 0, 0, 0, 1);

		MyProfiler.BeginSample("Procedural Planet / milisecondsBudget", " " + timeBudget.TotalMilliseconds.ToString());

		var pointOfInterest = new PointOfInterest()
		{
			pos = FloatingOriginCamera.main.BigPosition,
			fieldOfView = FloatingOriginCamera.main.fieldOfView,
		};

		UpdateChunkRenderers(frameStart, timeBudget);

		MyProfiler.BeginSample("Procedural Planet / ReleaseGeneratedData");
		int countToCleanup = chunkGenerationJustFinished.Count; // try to free same amount of memory that was just needed for generation
		if (countToCleanup <= 1) countToCleanup = 1;
		while (--countToCleanup >= 0 && considerChunkForCleanup.Count > 0)
		{
			var chunk = considerChunkForCleanup.GetAndRemoveLeastRecentlyUsed();
			if (chunk == null) break;
			chunk.ReleaseGeneratedData();
		}
		MyProfiler.EndSample();

		GenerateChunks(frameStart, timeBudget);

		MyProfiler.BeginSample("Procedural Planet / Calculate desired subdivision");
		if (subdivisonCalculationCoroutine == null)
		{
			subdivisonCalculationCoroutine = subdivisonCalculationInProgress.StartCoroutine(this, pointOfInterest);
		}
		do // do at least once
		{
			if (!subdivisonCalculationCoroutine.MoveNext())
			{
				subdivisonCalculationCoroutine = null;
				var temp = subdivisonCalculationInProgress;
				subdivisonCalculationInProgress = subdivisonCalculationLast;
				subdivisonCalculationLast = temp;
				break;
			}
		} while (frameStart.Elapsed > timeBudget && subdivisonCalculationCoroutine != null);
		MyProfiler.EndSample();

		MyProfiler.EndSample();
	}

19 View Source File : ConversionTablePlugin.cs
License : GNU General Public License v2.0
Project Creator : afrantzis

void UpdateFloat(DataView dv)
	{
		long offset = dv.CursorOffset;

		// make sure offset is valid for 32 bit float (and 64 bit)
		if (offset < dv.Buffer.Size - 3 && offset >= 0) {
			// create byte[] with float bytes
			byte[] ba = new byte[8];

			// fill byte[] according to endianess
			if (littleEndian)
				for (int i = 0; i < 4; i++)
					ba[i] = dv.Buffer[offset+i];
			else
				for (int i = 0; i < 4; i++)
					ba[3-i] = dv.Buffer[offset+i];

			// set float 32bit
			float f = BitConverter.ToSingle(ba, 0);
			Float32bitEntry.Text = f.ToString();

			// make sure offset is valid for 64 bit float
			if (offset < dv.Buffer.Size - 7) {
				// fill byte[] according to endianess
				if (littleEndian)
					for (int i = 4; i < 8; i++)
						ba[i] = dv.Buffer[offset+i];
				else
					for (int i = 0; i < 8; i++)
						ba[7-i] = dv.Buffer[offset+i];

				// set float 64bit
				double d = BitConverter.ToDouble(ba, 0);
				Float64bitEntry.Text = d.ToString();
			}
			else
				Float64bitEntry.Text = "---";
		}
		else {
			ClearFloat();
		}

	}

19 View Source File : RedisArgs.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static string GetScore(double score, bool isExclusive)
        {
            if (Double.IsNegativeInfinity(score) || score == Double.MinValue)
                return "-inf";
            else if (Double.IsPositiveInfinity(score) || score == Double.MaxValue)
                return "+inf";
            else if (isExclusive)
                return '(' + score.ToString();
            else
                return score.ToString();
        }

19 View Source File : DefaultParamValueProcessors.cs
License : MIT License
Project Creator : aillieo

public string Save(double value)
        {
            return value.ToString();
        }

19 View Source File : NumericManipulator.cs
License : MIT License
Project Creator : akaskela

private double RoundSignificantDigits(double value, int significantDigits, out int roundingPosition)
        {
            // this method will return a rounded double value at a number of signifigant figures.
            // the sigFigures parameter must be between 0 and 15, exclusive.


            roundingPosition = 0;

            Precision p = new Precision();

            if (p.AlmostEquals(value, 0d))
            {
                roundingPosition = significantDigits - 1;
                return 0d;
            }

            if (double.IsNaN(value))
            {
                return double.NaN;
            }

            if (double.IsPositiveInfinity(value))
            {
                return double.PositiveInfinity;
            }

            if (double.IsNegativeInfinity(value))
            {
                return double.NegativeInfinity;
            }

            if (significantDigits < 1 || significantDigits > 15)
            {
                throw new ArgumentOutOfRangeException("significantDigits", value, "The significantDigits argument must be between 1 and 15.");
            }

            // if it's extremely insignificant, treat it as zero
            if (((double)value).ToString() != value.ToString())
            {
                value = 0;
            }

            // The resulting rounding position will be negative for rounding at whole numbers, and positive for decimal places.
            roundingPosition = significantDigits - 1 - (int)(Math.Floor(Math.Log10(Math.Abs(value))));

            // try to use a rounding position directly, if no scale is needed.
            // this is because the scale mutliplication after the rounding can introduce error, although 
            // this only happens when you're dealing with really tiny numbers, i.e 9.9e-14.
            if (roundingPosition > 0 && roundingPosition < 16)
            {
                return Math.Round(value, roundingPosition, MidpointRounding.AwayFromZero);
            }

            // Shouldn't get here unless we need to scale it.
            // Set the scaling value, for rounding whole numbers or decimals past 15 places
            var scale = Math.Pow(10, Math.Ceiling(Math.Log10(Math.Abs(value))));

            return Math.Round(value / scale, significantDigits, MidpointRounding.AwayFromZero) * scale;
        }

19 View Source File : UpdateProgress.cs
License : MIT License
Project Creator : AlbertMN

public void SetProgress(DownloadProgressChangedEventArgs e) {
            this.BeginInvoke((MethodInvoker)delegate {
                double bytesIn = double.Parse(e.BytesReceived.ToString());
                double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
                double percentage = bytesIn / totalBytes * 100;
                progressText.Text = int.Parse(Math.Truncate(percentage).ToString()) + "%";

                var transString = Translator.__("downloaded_bytes", "update_downloading");
                transString = transString.Replace("{x}", e.BytesReceived.ToString());
                transString = transString.Replace("{y}", e.TotalBytesToReceive.ToString());

                //byteText.Text = "Downloaded " + e.BytesReceived + " of " + e.TotalBytesToReceive + " bytes";
                byteText.Text = transString;

                progressBar.Value = int.Parse(Math.Truncate(percentage).ToString());
            });
        }

19 View Source File : BearingFilter.cs
License : MIT License
Project Creator : alen-smajic

public override string ToString()
		{
			if (this.Bearing != null && this.Range != null)
			{
				return this.Bearing.ToString() + "," + this.Range.ToString();
			}
			else
			{
				return string.Empty;
			}
		}

19 View Source File : AppHostApplicationPoolProcessModelConfigurator.cs
License : MIT License
Project Creator : alethic

public AppHostApplicationPoolProcessModelConfigurator IdleTimeout(TimeSpan? value)
        {
            return SetAttributeValue("idleTimeout", value?.TotalMinutes.ToString());
        }

19 View Source File : FileAttachmentControlViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private static string BytesToString(long byteCount)
        {
            string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; // Longs run out around EB
            if (byteCount == 0)
            {
                return "0" + suf[0];
            }

            long bytes = Math.Abs(byteCount);
            int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
            double num = Math.Round(bytes / Math.Pow(1024, place), 1);
            return (Math.Sign(byteCount) * num).ToString() + " " + suf[place];
        }

19 View Source File : ServerWebhook.cs
License : Apache License 2.0
Project Creator : AlexWan

private string UnixEpochTimestamp(DateTime time)
        {
            return (time.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalSeconds.ToString();
        }

19 View Source File : BitStampClient.cs
License : Apache License 2.0
Project Creator : AlexWan

private BuySellResponse Execute(double amount, double price, string securityUrl)
        {
            lock (_lock)
            {
                try
                {
                    var request = GetAuthenticatedRequest(Method.POST);
                    request.AddParameter("amount", amount.ToString().Replace(",", "."));
                    request.AddParameter("price", price.ToString().Replace(",", "."));

                    var response = new RestClient(securityUrl).Execute(request);

                    if (response.Content.IndexOf("error", StringComparison.Ordinal) > 0)
                    {
                        SendLogMessage("Ошибка на выставлении ордера", LogMessageType.Error);
                        SendLogMessage(response.Content, LogMessageType.Error);
                        return null;
                    }


                    return JsonConvert.DeserializeObject<BuySellResponse>(response.Content);
                }
                catch (Exception ex)
                {
                    SendLogMessage(ex.ToString(), LogMessageType.Error);
                    return null;
                }
            }
        }

19 View Source File : IndentationHelper.cs
License : Apache License 2.0
Project Creator : alexyakunin

public static IndentedTextWriter AppendMetric(this IndentedTextWriter writer, 
            string name, double? value, string unit, string format = "0.###") => 
            writer.AppendValue(name, value.ToString(format, unit));

19 View Source File : AopDictionary.cs
License : Apache License 2.0
Project Creator : alipay

public void Add(string key, object value)
        {
            string strValue;

            if (value == null)
            {
                strValue = null;
            }
            else if (value is string)
            {
                strValue = (string)value;
            }
            else if (value is Nullable<DateTime>)
            {
                Nullable<DateTime> dateTime = value as Nullable<DateTime>;
                strValue = dateTime.Value.ToString(DATE_TIME_FORMAT);
            }
            else if (value is Nullable<int>)
            {
                strValue = (value as Nullable<int>).Value.ToString();
            }
            else if (value is Nullable<long>)
            {
                strValue = (value as Nullable<long>).Value.ToString();
            }
            else if (value is Nullable<double>)
            {
                strValue = (value as Nullable<double>).Value.ToString();
            }
            else if (value is Nullable<bool>)
            {
                strValue = (value as Nullable<bool>).Value.ToString().ToLower();
            }
            else if (value is ICollection)
            {
                AopModelParser parser = new AopModelParser();
                object jo = parser.serializeArrayValue(value as ICollection);

                JsonSerializerSettings jsetting = new JsonSerializerSettings();
                jsetting.NullValueHandling = NullValueHandling.Ignore;
                strValue = JsonConvert.SerializeObject(jo, Formatting.None, jsetting);
            }
            else if (value is AopObject)
            {
                AopModelParser parser = new AopModelParser();
                object jo = parser.serializeAopObject(value as AopObject);

                JsonSerializerSettings jsetting = new JsonSerializerSettings();
                jsetting.NullValueHandling = NullValueHandling.Ignore;
                strValue = JsonConvert.SerializeObject(jo, Formatting.None, jsetting);
            }
            else
            {
                strValue = value.ToString();
            }

            this.Add(key, strValue);
        }

private void TraverseModel(string parentPath, string parentTypeName, string propertyName, JsonSchema currentJsonSchema, bool isRequired, ISet<string> alreadyVisitedTypes, JsonSchema parentJsonSchema, string parentXpath)
        {
            string sanitizedPropertyName = SanitizeName(propertyName);
            string xPath;
            string path;
            int index = 0;
            do
            {
                path = (string.IsNullOrEmpty(parentPath) ? string.Empty : parentPath + ".") + sanitizedPropertyName;
                xPath = (string.IsNullOrEmpty(parentXpath) ? "/" : parentXpath + "/") + propertyName;
                if (++index >= 2)
                {
                    path += index.ToString();
                    xPath += index.ToString();
                }
            }
            while (elements.ContainsKey(path));

            // exclude elements that does not start with firstPropertyName
            if (!path.StartsWith(firstPropertyName))
            {
                return;
            }

            string minItems = "0";
            string maxItems = "1";

            TypeKeyword currentJsonSchemaType = currentJsonSchema.Get<TypeKeyword>();

            if (currentJsonSchemaType != null && currentJsonSchemaType.Value == JsonSchemaType.Array)
            {
                List<JsonSchema> items = currentJsonSchema.Items();
                path += multiplicityString;
                FollowRef(path, items[0], alreadyVisitedTypes, xPath); // TODO fix multiple item types. It now uses only the first

                double? minItemsValue = currentJsonSchema.MinItems();
                double? maxItemsValue = currentJsonSchema.MaxItems();

                if (minItemsValue.HasValue)
                {
                    minItems = minItemsValue.ToString();
                }

                maxItems = "*";
                if (maxItemsValue.HasValue && maxItemsValue.Value != MagicNumberMaxOccurs)
                {
                    maxItems = maxItemsValue.ToString();
                }
            }
            else if (currentJsonSchemaType != null && currentJsonSchemaType.Value == JsonSchemaType.Object)
            {   
                if (alreadyVisitedTypes.Contains(sanitizedPropertyName))
                {
                    return;
                }

                ISet<string> currentlyVisitedTypes = new HashSet<string>(alreadyVisitedTypes);
                currentlyVisitedTypes.Add(sanitizedPropertyName);
                if (currentJsonSchema.Properties() != null)
                {
                    foreach (KeyValuePair<string, JsonSchema> def in currentJsonSchema.Properties())
                    {
                        TraverseModel(path, sanitizedPropertyName, def.Key, def.Value, IsRequired(def.Key, currentJsonSchema), currentlyVisitedTypes, currentJsonSchema, xPath);
                    }
                }                
            }
            else
            {
                FollowRef(path, currentJsonSchema, alreadyVisitedTypes, xPath);
                if (isRequired)
                {
                    minItems = "1";
                }
            }

            JsonObject result = new JsonObject();

            string inputType = "Field";
            string xsdType = currentJsonSchema.OtherData.TryGetString("@xsdType");

            result.Add("ID", RemoveStarsFromPath(path));

            string parentElement = ExtractParent(path);
            if (parentElement != null)
            {
                result.Add("ParentElement", RemoveStarsFromPath(parentElement));
            }

            string xsdValueType = FollowValueType(currentJsonSchema);

            string typeName = ExtractTypeNameFromSchema(currentJsonSchema);
            if (typeName != null)
            {
                result.Add("TypeName", SanitizeName(typeName));
            }
            else
            {
                result.Add("TypeName", sanitizedPropertyName);
            }

            result.Add("Name", sanitizedPropertyName);

            string fixedValue = null;
            JsonValue fixedValueJson = currentJsonSchema.Const();
            if (fixedValueJson != null)
            {
                fixedValue = fixedValueJson.String;
            }

            if (xsdType != null && xsdType.Equals("XmlAttribute"))
            {
                inputType = "Attribute";
            }
            else if ((currentJsonSchemaType == null && xsdValueType == null) || (currentJsonSchemaType != null && (currentJsonSchemaType.Value == JsonSchemaType.Object || currentJsonSchemaType.Value == JsonSchemaType.Array)))
            {
                inputType = "Group";
            }

            int maxOccursParsed = maxItems.Equals("*") ? MagicNumberMaxOccurs : int.Parse(maxItems);

            if ((!inputType.Equals("Group") && string.IsNullOrEmpty(fixedValue)) || (inputType.Equals("Group") && maxOccursParsed > 1))
            {
                string dataBindingNameWithoutFirstPropertyName = $"{parentXpath}/{propertyName}".Replace("/" + firstPropertyName + "/", string.Empty);
                string dataBindingName = dataBindingNameWithoutFirstPropertyName.Replace("/", ".");
                result.Add("DataBindingName", dataBindingName);
            }

            result.Add("XPath", xPath);

            result.Add("Restrictions", ExtractRestrictions(xsdValueType, currentJsonSchema));

            result.Add("Type", inputType);

            if (!string.IsNullOrEmpty(xsdValueType))
            {
                result.Add("XsdValueType", char.ToUpper(xsdValueType[0]) + xsdValueType.Substring(1)); // Uppercase first character
            }

            if (path.EndsWith(".value"))
            {
                result.Add("Texts", ExtractTexts(parentElement.Split(".").Last(), parentJsonSchema));
                result.Add("IsTagContent", true);
            }
            else
            {
                result.Add("Texts", ExtractTexts(propertyName, currentJsonSchema));
            }

            result.Add("CustomProperties", new JsonObject()); // ??

            result.Add("MaxOccurs", maxOccursParsed);
            result.Add("MinOccurs", int.Parse(minItems));

            result.Add("XName", propertyName);

            if (fixedValue != null)
            {
                result.Add("FixedValue", fixedValue);
            }

            string jsonSchemaPointer = "#/properties/" + propertyName;
            if (parentElement != null)
            {
                jsonSchemaPointer = "#/definitions/" + parentTypeName + "/properties/" + propertyName;
            }

            result.Add("JsonSchemaPointer", jsonSchemaPointer);

            string cardinality = "[" + minItems + ".." + maxItems + "]";
            string displayString = RemoveLastStar(path) + " : " + cardinality + " " + SanitizeName(typeName);
            result.Add("DisplayString", displayString);

            // TODO ..., XmlSchemaReference
            elements.Add(RemoveStarsFromPath(path), result);
        }

private static void AddRestrictionValue(JsonObject restriction, string name, double? value)
        {
            if (value.HasValue)
            {
                JsonObject len = new JsonObject();
                len.Add("Value", value.ToString());

                restriction.Add(name, len);
            }
        }

19 View Source File : JsonSchemaToXsd.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

private static XmlSchemaSimpleTypeRestriction ExtractNumberAndIntegerFacets(JsonSchema jSchema, TypeKeyword type)
        {
            XmlSchemaSimpleTypeRestriction content = new XmlSchemaSimpleTypeRestriction();
            double? minValue = GetterExtensions.Minimum(jSchema);
            double? minExclusiveValue = GetterExtensions.ExclusiveMinimum(jSchema);

            if (type.Value == JsonSchemaType.Number)
            {
                content.BaseTypeName = new XmlQualifiedName("decimal", XML_SCHEMA_NS);
            }
            else if (type.Value == JsonSchemaType.Integer)
            {
                if (minValue != null && minValue == 1)
                {
                    content.BaseTypeName = new XmlQualifiedName("positiveInteger", XML_SCHEMA_NS);
                }
                else
                {
                    content.BaseTypeName = new XmlQualifiedName("integer", XML_SCHEMA_NS);
                }
            }

            double? maxValue = GetterExtensions.Maximum(jSchema);
            double? maxExclusiveValue = GetterExtensions.ExclusiveMaximum(jSchema);

            Regex regex = new Regex("^[9]+$");
            if ((minValue != null && maxValue != null) && Math.Abs((double)minValue).Equals(maxValue) && regex.IsMatch(maxValue.ToString()))
            {
                XmlSchemaTotalDigitsFacet facet = new XmlSchemaTotalDigitsFacet
                {
                    Value = FormatDouble(maxValue.ToString().Length),
                };
                content.Facets.Add(facet);
            }
            else
            {
                if (minValue != null || minExclusiveValue != null)
                {
                    if (minValue != null)
                    {
                        XmlSchemaMinInclusiveFacet facet = new XmlSchemaMinInclusiveFacet
                        {
                            Value = FormatDouble((double)minValue),
                        };
                        content.Facets.Add(facet);
                    }
                    else
                    {
                        XmlSchemaMinExclusiveFacet facet = new XmlSchemaMinExclusiveFacet
                        {
                            Value = FormatDouble((double)minExclusiveValue),
                        };
                        content.Facets.Add(facet);
                    }
                }

                if (maxValue != null || maxExclusiveValue != null)
                {
                    if (maxValue != null)
                    {
                        XmlSchemaMaxInclusiveFacet maxInclusiveFacet = new XmlSchemaMaxInclusiveFacet
                        {
                            Value = FormatDouble((double)maxValue),
                        };
                        content.Facets.Add(maxInclusiveFacet);
                    }
                    else
                    {
                        XmlSchemaMaxExclusiveFacet maxExclusiveFacet = new XmlSchemaMaxExclusiveFacet
                        {
                            Value = FormatDouble((double)maxExclusiveValue),
                        };
                        content.Facets.Add(maxExclusiveFacet);
                    }
                }
            }

            return content;
        }

19 View Source File : CachablePing.cs
License : MIT License
Project Creator : alveflo

public string GetCacheKey()
            {
                return Value.ToString();
            }

19 View Source File : OverlayBase`1.cs
License : GNU General Public License v2.0
Project Creator : AmanoTooko

public static string ReplaceNaNString(string str, string replace)
            {
                return str.Replace(double.NaN.ToString(), replace);
            }

19 View Source File : Util.cs
License : GNU General Public License v2.0
Project Creator : AmanoTooko

public static string ReplaceNaNString(string str, string replace)
    {
      return str.Replace(double.NaN.ToString(), replace);
    }

19 View Source File : NumberToHumanReadableConverter.cs
License : GNU General Public License v3.0
Project Creator : Amebis

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return null;

            double number = System.Convert.ToDouble(value);
            int b = parameter != null ? System.Convert.ToInt32(parameter) : Base;

            if (number <= 0.5 && EmptyIfZero)
                return "";

            int n = number > 0.5 ? Math.Min((int)Math.Truncate(Math.Log(Math.Abs(number)) / Math.Log(b)), Prefixes.Length) : 0;
            double x = number / Math.Pow(b, n);
            return string.Format(
                Views.Resources.Strings.NumberToHumanReadable,
                n > 0 && Math.Abs(x) < 10 ?
                    (Math.Truncate(x * 10) / 10).ToString("N1") :
                     Math.Truncate(x).ToString(),
                Prefixes[n],
                Unit);
        }

19 View Source File : NumberBox.cs
License : MIT License
Project Creator : amwx

private void UpdateTextToValue()
        {
            if (_textBox == null)
                return;

            string newText = "";

            if (!double.IsNaN(_value))
            {
                // Round to 12 digits (standard .net rounding per WinUI in the NumberBox source)
                // We do this to prevent weirdness from floating point imprecision
                var newValue = Math.Round(_value, 12);
				if (SimpleNumberFormat != null)
				{
					newText = newValue.ToString(_simpleFormat);
				}
                else if (NumberFormatter != null)
                {
                    newText = NumberFormatter(newValue);
                }
                else
                {
                    newText = newValue.ToString();
                }
            }

            _textBox.Text = newText;

            try
            {
                _textUpdating = true;
                Text = newText;
            }
            finally
            {
                _textUpdating = false;
                MoveCaretToTextEnd(); //Add this
            }
        }

19 View Source File : frmMap.cs
License : GNU Lesser General Public License v3.0
Project Creator : andisturber

public void position(string a_0, string a_1, string b_0)
        {
            this.label3.Text = (double.Parse( a_1) - 0.0125).ToString();
            this.label4.Text = (double.Parse(a_0) - 0.00736).ToString();
            this.label5.Text = b_0;
        }

19 View Source File : LocationService.cs
License : GNU Lesser General Public License v3.0
Project Creator : andisturber

public void UpdateLocation(Location location)
        {
            if (Devices.Count == 0)
            {
                PrintMessage($"修改失败! 未发现任何设备。");
                return;
            }

            iDevice.idevice_set_debug_level(1);

            var Longitude = location.Longitude.ToString();
            var Lareplacedude = location.Lareplacedude.ToString();

            PrintMessage($"尝试修改位置。");
            PrintMessage($"经度:{location.Longitude}");
            PrintMessage($"纬度:{location.Lareplacedude}");

            var size = BitConverter.GetBytes(0u);
            Array.Reverse(size);
            Devices.ForEach(itm =>
            {
                PrintMessage($"开始修改设备 {itm.Name} {itm.Version}");

                var num = 0u;
                iDevice.idevice_new(out var device, itm.UDID);
                lockdown.lockdownd_client_new_with_handshake(device, out var client, "com.alpha.jailout").ThrowOnError();//com.alpha.jailout
                lockdown.lockdownd_start_service(client, "com.apple.dt.simulatelocation", out var service2).ThrowOnError();//com.apple.dt.simulatelocation
                var se = service.service_client_new(device, service2, out var client2);
                // 先置空
                se = service.service_send(client2, size, 4u, ref num);

                num = 0u;
                var bytesLocation = Encoding.ASCII.GetBytes(Lareplacedude);
                size = BitConverter.GetBytes((uint)Lareplacedude.Length);
                Array.Reverse(size);
                se = service.service_send(client2, size, 4u, ref num);
                se = service.service_send(client2, bytesLocation, (uint)bytesLocation.Length, ref num);


                bytesLocation = Encoding.ASCII.GetBytes(Longitude);
                size = BitConverter.GetBytes((uint)Longitude.Length);
                Array.Reverse(size);
                se = service.service_send(client2, size, 4u, ref num);
                se = service.service_send(client2, bytesLocation, (uint)bytesLocation.Length, ref num);



                //device.Dispose();
                //client.Dispose();
                PrintMessage($"设备 {itm.Name} {itm.Version} 位置修改完成。");
            });
        }

19 View Source File : DecimalValidationContract.cs
License : MIT License
Project Creator : andrebaltieri

public Contract<T> AreEquals(decimal val, double comparer, string key) =>
            AreEquals(val, (decimal)comparer, key, FluntErrorMessages.AreEqualsErrorMessage(val.ToString(), comparer.ToString()));

19 View Source File : DecimalValidationContract.cs
License : MIT License
Project Creator : andrebaltieri

public Contract<T> AreNotEquals(decimal val, double comparer, string key) =>
            AreNotEquals(val, (decimal)comparer, key, FluntErrorMessages.AreNotEqualsErrorMessage(val.ToString(), comparer.ToString()));

19 View Source File : DoubleValidationContract.cs
License : MIT License
Project Creator : andrebaltieri

public Contract<T> IsGreaterThan(double val, double comparer, string key) =>
            IsGreaterThan(val, comparer, key, FluntErrorMessages.IsGreaterThanErrorMessage(key, comparer.ToString()));

19 View Source File : DoubleValidationContract.cs
License : MIT License
Project Creator : andrebaltieri

public Contract<T> IsGreaterOrEqualsThan(double val, double comparer, string key) =>
            IsGreaterOrEqualsThan(val, comparer, key, FluntErrorMessages.IsGreaterOrEqualsThanErrorMessage(key, comparer.ToString()));

19 View Source File : DoubleValidationContract.cs
License : MIT License
Project Creator : andrebaltieri

public Contract<T> IsLowerThan(double val, double comparer, string key) =>
            IsLowerThan(val, comparer, key, FluntErrorMessages.IsLowerThanErrorMessage(key, comparer.ToString()));

19 View Source File : DoubleValidationContract.cs
License : MIT License
Project Creator : andrebaltieri

public Contract<T> IsLowerOrEqualsThan(double val, double comparer, string key) =>
            IsLowerOrEqualsThan(val, comparer, key, FluntErrorMessages.IsLowerOrEqualsThanErrorMessage(key, comparer.ToString()));

19 View Source File : DoubleValidationContract.cs
License : MIT License
Project Creator : andrebaltieri

public Contract<T> IsMinValue(double val, string key) =>
            IsMinValue(val, key, FluntErrorMessages.IsMinValueErrorMessage(key, double.MinValue.ToString()));

19 View Source File : DoubleValidationContract.cs
License : MIT License
Project Creator : andrebaltieri

public Contract<T> IsNotMinValue(double val, string key) =>
            IsNotMinValue(val, key, FluntErrorMessages.IsNotMinValueErrorMessage(key, double.MinValue.ToString()));

19 View Source File : DoubleValidationContract.cs
License : MIT License
Project Creator : andrebaltieri

public Contract<T> IsMaxValue(double val, string key) =>
            IsMaxValue(val, key, FluntErrorMessages.IsMaxValueErrorMessage(key, double.MaxValue.ToString()));

19 View Source File : DoubleValidationContract.cs
License : MIT License
Project Creator : andrebaltieri

public Contract<T> IsNotMaxValue(double val, string key) =>
            IsNotMaxValue(val, key, FluntErrorMessages.IsNotMaxValueErrorMessage(key, double.MaxValue.ToString()));

See More Examples