double.ToString(string)

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

1350 Examples 7

19 Source : ReportTimer.cs
with MIT License
from cgaueb

public void Report(int num_iterations, double error) {
        LumiLogger.Logger.Log("Finished after " + num_iterations.ToString() + " iterations. Final error: " + error.ToString("0.00") + "%." +
        ", Stages Time: 1. Remove LP: " + step1Time / 1000.0 + "s" + 
        ", 2. Remap EPs: " + step2Time / 1000.0 + "s" +
        ", 2.1 Tetrahed: " + tetrahedralizeTime / 1000.0 + "s" +
        ", 2.2 Mappings: " + mappingTime / 1000.0 + "s" +
        ", 3. Eval  EPs: " + step3Time / 1000.0 + "s" +
        ", 4. Calc Cost: " + step4Time / 1000.0 + "s" +
        ", 5. Find Min : " + step5Time / 1000.0 + "s" +
        ", 6. Insert LP: " + step6Time / 1000.0 + "s" +
        ", Total: " + (step1Time + step2Time + step3Time + step4Time + step5Time + step6Time) / 1000.0 + "s");
    }

19 Source : Evaluator.cs
with MIT License
from cgaueb

public List<Vector3> DecimateBakedLightProbes(LumiProbesScript script, ref bool isCancelled, List<Vector3> evaluationPoints, List<Vector3> lightProbePositions, 
        ref List<Vector3> removedList, ref List<SphericalHarmonicsL2> removedSHList) {
        // TODO: Add iterate [DONE]
        // TODO: Optimize [NOT], e.g. stochastic [DONE]
        // TODO: Modify cost function [DONE]
        // TODO: Verify result [DONE]
        // TODO: Potentially add multiple cost functions and error metrics [DONE]
        // TODO: Finalize plugin/UI software engineering [ALMOST DONE]

        // Optimizations TODO: Don't iterate against every EP/LP every time
        // Step 1: Ideally use a stochastic and approximate approach, i.e. remove random N at each iteration. [Partially done - Needs to check most important ones]
        // Step 2: Only perform mapping in the vicinity of the removed light probe. [NOT]
        // Step 3: Only evaluate points in the vicinity of the probe. [DONE - Disabled as it needs larger neighbourhood checks]
        // Step 4: Add a further optimization step to move LPs to "better" locations

        solversManager.SetCurrentSolver();
        metricsManager.SetCurrentMetric();
        removedList.Clear();
        removedSHList.Clear();

        // store the final result here
        List<Vector3> finalPositionsDecimated = new List<Vector3>(lightProbePositions);
        List<SphericalHarmonicsL2> finalLightProbesDecimated = new List<SphericalHarmonicsL2>(tetrahedronGraph.LightProbesBakedProbes);
        double currentEvaluationError = 0.0;
        int iteration = 0;
        float termination_error = isTerminationEvaluationError ? terminationEvaluationError : float.MaxValue;
        int termination_probes = isTerminationCurrentLightProbes ? terminationCurrentLightProbes : 0;

        LumiLogger.Logger.Log("Starting Decimation. Settings: " +
            "LPs: " + script.CurrentLightProbesGenerator.TotalNumProbes +
            ", EPs: " + script.CurrentEvaluationPointsGenerator.TotalNumProbes +
            ", LP Evaluation method: " + directionSamplingGenerator.EvaluationType.ToString() + " (" + directionSamplingGenerator.GetDirectionCount() + ")" +
            ", Averaging EP directions: " + averageDirections.ToString() +
           // ", Stochastic: " + (is_stochastic ? num_stochastic_samples.ToString() : "Disabled") +
            ", Solver: " + solversManager.CurrentSolverType.ToString() +
            ", Metric: " + metricsManager.CurrentMetricType.ToString() +
            ", Minimum Error: " + (isTerminationEvaluationError ? termination_error.ToString() : "Disabled") +
            ", Minimum LP Set: " + (isTerminationCurrentLightProbes ? termination_probes.ToString() : "Disabled"));

        System.Diagnostics.Stopwatch stopwatch;

        // holds the current minimum evaluation results
        //List<Color> decimatedEvaluationResultsMin = new List<Color>(referenceEvaluationResults);
        //List<Color> prevEvaluationResults = new List<Color>(referenceEvaluationResults);
        //List<List<int>> mappingLPtoEPDecimatedMin = new List<List<int>>(finalLightProbesDecimated.Count - 1);
        int decimatedIndexMin = -1;
        double decimatedCostMin = double.MaxValue;

        float progress_range = terminationMaxLightProbes - terminationCurrentLightProbes;
        float progress_step = 1 / (progress_range);
        System.DateTime startTime = System.DateTime.Now;

        while (currentEvaluationError < termination_error && termination_probes < finalPositionsDecimated.Count && finalPositionsDecimated.Count > 4 && !isCancelled) {
            // remove the Probe which contributes "the least" to the reference

            float progress = 0.0f; 
            if (isTerminationCurrentLightProbes) {
                progress = (lightProbePositions.Count - finalPositionsDecimated.Count) / progress_range;
            }

            int random_samples_each_iteration = (is_stochastic) ? Mathf.Min(num_stochastic_samples, finalPositionsDecimated.Count) : finalPositionsDecimated.Count;
            for (int i = 0; i < random_samples_each_iteration && !isCancelled; i++) {
                // update progress bar
                System.TimeSpan interval = (System.DateTime.Now - startTime);
                string timeText = string.Format("{0:D2}:{1:D2}:{2:D2}", interval.Hours, interval.Minutes, interval.Seconds);
                //LumiLogger.Logger.Log((progress).ToString("0.0%"));
                if (isTerminationCurrentLightProbes && isTerminationEvaluationError) {
                    float internal_progress = progress + (progress_step * i / (float)(random_samples_each_iteration));
                    isCancelled = EditorUtility.DisplayCancelableProgressBar("Decimation: " + "Progress: " + (internal_progress).ToString("0.0%") + ", Error: " + currentEvaluationError.ToString("0.00") + "%", timeText + " Running: Remaining probes: " + finalPositionsDecimated.Count.ToString(), internal_progress);
                } else if (isTerminationEvaluationError) {
                    isCancelled = EditorUtility.DisplayCancelableProgressBar("Decimation: " + "Error: " + currentEvaluationError.ToString("0.00") + "%", timeText + " Running: Remaining probes: " + finalPositionsDecimated.Count.ToString(), progress);
                } else {
                    float internal_progress = progress + (progress_step * i / (float)(random_samples_each_iteration));
                    isCancelled = EditorUtility.DisplayCancelableProgressBar("Decimation: " + "Progress: " + (internal_progress).ToString("0.0%"), timeText + " Running: Remaining probes: " + finalPositionsDecimated.Count.ToString(), internal_progress);
                  }

                // 1. Remove Light Probe from Set
                stopwatch = System.Diagnostics.Stopwatch.StartNew();
                int random_index = (is_stochastic) ? Random.Range(0, finalPositionsDecimated.Count) : i;
                Vector3 last_position_removed = finalPositionsDecimated[random_index];
                finalPositionsDecimated.RemoveAt(random_index);
                SphericalHarmonicsL2 last_SH_removed = finalLightProbesDecimated[random_index];
                finalLightProbesDecimated.RemoveAt(random_index);
                // replacedign the new probe data to the graph
                tetrahedronGraph.LightProbesBakedProbes = finalLightProbesDecimated;
                stopwatch.Stop();
                reportTimer.step1Time += stopwatch.ElapsedMilliseconds;

                // 2. Map Evaluation Points to New Light Probe Set 
                stopwatch = System.Diagnostics.Stopwatch.StartNew();
                Tetrahedralize(finalPositionsDecimated);
                (int, int) mapresult = MapEvaluationPointsToLightProbes(finalPositionsDecimated, evaluationPoints, ref mappingLPtoEPDecimated);
                if (mapresult.Item1 == -1) {
                    // invalid result (4 planar probes?), add back the item and continue
                    stopwatch = System.Diagnostics.Stopwatch.StartNew();
                    finalPositionsDecimated.Insert(random_index, last_position_removed);
                    finalLightProbesDecimated.Insert(random_index, last_SH_removed);
                    stopwatch.Stop();
                    reportTimer.step6Time += stopwatch.ElapsedMilliseconds;
                    continue;
                }
                Debug.replacedert(evaluationPoints.Count - mapresult.Item1 - mapresult.Item2 == 0);
                stopwatch.Stop();
                reportTimer.step2Time += stopwatch.ElapsedMilliseconds;

                // 3. Evaluate only the points that have changed
                stopwatch = System.Diagnostics.Stopwatch.StartNew();
                // Flag the evaluation points that have changed for the removed Light Probe
                /*foreach (int evalIndex in mappingLPtoEP[random_index]) {
                    tetrahedronGraph.FlagEvaluationPointΑsChanged(evalIndex, true);
                }*/
                //List<Color> currentEvaluationResults = EvaluatePoints(evaluationPoints, prevEvaluationResults);
                List<Color> currentEvaluationResults = EvaluatePoints(evaluationPoints, null);
                stopwatch.Stop();
                reportTimer.step3Time += stopwatch.ElapsedMilliseconds;

                // 4. Compute Cost of current configuration
                stopwatch = System.Diagnostics.Stopwatch.StartNew();
                double decimatedCost = solversManager.computeLoss(currentEvaluationResults, referenceEvaluationResults);
                stopwatch.Stop();
                reportTimer.step4Time += stopwatch.ElapsedMilliseconds;

                // 5. Find light probe with the minimum error
                stopwatch = System.Diagnostics.Stopwatch.StartNew();
                if (decimatedCost > 0 && decimatedCost < decimatedCostMin) {
                    decimatedIndexMin = i;
                    decimatedCostMin = decimatedCost;
                    /*decimatedEvaluationResultsMin = new List<Color>(prevEvaluationResults);
                    foreach (int j in mappingLPtoEP[random_index]) {
                        decimatedEvaluationResultsMin[j] = new Color(currentEvaluationResults[j].r, currentEvaluationResults[j].g, currentEvaluationResults[j].b);
                    }
                    mappingLPtoEPDecimatedMin = new List<List<int>>(mappingLPtoEPDecimated);
                    */
                }

                //LumiLogger.Logger.Log("Iteration: " + iteration + ", Probe " + i + " with cost " + decimatedCost.ToString() + ", Min Cost: " + decimatedCostMin);

                stopwatch.Stop();
                reportTimer.step5Time += stopwatch.ElapsedMilliseconds;

                // add back the removed items O(n)
                stopwatch = System.Diagnostics.Stopwatch.StartNew();
                finalPositionsDecimated.Insert(random_index, last_position_removed);
                finalLightProbesDecimated.Insert(random_index, last_SH_removed);
                stopwatch.Stop();
                reportTimer.step6Time += stopwatch.ElapsedMilliseconds;
            }

            if (decimatedIndexMin == -1) {
                LumiLogger.Logger.LogError("No probe found during the iteration. Forced stopping.");
                break;
            }

            // if we have terminated on error, skip this iteration
            if (isTerminationEvaluationError && decimatedCostMin > termination_error) {
                LumiLogger.Logger.Log("Iteration: " + iteration.ToString() + ". Error: " + decimatedCostMin.ToString() + ". Stopping using max error criteria");
                break;
            }
            // 6. Remove light probe with the minimum error
            removedList.Add(finalPositionsDecimated[decimatedIndexMin]);
            removedSHList.Add(finalLightProbesDecimated[decimatedIndexMin]);
            finalPositionsDecimated.RemoveAt(decimatedIndexMin);
            finalLightProbesDecimated.RemoveAt(decimatedIndexMin);

            // update reference values with the new ones
            currentEvaluationError = decimatedCostMin;
            //prevEvaluationResults = new List<Color>(decimatedEvaluationResultsMin);
            //mappingLPtoEP = new List<List<int>>(mappingLPtoEPDecimatedMin);
            //LumiLogger.Logger.Log("Iteration: " + iteration.ToString() + ". Error: " + decimatedCostMin.ToString() + ". Removed probe: " + decimatedIndexMin.ToString());

            // reset to default state
            //mappingLPtoEPDecimatedMin = new List<List<int>>(finalLightProbesDecimated.Count - 1);
            decimatedIndexMin = -1;
            decimatedCostMin = double.MaxValue;

            ++iteration;
        }

        {
            // update progress bar
            float progress = (lightProbePositions.Count - finalPositionsDecimated.Count) / progress_range;
            System.TimeSpan interval = (System.DateTime.Now - startTime);
            string timeText = string.Format("{0:D2}:{1:D2}:{2:D2}", interval.Hours, interval.Minutes, interval.Seconds);
            //LumiLogger.Logger.Log((progress).ToString("0.0%"));
            if (isTerminationCurrentLightProbes && isTerminationEvaluationError) {
                isCancelled = EditorUtility.DisplayCancelableProgressBar("Decimation: " + "Progress: " + (progress).ToString("0.0%") + ", Error: " + currentEvaluationError.ToString("0.00") + "%", timeText + " Running: Remaining probes: " + finalPositionsDecimated.Count.ToString(), progress);
              } else if (isTerminationEvaluationError) {
                isCancelled = EditorUtility.DisplayCancelableProgressBar("Decimation: " + "Error: " + currentEvaluationError.ToString("0.00") + "%", timeText + " Running: Remaining probes: " + finalPositionsDecimated.Count.ToString(), progress);
            } else {
                isCancelled = EditorUtility.DisplayCancelableProgressBar("Decimation: " + "Progress: " + (progress).ToString("0.0%"), timeText + " Running: Remaining probes: " + finalPositionsDecimated.Count.ToString(), progress);
            }
        }

        if (!isCancelled) {
            evaluationError = currentEvaluationError;
        }

        reportTimer.Report(iteration, evaluationError);

        return finalPositionsDecimated;
    }

19 Source : Program.cs
with MIT License
from ch00486259

private static void StartMonite()
        {
            Task.Factory.StartNew(() => {
                var intervalSecond = 2;

                while (true)
                {
                    var processCount = Interlocked.Exchange(ref RpcDebugger.ProcessCount, 0);
                    var processTime = Interlocked.Exchange(ref RpcDebugger.ProcessTime, 0);

                    _totalCount += processCount;

                    processCount = processCount / intervalSecond;
                    processTime = processTime / intervalSecond;
                    if (processCount == 0)
                        processCount = 1;

                    var pt = processTime * 1.0d / processCount;

                    WriteMessage(string.Format("[thread_count:{0}][rps:{1}][process time:{2}ms]", _threadCount, processCount, pt.ToString("f3")));

                    Thread.Sleep(intervalSecond * 1000);
                }
            }, TaskCreationOptions.LongRunning);
        }

19 Source : Form1.cs
with GNU General Public License v3.0
from Charltsing

private void pictureBox1_Click(object sender, EventArgs e)
        {
            capturecount = 0;
            isPause = false;
            var me = ((System.Windows.Forms.MouseEventArgs)(e));
            if (me.Button==MouseButtons.Left)              //按下左键是黑人底部坐标
            {
                Start = ((System.Windows.Forms.MouseEventArgs)(e)).Location;
            }
            else if (me.Button == MouseButtons.Right)      //按下右键键是终点坐标
            {
                if (Start.X==0)
                {
                    Start = new Point(StartX, StartY);
                }
                End = ((System.Windows.Forms.MouseEventArgs)(e)).Location;
                //计算两点直接的距离
                double value = Math.Sqrt(Math.Abs(Start.X - End.X) * Math.Abs(Start.X - End.X) + Math.Abs(Start.Y - End.Y) * Math.Abs(Start.Y - End.Y));
                
                //3.999022243950134  这个是我通过多次模拟后得到 我这个分辨率的最佳时间
                if (this.tbxPressTimeValue.Text.Trim().Length==0)
                {
                    tbxPressTimeValue.Text = "4.0";// "3.999022243950134";
                }
                double timevalue;
                bool ret;
                ret=double.TryParse(tbxPressTimeValue.Text,out timevalue);
                if (!ret)
                {
                    tbxPressTimeValue.Text = "4.0";
                    timevalue = 4.0d;
                }
                Text = string.Format("距离:{0},时间:{1}", value.ToString("0.00"), (timevalue * value).ToString("0.000"));

                Random ran = new Random();
                string rndX = ran.Next(100, 300).ToString();
                string rndY = ran.Next(100, 600).ToString();
                string offsetx = ran.Next(10, 50).ToString();
                string offsety = ran.Next(10, 100).ToString();
                ADB.RunADBShellCommand(string.Format("shell input swipe {0} {1} {2} {3} {4}", 
                                                     rndX, rndY, (int.Parse(rndX) + int.Parse(offsetx)).ToString(), (int.Parse(rndY) + int.Parse(offsety)).ToString(), (timevalue * value).ToString("0")));
                
                Cursor = Cursors.WaitCursor;
                int delay = 2500;
                ret = int.TryParse(textBox1.Text, out delay);
                if (!ret)
                {
                    textBox1.Text="1200";
                }
                if (delay < 500) delay = 500;
                if (delay > 5000) delay = 5000;
                isWaiting = true;
                Thread.Sleep(delay);
                Cursor = Cursors.Default;
                isWaiting = false;                
                
                Start = new Point(0, 0);
            }
        }

19 Source : RTSPClient.cs
with MIT License
from chatop2020

private void ProcessRTPPackets()
        {
            try
            {
                Thread.CurrentThread.Name = "rtspclient-rtp";

                _lastRTPReceivedAt = DateTime.Now;
                _lastBWCalcAt = DateTime.Now;

                while (!_isClosed)
                {
                    while (_rtspSession.HasRTPPacket())
                    {
                        RTPPacket rtpPacket = _rtspSession.GetNextRTPPacket();

                        if (rtpPacket != null)
                        {
                            _lastRTPReceivedAt = DateTime.Now;
                            _bytesSinceLastBWCalc += RTPHeader.MIN_HEADER_LEN + rtpPacket.Payload.Length;

                            if (_rtpTrackingAction != null)
                            {
                                double bwCalcSeconds = DateTime.Now.Subtract(_lastBWCalcAt).TotalSeconds;
                                if (bwCalcSeconds > BANDWIDTH_CALCULATION_SECONDS)
                                {
                                    _lastBWCalc = _bytesSinceLastBWCalc * 8 / bwCalcSeconds;
                                    _lastFrameRate = _framesSinceLastCalc / bwCalcSeconds;
                                    _bytesSinceLastBWCalc = 0;
                                    _framesSinceLastCalc = 0;
                                    _lastBWCalcAt = DateTime.Now;
                                }

                                var abbrevURL = (_url.Length <= 50) ? _url : _url.Substring(0, 50);
                                string rtpTrackingText = String.Format("Url: {0}\r\nRcvd At: {1}\r\nSeq Num: {2}\r\nTS: {3}\r\nPayoad: {4}\r\nFrame Size: {5}\r\nBW: {6}\r\nFrame Rate: {7}", abbrevURL, DateTime.Now.ToString("HH:mm:ss:fff"), rtpPacket.Header.SequenceNumber, rtpPacket.Header.Timestamp, ((SDPMediaFormatsEnum)rtpPacket.Header.PayloadType).ToString(), _lastFrameSize + " bytes", _lastBWCalc.ToString("0.#") + "bps", _lastFrameRate.ToString("0.##") + "fps");
                                _rtpTrackingAction(rtpTrackingText);
                            }

                            if (rtpPacket.Header.Timestamp < _lastCompleteFrameTimestamp)
                            {
                                System.Diagnostics.Debug.WriteLine("Ignoring RTP packet with timestamp " + rtpPacket.Header.Timestamp + " as it's earlier than the last complete frame.");
                            }
                            else
                            {
                                while (_frames.Count > MAX_FRAMES_QUEUE_LENGTH)
                                {
                                    var oldestFrame = _frames.OrderBy(x => x.Timestamp).First();
                                    _frames.Remove(oldestFrame);
                                    System.Diagnostics.Debug.WriteLine("Receive queue full, dropping oldest frame with timestamp " + oldestFrame.Timestamp + ".");
                                }

                                var frame = _frames.Where(x => x.Timestamp == rtpPacket.Header.Timestamp).SingleOrDefault();

                                if (frame == null)
                                {
                                    frame = new RTPFrame() { Timestamp = rtpPacket.Header.Timestamp, HasMarker = rtpPacket.Header.MarkerBit == 1 };
                                    frame.AddRTPPacket(rtpPacket);
                                    _frames.Add(frame);
                                }
                                else
                                {
                                    frame.HasMarker = (rtpPacket.Header.MarkerBit == 1);
                                    frame.AddRTPPacket(rtpPacket);
                                }

                                if (frame.IsComplete())
                                {
                                    // The frame is ready for handing over to the UI.
                                    byte[] imageBytes = frame.GetFramePayload();

                                    _lastFrameSize = imageBytes.Length;
                                    _framesSinceLastCalc++;

                                    _lastCompleteFrameTimestamp = rtpPacket.Header.Timestamp;
                                    //System.Diagnostics.Debug.WriteLine("Frame ready " + frame.Timestamp + ", sequence numbers " + frame.StartSequenceNumber + " to " + frame.EndSequenceNumber + ",  payload length " + imageBytes.Length + ".");
                                    //logger.LogDebug("Frame ready " + frame.Timestamp + ", sequence numbers " + frame.StartSequenceNumber + " to " + frame.EndSequenceNumber + ",  payload length " + imageBytes.Length + ".");
                                    _frames.Remove(frame);

                                    // Also remove any earlier frames as we don't care about anything that's earlier than the current complete frame.
                                    foreach (var oldFrame in _frames.Where(x => x.Timestamp <= rtpPacket.Header.Timestamp).ToList())
                                    {
                                        System.Diagnostics.Debug.WriteLine("Discarding old frame for timestamp " + oldFrame.Timestamp + ".");
                                        logger.LogWarning("Discarding old frame for timestamp " + oldFrame.Timestamp + ".");
                                        _frames.Remove(oldFrame);
                                    }

                                    if (OnFrameReady != null)
                                    {
                                        try
                                        {
                                            //if (frame.FramePackets.Count == 1)
                                            //{
                                            //    // REMOVE.
                                            //    logger.LogWarning("Discarding frame as there should have been more than 1 RTP packets.");
                                            //}
                                            //else
                                            //{
                                            //System.Diagnostics.Debug.WriteLine("RTP frame ready for timestamp " + frame.Timestamp + ".");
                                            OnFrameReady(this, frame);
                                            //}
                                        }
                                        catch (Exception frameReadyExcp)
                                        {
                                            logger.LogError("Exception RTSPClient.ProcessRTPPackets OnFrameReady. " + frameReadyExcp);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (DateTime.Now.Subtract(_lastRTPReceivedAt).TotalSeconds > RTP_TIMEOUT_SECONDS)
                    {
                        logger.LogWarning("No RTP packets were received on RTSP session " + _rtspSession.SessionID + " for " + RTP_TIMEOUT_SECONDS + ". The session will now be closed.");
                        Close();
                    }
                    else
                    {
                        Thread.Sleep(1);
                    }
                }
            }
            catch (Exception excp)
            {
                logger.LogError("Exception RTSPClient.ProcessRTPPackets. " + excp);
            }
        }

19 Source : Library.cs
with Apache License 2.0
from Chem4Word

private string CmlFromBytes(byte[] byteArray, long id)
        {
            string cml = Encoding.UTF8.GetString(byteArray);
            CMLConverter cc = new CMLConverter();
            Model.Model m = cc.Import(cml);
            double before = m.MeanBondLength;
            if (before < Constants.MinimumBondLength - Constants.BondLengthTolerance
                || before > Constants.MaximumBondLength + Constants.BondLengthTolerance)
            {
                m.ScaleToAverageBondLength(Constants.StandardBondLength);
                double after = m.MeanBondLength;
                Debug.WriteLine($"Structure Id: {id} rescaled from {before.ToString("#0.00")} to {after.ToString("#0.00")}");
            }

            return cc.Export(m);
        }

19 Source : Library.cs
with Apache License 2.0
from Chem4Word

public bool ImportCml(string cmlFile)
        {
            string module = $"{_product}.{_clreplaced}.{MethodBase.GetCurrentMethod().Name}()";

            bool result = false;

            try
            {
                var converter = new CMLConverter();
                Model.Model model = converter.Import(cmlFile);

                if (model.AllAtoms.Count > 0)
                {
                    double before = model.MeanBondLength;
                    if (before < Constants.MinimumBondLength - Constants.BondLengthTolerance
                        || before > Constants.MaximumBondLength + Constants.BondLengthTolerance)
                    {
                        model.ScaleToAverageBondLength(Constants.StandardBondLength);
                        double after = model.MeanBondLength;
                        Globals.Chem4WordV3.Telemetry.Write(module, "Information", $"Structure rescaled from {before.ToString("#0.00")} to {after.ToString("#0.00")}");
                    }

                    // Ensure each molecule has a Consise Formula set
                    foreach (var molecule in model.Molecules)
                    {
                        if (string.IsNullOrEmpty(molecule.ConciseFormula))
                        {
                            molecule.ConciseFormula = molecule.CalculatedFormula();
                        }
                    }

                    CMLConverter cmlConverter = new CMLConverter();
                    model.CustomXmlPartGuid = "";
                    var cml = cmlConverter.Export(model);

                    string chemicalName = model.ConciseFormula;
                    var mol = model.Molecules[0];
                    if (mol.ChemicalNames.Count > 0)
                    {
                        foreach (var name in mol.ChemicalNames)
                        {
                            long temp;
                            if (!long.TryParse(name.Name, out temp))
                            {
                                chemicalName = name.Name;
                                break;
                            }
                        }
                    }

                    using (SQLiteConnection conn = LibraryConnection())
                    {
                        var id = AddChemistry(conn, cml, chemicalName, model.ConciseFormula);
                        foreach (var name in mol.ChemicalNames)
                        {
                            AddChemicalName(conn, id, name.Name, name.DictRef);
                        }
                    }

                    result = true;
                }
            }
            catch (Exception ex)
            {
                new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex).ShowDialog();
            }

            return result;
        }

19 Source : ChemistryHelper.cs
with Apache License 2.0
from Chem4Word

public static Word.ContentControl Insert2DChemistry(Word.Doreplacedent doc, string cml, bool isCopy)
        {
            string module = $"{Product}.{Clreplaced}.{MethodBase.GetCurrentMethod().Name}()";

            if (Globals.Chem4WordV3.SystemOptions == null)
            {
                Globals.Chem4WordV3.LoadOptions();
            }

            // Calling routine should check that Globals.Chem4WordV3.ChemistryAllowed = true

            Word.ContentControl cc = null;
            Word.Application app = doc.Application;

            var wordSettings = new WordSettings(app);

            IChem4WordRenderer renderer =
                Globals.Chem4WordV3.GetRendererPlugIn(
                    Globals.Chem4WordV3.SystemOptions.SelectedRendererPlugIn);

            if (renderer != null)
            {
                try
                {
                    app.ScreenUpdating = false;
                    Globals.Chem4WordV3.DisableContentControlEvents();

                    var converter = new CMLConverter();
                    var model = converter.Import(cml);
                    var modified = false;

                    double before = model.MeanBondLength;
                    if (before < Constants.MinimumBondLength - Constants.BondLengthTolerance
                        || before > Constants.MaximumBondLength + Constants.BondLengthTolerance)
                    {
                        model.ScaleToAverageBondLength(Constants.StandardBondLength);
                        modified = true;
                        double after = model.MeanBondLength;
                        Globals.Chem4WordV3.Telemetry.Write(module, "Information", $"Structure rescaled from {before.ToString("#0.00")} to {after.ToString("#0.00")}");
                    }

                    if (isCopy)
                    {
                        // Always generate new Guid on Import
                        model.CustomXmlPartGuid = Guid.NewGuid().ToString("N");
                        modified = true;
                    }

                    // Ensure each molecule has a Concise Formula set
                    foreach (var molecule in model.Molecules)
                    {
                        if (string.IsNullOrEmpty(molecule.ConciseFormula))
                        {
                            molecule.ConciseFormula = molecule.CalculatedFormula();
                            modified = true;
                        }
                    }

                    if (modified)
                    {
                        // Re-export as the CustomXmlPartGuid or Bond Length has been changed
                        cml = converter.Export(model);
                    }

                    string guid = model.CustomXmlPartGuid;

                    renderer.Properties = new Dictionary<string, string>();
                    renderer.Properties.Add("Guid", guid);
                    renderer.Cml = cml;

                    // Generate temp file which can be inserted into a content control
                    string tempfileName = renderer.Render();
                    if (File.Exists(tempfileName))
                    {
                        cc = doc.ContentControls.Add(Word.WdContentControlType.wdContentControlRichText, ref _missing);
                        Insert2D(cc.ID, tempfileName, guid);

                        if (isCopy)
                        {
                            doc.CustomXMLParts.Add(cml);
                        }

                        try
                        {
                            // Delete the temporary file now we are finished with it
#if DEBUG
#else
                            File.Delete(tempfileName);
#endif
                        }
                        catch
                        {
                            // Not much we can do here
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Error in Insert2DChemistry; See InnerException for details", ex);
                }
                finally
                {
                    app.ScreenUpdating = true;
                    Globals.Chem4WordV3.EnableContentControlEvents();
                }
            }

            wordSettings.RestoreSettings(app);

            return cc;
        }

19 Source : WpfChemDoodle.xaml.cs
with Apache License 2.0
from Chem4Word

private void SetupControls()
        {
            string module = $"{_product}.{_clreplaced}.{MethodBase.GetCurrentMethod().Name}()";

            ShowHydrogens.IsChecked = UserOptions.ShowHydrogens;
            ShowColour.IsChecked = UserOptions.ColouredAtoms;
            ShowCarbons.IsChecked = UserOptions.ShowCarbons;

            if (AverageBondLength < Constants.MinimumBondLength - Constants.BondLengthTolerance
                || AverageBondLength > Constants.MaximumBondLength + Constants.BondLengthTolerance)
            {
                BondLength.Text = Constants.StandardBondLength.ToString("0");
                AverageBondLength = Constants.StandardBondLength;
            }
            else
            {
                AverageBondLength = Math.Round(AverageBondLength / 5.0) * 5;
                BondLength.Text = AverageBondLength.ToString("0");
            }

            if (IsSingleMolecule)
            {
                SwitchToSingle.IsChecked = true;
                SwitchToMulti.IsChecked = false;
            }
            else
            {
                SwitchToMulti.IsChecked = true;
                SwitchToSingle.IsChecked = false;
            }
        }

19 Source : OoXmlRenderer.cs
with Apache License 2.0
from Chem4Word

private void DrawBox(Wpg.WordprocessingGroup wordprocessingGroup1, Rect extents, string colour, int thick)
        {
            UInt32Value bondLineId = UInt32Value.FromUInt32((uint)_ooxmlId++);
            string bondLineName = "diag-box-" + bondLineId;

            Int64Value width1 = OoXmlHelper.ScaleCmlToEmu(extents.Width);
            Int64Value height1 = OoXmlHelper.ScaleCmlToEmu(extents.Height);
            Int64Value top1 = OoXmlHelper.ScaleCmlToEmu(extents.Top);
            Int64Value left1 = OoXmlHelper.ScaleCmlToEmu(extents.Left);

            Point pp1 = new Point(left1, top1);
            Size ss2 = new Size(width1, height1);
            pp1.Offset(OoXmlHelper.ScaleCmlToEmu(-_canvasExtents.Left), OoXmlHelper.ScaleCmlToEmu(-_canvasExtents.Top));
            Rect boundingBox = new Rect(pp1, ss2);

            Int64Value width = (Int64Value)boundingBox.Width;
            Int64Value height = (Int64Value)boundingBox.Height;
            Int64Value top = (Int64Value)boundingBox.Top;
            Int64Value left = (Int64Value)boundingBox.Left;

            Wps.WordprocessingShape wordprocessingShape1 = new Wps.WordprocessingShape();
            Wps.NonVisualDrawingProperties nonVisualDrawingProperties1 = new Wps.NonVisualDrawingProperties()
            {
                Id = bondLineId,
                Name = bondLineName
            };
            Wps.NonVisualDrawingShapeProperties nonVisualDrawingShapeProperties1 = new Wps.NonVisualDrawingShapeProperties();

            Wps.ShapeProperties shapeProperties1 = new Wps.ShapeProperties();

            A.Transform2D transform2D1 = new A.Transform2D();
            A.Offset offset2 = new A.Offset() { X = left, Y = top };
            A.Extents extents2 = new A.Extents() { Cx = width, Cy = height };

            transform2D1.Append(offset2);
            transform2D1.Append(extents2);

            A.CustomGeometry customGeometry1 = new A.CustomGeometry();
            A.AdjustValueList adjustValueList1 = new A.AdjustValueList();
            A.Rectangle rectangle1 = new A.Rectangle() { Left = "l", Top = "t", Right = "r", Bottom = "b" };

            A.PathList pathList1 = new A.PathList();

            A.Path path1 = new A.Path() { Width = width, Height = height };

            // Starting Point
            A.MoveTo moveTo1 = new A.MoveTo();
            A.Point point1 = new A.Point() { X = "0", Y = "0" };
            moveTo1.Append(point1);

            // Mid Point
            A.LineTo lineTo1 = new A.LineTo();
            A.Point point2 = new A.Point() { X = boundingBox.Width.ToString("0"), Y = "0" };
            lineTo1.Append(point2);

            // Mid Point
            A.LineTo lineTo2 = new A.LineTo();
            A.Point point3 = new A.Point() { X = boundingBox.Width.ToString("0"), Y = boundingBox.Height.ToString("0") };
            lineTo2.Append(point3);

            // Last Point
            A.LineTo lineTo3 = new A.LineTo();
            A.Point point4 = new A.Point() { X = "0", Y = boundingBox.Height.ToString("0") };
            lineTo3.Append(point4);

            // Back to Start Point
            A.LineTo lineTo4 = new A.LineTo();
            A.Point point5 = new A.Point() { X = "0", Y = "0" };
            lineTo4.Append(point5);

            path1.Append(moveTo1);
            path1.Append(lineTo1);
            path1.Append(lineTo2);
            path1.Append(lineTo3);
            path1.Append(lineTo4);

            pathList1.Append(path1);

            customGeometry1.Append(adjustValueList1);
            customGeometry1.Append(rectangle1);
            customGeometry1.Append(pathList1);

            A.Outline outline1 = new A.Outline() { Width = thick, CapType = A.LineCapValues.Round };

            A.SolidFill solidFill1 = new A.SolidFill();

            A.RgbColorModelHex rgbColorModelHex1 = new A.RgbColorModelHex() { Val = colour };
            A.Alpha alpha1 = new A.Alpha() { Val = new Int32Value() { InnerText = "100%" } };

            rgbColorModelHex1.Append(alpha1);

            solidFill1.Append(rgbColorModelHex1);

            outline1.Append(solidFill1);

            shapeProperties1.Append(transform2D1);
            shapeProperties1.Append(customGeometry1);
            shapeProperties1.Append(outline1);

            Wps.ShapeStyle shapeStyle1 = new Wps.ShapeStyle();
            A.LineReference lineReference1 = new A.LineReference() { Index = (UInt32Value)0U };
            A.FillReference fillReference1 = new A.FillReference() { Index = (UInt32Value)0U };
            A.EffectReference effectReference1 = new A.EffectReference() { Index = (UInt32Value)0U };
            A.FontReference fontReference1 = new A.FontReference() { Index = A.FontCollectionIndexValues.Minor };

            shapeStyle1.Append(lineReference1);
            shapeStyle1.Append(fillReference1);
            shapeStyle1.Append(effectReference1);
            shapeStyle1.Append(fontReference1);
            Wps.TextBodyProperties textBodyProperties1 = new Wps.TextBodyProperties();

            wordprocessingShape1.Append(nonVisualDrawingProperties1);
            wordprocessingShape1.Append(nonVisualDrawingShapeProperties1);
            wordprocessingShape1.Append(shapeProperties1);
            wordprocessingShape1.Append(shapeStyle1);
            wordprocessingShape1.Append(textBodyProperties1);

            wordprocessingGroup1.Append(wordprocessingShape1);
        }

19 Source : AtomLabelRenderer.cs
with Apache License 2.0
from Chem4Word

private void DrawCharacterBox(Wpg.WordprocessingGroup wordprocessingGroup1, Rect extents, string colour, int thick)
        {
            UInt32Value bondLineId = UInt32Value.FromUInt32((uint)_ooxmlId++);
            string bondLineName = "char-diag-box-" + bondLineId;

            Int64Value width = (Int64Value)extents.Width;
            Int64Value height = (Int64Value)extents.Height;
            Int64Value top = (Int64Value)extents.Top;
            Int64Value left = (Int64Value)extents.Left;

            Wps.WordprocessingShape wordprocessingShape1 = new Wps.WordprocessingShape();
            Wps.NonVisualDrawingProperties nonVisualDrawingProperties1 = new Wps.NonVisualDrawingProperties()
            {
                Id = bondLineId,
                Name = bondLineName
            };
            Wps.NonVisualDrawingShapeProperties nonVisualDrawingShapeProperties1 = new Wps.NonVisualDrawingShapeProperties();

            Wps.ShapeProperties shapeProperties1 = new Wps.ShapeProperties();

            A.Transform2D transform2D1 = new A.Transform2D();
            A.Offset offset2 = new A.Offset() { X = left, Y = top };
            A.Extents extents2 = new A.Extents() { Cx = width, Cy = height };

            transform2D1.Append(offset2);
            transform2D1.Append(extents2);

            A.CustomGeometry customGeometry1 = new A.CustomGeometry();
            A.AdjustValueList adjustValueList1 = new A.AdjustValueList();
            A.Rectangle rectangle1 = new A.Rectangle() { Left = "l", Top = "t", Right = "r", Bottom = "b" };

            A.PathList pathList1 = new A.PathList();

            A.Path path1 = new A.Path() { Width = width, Height = height };

            // Starting Point
            A.MoveTo moveTo1 = new A.MoveTo();
            A.Point point1 = new A.Point() { X = "0", Y = "0" };
            moveTo1.Append(point1);

            // Mid Point
            A.LineTo lineTo1 = new A.LineTo();
            A.Point point2 = new A.Point() { X = extents.Width.ToString("0"), Y = "0" };
            lineTo1.Append(point2);

            // Mid Point
            A.LineTo lineTo2 = new A.LineTo();
            A.Point point3 = new A.Point() { X = extents.Width.ToString("0"), Y = extents.Height.ToString("0") };
            lineTo2.Append(point3);

            // Last Point
            A.LineTo lineTo3 = new A.LineTo();
            A.Point point4 = new A.Point() { X = "0", Y = extents.Height.ToString("0") };
            lineTo3.Append(point4);

            // Back to Start Point
            A.LineTo lineTo4 = new A.LineTo();
            A.Point point5 = new A.Point() { X = "0", Y = "0" };
            lineTo4.Append(point5);

            path1.Append(moveTo1);
            path1.Append(lineTo1);
            path1.Append(lineTo2);
            path1.Append(lineTo3);
            path1.Append(lineTo4);

            pathList1.Append(path1);

            customGeometry1.Append(adjustValueList1);
            customGeometry1.Append(rectangle1);
            customGeometry1.Append(pathList1);

            A.Outline outline1 = new A.Outline() { Width = thick, CapType = A.LineCapValues.Round };

            A.SolidFill solidFill1 = new A.SolidFill();

            A.RgbColorModelHex rgbColorModelHex1 = new A.RgbColorModelHex() { Val = colour };
            solidFill1.Append(rgbColorModelHex1);

            outline1.Append(solidFill1);

            shapeProperties1.Append(transform2D1);
            shapeProperties1.Append(customGeometry1);
            shapeProperties1.Append(outline1);

            Wps.ShapeStyle shapeStyle1 = new Wps.ShapeStyle();
            A.LineReference lineReference1 = new A.LineReference() { Index = (UInt32Value)0U };
            A.FillReference fillReference1 = new A.FillReference() { Index = (UInt32Value)0U };
            A.EffectReference effectReference1 = new A.EffectReference() { Index = (UInt32Value)0U };
            A.FontReference fontReference1 = new A.FontReference() { Index = A.FontCollectionIndexValues.Minor };

            shapeStyle1.Append(lineReference1);
            shapeStyle1.Append(fillReference1);
            shapeStyle1.Append(effectReference1);
            shapeStyle1.Append(fontReference1);
            Wps.TextBodyProperties textBodyProperties1 = new Wps.TextBodyProperties();

            wordprocessingShape1.Append(nonVisualDrawingProperties1);
            wordprocessingShape1.Append(nonVisualDrawingShapeProperties1);
            wordprocessingShape1.Append(shapeProperties1);
            wordprocessingShape1.Append(shapeStyle1);
            wordprocessingShape1.Append(textBodyProperties1);

            wordprocessingGroup1.Append(wordprocessingShape1);
        }

19 Source : SearchChEBI.cs
with Apache License 2.0
from Chem4Word

private void ImportStructure()
        {
            string module = $"{_product}.{_clreplaced}.{MethodBase.GetCurrentMethod().Name}()";

            if (_lastModel != null)
            {
                using (new WaitCursor())
                {
                    CMLConverter conv = new CMLConverter();

                    double before = _lastModel.MeanBondLength;
                    _lastModel.ScaleToAverageBondLength(Core.Helpers.Constants.StandardBondLength);
                    double after = _lastModel.MeanBondLength;
                    Telemetry.Write(module, "Information", $"Structure rescaled from {before.ToString("#0.00")} to {after.ToString("#0.00")}");
                    _lastModel.Relabel();

                    using (new WaitCursor())
                    {
                        _lastModel.Molecules[0].ChemicalNames.Clear();
                        if (_allResults.IupacNames != null)
                        {
                            foreach (var di in _allResults.IupacNames)
                            {
                                var cn = new Model.ChemicalName();
                                cn.Name = di.data;
                                cn.DictRef = "chebi:Iupac";
                                _lastModel.Molecules[0].ChemicalNames.Add(cn);
                            }
                        }
                        if (_allResults.Synonyms != null)
                        {
                            foreach (var di in _allResults.Synonyms)
                            {
                                var cn = new Model.ChemicalName();
                                cn.Name = di.data;
                                cn.DictRef = "chebi:Synonym";
                                _lastModel.Molecules[0].ChemicalNames.Add(cn);
                            }
                        }
                        Cml = conv.Export(_lastModel);
                    }
                }

            }
        }

19 Source : SafeDouble.cs
with Apache License 2.0
from Chem4Word

public static string replacedtring(double? source, string format)
        {
            string result = "{null}";

            if (source != null)
            {
                result = source.Value.ToString(format);
            }

            return result;
        }

19 Source : OoXmlRenderer.cs
with Apache License 2.0
from Chem4Word

public Run GenerateRun()
        {
            string module = $"{_product}.{_clreplaced}.{MethodBase.GetCurrentMethod().Name}()";
            _telemetry.Write(module, "Verbose", "Called");

            //start off progress monitoring
            Progress pb = new Progress();
            pb.TopLeft = _topLeft;

            //lists of objects for drawing
            _atomLabelCharacters = new List<AtomLabelCharacter>();
            _bondLines = new List<BondLine>();

            Stopwatch swr = new Stopwatch();
            Stopwatch sw = new Stopwatch();

            //Create a run
            Run run = new Run();

            sw.Start();
            swr.Start();

            //set the median bond length
            _medianBondLength = GeometryTool.GetMedianBondLength2D(_chemistryModel.AllBonds);

            int moleculeNo = 0;
            foreach (Molecule mol in _chemistryModel.Molecules)
            {
                moleculeNo++;
                // Step 1- gather the atom information together
                Debug.WriteLine($"{module} Starting Step 1");
                //_telemetry.Write(module, "Verbose", $"Starting Step 1 for molecule {moleculeNo}");

                ProcessAtoms(mol, pb, moleculeNo, _pt);

                Debug.WriteLine("Elapsed time " + sw.ElapsedMilliseconds.ToString("##,##0") + "ms");
                //_telemetry.Write(module, "Timing", $"Step 1 for molecule {moleculeNo} took " + sw.ElapsedMilliseconds.ToString("#,##0", CultureInfo.InvariantCulture) + "ms");
                sw.Reset();
                sw.Start();

                // Step 2- gather the bond information together

                Debug.WriteLine($"{module} Starting Step 2");
                //_telemetry.Write(module, "Verbose", $"Starting Step 2 for molecule {moleculeNo}");
                ProcessBonds(mol, pb, moleculeNo);

                Debug.WriteLine("Elapsed time " + sw.ElapsedMilliseconds.ToString("##,##0") + "ms");
                //_telemetry.Write(module, "Timing", $"Step 2 for molecule {moleculeNo} took " + sw.ElapsedMilliseconds.ToString("#,##0", CultureInfo.InvariantCulture) + "ms");
                sw.Reset();
                sw.Start();

                if (_options.ShowRingCentres)
                {
                    // Save Rings for later
                    foreach (Ring ring in mol.Rings)
                    {
                        _rings.Add(ring.UniqueID, ring);
                    }
                }
            }

            Debug.WriteLine($"{module} Starting Step 3");
            //_telemetry.Write(module, "Verbose", "Starting Step 3");

            IncreaseCanvreplacedize();

            Debug.WriteLine("Elapsed time " + sw.ElapsedMilliseconds.ToString("##,##0") + "ms");
            //_telemetry.Write(module, "Timing", "Step 3 took " + sw.ElapsedMilliseconds.ToString("#,##0", CultureInfo.InvariantCulture) + "ms");
            sw.Reset();
            sw.Start();

            if (_options.ClipLines)
            {
                Debug.WriteLine($"{module} Starting Step 4");
                //_telemetry.Write(module, "Verbose", "Starting Step 4");

                #region Step 4 - Shrink bond lines

                ShrinkBondLinesPreplaced1(pb);
                ShrinkBondLinesPreplaced2(pb);

                #endregion Step 4 - Shrink bond lines

                Debug.WriteLine("Elapsed time " + sw.ElapsedMilliseconds.ToString("##,##0") + "ms");
                //_telemetry.Write(module, "Timing", "Step 4 took " + sw.ElapsedMilliseconds.ToString("#,##0", CultureInfo.InvariantCulture) + "ms");
                sw.Reset();
                sw.Start();
            }

            Debug.WriteLine($"{module} Starting Step 5");
            //_telemetry.Write(module, "Verbose", "Starting Step 5");

            #region Step 5 - Create main OoXml drawing objects

            Drawing drawing1 = new Drawing();
            A.Graphic graphic1 = CreateGraphic();
            A.GraphicData graphicData1 = CreateGraphicData();
            Wpg.WordprocessingGroup wordprocessingGroup1 = new Wpg.WordprocessingGroup();

            // Create Inline Drawing using canvas extents
            Wp.Inline inline1 = CreateInline(graphicData1, wordprocessingGroup1);

            #endregion Step 5 - Create main OoXml drawing objects

            Debug.WriteLine("Elapsed time " + sw.ElapsedMilliseconds.ToString("##,##0") + "ms");
            //_telemetry.Write(module, "Timing", "Step 5 took " + sw.ElapsedMilliseconds.ToString("#,##0", CultureInfo.InvariantCulture) + "ms");
            sw.Reset();
            sw.Start();

            #region Step 5a - Diagnostics

            if (_options.ShowMoleculeBoundingBoxes)
            {
                DrawBox(wordprocessingGroup1, _modelExtents, "00ff00", 1);
                foreach (Molecule mol in _chemistryModel.Molecules)
                {
                    DrawBox(wordprocessingGroup1, mol.BoundingBox, "0000ff", 1);
                    DrawBox(wordprocessingGroup1, MoleculeExtents(mol), "ff0000", 1);
                }
                DrawBox(wordprocessingGroup1, _canvasExtents, "000000", 1);
            }

            if (_options.ShowRingCentres)
            {
                ShowRingCentres(wordprocessingGroup1);
            }

            if (_options.ShowAtomPositions)
            {
                ShowAtomCentres(wordprocessingGroup1);
            }

            if (_options.ShowHulls)
            {
                ShowConvexHulls(wordprocessingGroup1);
            }

            #endregion Step 5a - Diagnostics

            Debug.WriteLine($"{module} Starting Step 6");
            //_telemetry.Write(module, "Verbose", "Starting Step 6");

            #region Step 6 - Create and append OoXml objects for all Bond Lines

            AppendBondOoxml(pb, wordprocessingGroup1);

            #endregion Step 6 - Create and append OoXml objects for all Bond Lines

            Debug.WriteLine("Elapsed time " + sw.ElapsedMilliseconds.ToString("##,##0") + "ms");
            //_telemetry.Write(module, "Timing", "Step 6 took " + sw.ElapsedMilliseconds.ToString("#,##0", CultureInfo.InvariantCulture) + "ms");
            sw.Reset();
            sw.Start();

            Debug.WriteLine($"{module} Starting Step 7");
            //_telemetry.Write(module, "Verbose", "Starting Step 7");

            #region Step 7 - Create and append OoXml objects for Atom Labels

            AppendAtomLabelOoxml(pb, wordprocessingGroup1);

            #endregion Step 7 - Create and append OoXml objects for Atom Labels

            Debug.WriteLine("Elapsed time " + sw.ElapsedMilliseconds.ToString("##,##0") + "ms");
            //_telemetry.Write(module, "Timing", "Step 7 took " + sw.ElapsedMilliseconds.ToString("#,##0", CultureInfo.InvariantCulture) + "ms");
            sw.Reset();
            sw.Start();

            Debug.WriteLine($"{module} Starting Step 8");
            //_telemetry.Write(module, "Verbose", "Starting Step 8");

            #region Step 8 - Append OoXml drawing objects to OoXml run object

            AppendAllOoXml(graphicData1, wordprocessingGroup1, graphic1, inline1, drawing1, run);

            #endregion Step 8 - Append OoXml drawing objects to OoXml run object

            Debug.WriteLine("Elapsed time " + sw.ElapsedMilliseconds.ToString("##,##0") + "ms");
            //_telemetry.Write(module, "Timing", "Step 8 took " + sw.ElapsedMilliseconds.ToString("#,##0", CultureInfo.InvariantCulture) + "ms");
            sw.Reset();
            sw.Start();

            double abl = _chemistryModel.MeanBondLength;
            Debug.WriteLine("Elapsed time for GenerateRun " + swr.ElapsedMilliseconds.ToString("#,##0", CultureInfo.InvariantCulture) + "ms");
            _telemetry.Write(module, "Timing", $"Rendering {_chemistryModel.Molecules.Count} molecules with {_chemistryModel.AllAtoms.Count} atoms and {_chemistryModel.AllBonds.Count} bonds took {swr.ElapsedMilliseconds.ToString("##,##0")} ms; Average Bond Length: {abl.ToString("#0.00")}");

            ShutDownProgress(pb);

            return run;
        }

19 Source : WpfChemDoodle.xaml.cs
with Apache License 2.0
from Chem4Word

private void SetupControls()
        {
            string module = $"{_product}.{_clreplaced}.{MethodBase.GetCurrentMethod().Name}()";

            ShowHydrogens.IsChecked = UserOptions.ShowHydrogens;
            ShowColour.IsChecked = UserOptions.ColouredAtoms;
            ShowCarbons.IsChecked = UserOptions.ShowCarbons;

            if (AverageBondLength < Constants.MinimumBondLength - Constants.BondLengthTolerance
                || AverageBondLength > Constants.MaximumBondLength + Constants.BondLengthTolerance)
            {
                BondLength.Text = UserOptions.BondLength.ToString("0");
                AverageBondLength = UserOptions.BondLength;
            }
            else
            {
                AverageBondLength = Math.Round(AverageBondLength / 5.0) * 5;
                BondLength.Text = AverageBondLength.ToString("0");
            }

            if (IsSingleMolecule)
            {
                SwitchToSingle.IsChecked = true;
                SwitchToMulti.IsChecked = false;
            }
            else
            {
                SwitchToMulti.IsChecked = true;
                SwitchToSingle.IsChecked = false;
            }
        }

19 Source : SearchChEBI.cs
with Apache License 2.0
from Chem4Word

private void ImportStructure()
        {
            string module = $"{_product}.{_clreplaced}.{MethodBase.GetCurrentMethod().Name}()";

            if (_lastModel != null)
            {
                using (new WaitCursor())
                {
                    CMLConverter conv = new CMLConverter();

                    double before = _lastModel.MeanBondLength;
                    _lastModel.ScaleToAverageBondLength(Core.Helpers.Constants.StandardBondLength);
                    double after = _lastModel.MeanBondLength;
                    Telemetry.Write(module, "Information", $"Structure rescaled from {before.ToString("#0.00")} to {after.ToString("#0.00")}");
                    _lastModel.Relabel(true);
                    var expModel = _lastModel;

                    using (new WaitCursor())
                    {
                        if (expModel.Molecules.Values.Any())
                        {
                            var mol = expModel.Molecules.Values.First();

                            mol.Names.Clear();

                            if (_allResults.IupacNames != null)
                            {
                                foreach (var di in _allResults.IupacNames)
                                {
                                    var cn = new TextualProperty();
                                    cn.Value = di.data;
                                    cn.FullType = "chebi:Iupac";
                                    mol.Names.Add(cn);
                                }
                            }

                            if (_allResults.Synonyms != null)
                            {
                                foreach (var di in _allResults.Synonyms)
                                {
                                    var cn = new TextualProperty();
                                    cn.Value = di.data;
                                    cn.FullType = "chebi:Synonym";
                                    mol.Names.Add(cn);
                                }
                            }

                            Cml = conv.Export(expModel);
                        }
                    }
                }
            }
        }

19 Source : MainForm.cs
with Apache License 2.0
from Chem4Word

private void SaveStructure_Click(object sender, EventArgs e)
        {
            string module = $"{_product}.{_clreplaced}.{MethodBase.GetCurrentMethod().Name}()";
            try
            {
                CMLConverter cmlConverter = new CMLConverter();
                Model m = cmlConverter.Import(_lastCml);
                m.CustomXmlPartGuid = "";

                string filter = "CML molecule files (*.cml, *.xml)|*.cml;*.xml|MDL molecule files (*.mol, *.sdf)|*.mol;*.sdf";
                using (SaveFileDialog sfd = new SaveFileDialog { Filter = filter })
                {
                    DialogResult dr = sfd.ShowDialog();
                    if (dr == DialogResult.OK)
                    {
                        FileInfo fi = new FileInfo(sfd.FileName);
                        _telemetry.Write(module, "Information", $"Exporting to '{fi.Name}'");
                        string fileType = Path.GetExtension(sfd.FileName).ToLower();
                        switch (fileType)
                        {
                            case ".cml":
                            case ".xml":
                                string temp = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                                              + Environment.NewLine
                                              + cmlConverter.Export(m);
                                File.WriteAllText(sfd.FileName, temp);
                                break;

                            case ".mol":
                            case ".sdf":
                                // https://www.chemaxon.com/marvin-archive/6.0.2/marvin/help/formats/mol-csmol-doc.html
                                double before = m.MeanBondLength;
                                // Set bond length to 1.54 angstroms (Å)
                                m.ScaleToAverageBondLength(1.54);
                                double after = m.MeanBondLength;
                                _telemetry.Write(module, "Information", $"Structure rescaled from {before.ToString("#0.00")} to {after.ToString("#0.00")}");
                                SdFileConverter converter = new SdFileConverter();
                                File.WriteAllText(sfd.FileName, converter.Export(m));
                                break;
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                _telemetry.Write(module, "Exception", $"Exception: {exception.Message}");
                _telemetry.Write(module, "Exception(Data)", $"Exception: {exception}");
                MessageBox.Show(exception.StackTrace, exception.Message);
            }
        }

19 Source : Downloader.cs
with GNU General Public License v2.0
from CHKZL

public static string 转换下载大小数据格式(double size)
        {
            if (size < 0) {
                return "未知";
            }
            if (size <= 1024)
            {
                return size.ToString("F2") + "B";
            }
            if (size <= 1048576)
            {
                return (size / 1024.0).ToString("F2") + "KB";
            }
            if (size <= 1073741824)
            {
                return (size / 1048576.0).ToString("F2") + "MB";
            }
            if (size <= 1099511627776)
            {
                return (size / 1073741824.0).ToString("F2") + "GB";
            }
            return (size / 1099511627776.0).ToString("F2") + "TB";
        }

19 Source : update.cs
with GNU General Public License v2.0
from CHKZL

public static string CountSize(long Size)
        {
            string m_strSize = "";
            long FactSize = 0;
            FactSize = Size;
            if (FactSize < 1024.00)
                m_strSize = FactSize.ToString("F2") + " Byte";
            else if (FactSize >= 1024.00 && FactSize < 1048576)
                m_strSize = (FactSize / 1024.00).ToString("F2") + " K";
            else if (FactSize >= 1048576 && FactSize < 1073741824)
                m_strSize = (FactSize / 1024.00 / 1024.00).ToString("F2") + " M";
            else if (FactSize >= 1073741824)
                m_strSize = (FactSize / 1024.00 / 1024.00 / 1024.00).ToString("F2") + " G";
            return m_strSize;
        }

19 Source : MMPU.cs
with GNU General Public License v3.0
from CHKZL

private static string FormatSize(long size)
        {
            if (size <= 1024)
            {
                return size.ToString("F2") + "B";
            }
            if (size <= 1048576)
            {
                return (size / 1024.0).ToString("F2") + "KB";
            }
            if (size <= 1073741824)
            {
                return (size / 1048576.0).ToString("F2") + "MB";
            }
            if (size <= 1099511627776)
            {
                return (size / 1073741824.0).ToString("F2") + "GB";
            }
            return (size / 1099511627776.0).ToString("F2") + "TB";
        }

19 Source : Range.cs
with MIT License
from chstetco

public string ToString(string format)
        {
            return UnityString.Format("({0}, {1})", start.ToString(format), end.ToString(format));
        }

19 Source : TimeUtility.cs
with MIT License
from chstetco

public static string TimeAsFrames(double timeValue, double frameRate, string format = "F2")
        {
            if (OnFrameBoundary(timeValue, frameRate)) // make integral values when on time borders
                return ToFrames(timeValue, frameRate).ToString();
            return ToExactFrames(timeValue, frameRate).ToString(format);
        }

19 Source : TimeUtility.cs
with MIT License
from chstetco

public static string TimeAsTimeCode(double timeValue, double frameRate, string format = "F2")
        {
            ValidateFrameRate(frameRate);

            int intTime = (int)Math.Abs(timeValue);

            int hours = intTime / 3600;
            int minutes = (intTime % 3600) / 60;
            int seconds = intTime % 60;

            string result;
            string sign = timeValue < 0 ? "-" : string.Empty;
            if (hours > 0)
                result = hours + ":" + minutes.ToString("D2") + ":" + seconds.ToString("D2");
            else if (minutes > 0)
                result = minutes + ":" + seconds.ToString("D2");
            else
                result = seconds.ToString();

            int frameDigits = (int)Math.Floor(Math.Log10(frameRate) + 1);

            // Add partial digits on the frame if needed.
            // we are testing the original value (not the truncated), because the truncation can cause rounding errors leading
            // to invalid strings for items on frame boundaries
            string frames = (ToFrames(timeValue, frameRate) - ToFrames(intTime, frameRate)).ToString().PadLeft(frameDigits, '0');
            if (!OnFrameBoundary(timeValue, frameRate))
            {
                string decimals = ToExactFrames(timeValue, frameRate).ToString(format);
                int decPlace = decimals.IndexOf('.');
                if (decPlace >= 0)
                    frames += " [" + decimals.Substring(decPlace) + "]";
            }

            return sign + result + ":" + frames;
        }

19 Source : Extensions.cs
with MIT License
from circles-arrows

public static string ToSize(this Int64 value, SizeUnits unit)
        {
            return (value / (double)Math.Pow(1024, (Int64)unit)).ToString("0.0");
        }

19 Source : FieldView.cs
with MIT License
from Coac

public static double displayDouble(double doubl)
    {
        return double.Parse(GUILayout.TextField(doubl.ToString(format)));
    }

19 Source : AstarProfiler.cs
with GNU General Public License v3.0
from coconauts

[System.Diagnostics.Conditional ("ProfileAstar")]
		public static void PrintFastResults()
		{
			
			StartFastProfile (fastProfiles.Length-2);
			for (int i=0;i<1000;i++) {
				StartFastProfile (fastProfiles.Length-1);
				EndFastProfile (fastProfiles.Length-1);
			}
			EndFastProfile (fastProfiles.Length-2);
			
			double avgOverhead = fastProfiles[fastProfiles.Length-2].watch.Elapsed.TotalMilliseconds / 1000.0;
			
			TimeSpan endTime = DateTime.UtcNow - startTime;
			System.Text.StringBuilder output = new System.Text.StringBuilder();
			output.Append("============================\n\t\t\t\tProfile results:\n============================\n");
			output.Append ("Name		|	Total Time	|	Total Calls	|	Avg/Call	|	Bytes");
			//foreach(KeyValuePair<string, ProfilePoint> pair in profiles)
			for (int i=0;i<fastProfiles.Length;i++)
			{
				string name = fastProfileNames[i];
				ProfilePoint value = fastProfiles[i];
				
				int totalCalls = value.totalCalls;
				double totalTime = value.watch.Elapsed.TotalMilliseconds - avgOverhead*totalCalls;
				
				if (totalCalls < 1) continue;
				
				
				output.Append ("\n").Append(name.PadLeft(10)).Append("|   ");
				output.Append (totalTime.ToString("0.0 ").PadLeft (10)).Append(value.watch.Elapsed.TotalMilliseconds.ToString("(0.0)").PadLeft(10)).Append ("|   ");
				output.Append (totalCalls.ToString().PadLeft (10)).Append ("|   ");
				output.Append ((totalTime / totalCalls).ToString("0.000").PadLeft(10));
				
				
				/* output.Append("\nProfile");
				output.Append(name);
				output.Append(" took \t");
				output.Append(totalTime.ToString("0.0"));
				output.Append(" ms to complete over ");
				output.Append(totalCalls);
				output.Append(" iteration");
				if (totalCalls != 1) output.Append("s");
				output.Append(", averaging \t");
				output.Append((totalTime / totalCalls).ToString("0.000"));
				output.Append(" ms per call"); */
				
			}
			output.Append("\n\n============================\n\t\tTotal runtime: ");
			output.Append(endTime.TotalSeconds.ToString("F3"));
			output.Append(" seconds\n============================");
			Debug.Log(output.ToString());
		}

19 Source : AstarProfiler.cs
with GNU General Public License v3.0
from coconauts

[System.Diagnostics.Conditional ("ProfileAstar")]
		public static void PrintResults()
		{
			TimeSpan endTime = DateTime.UtcNow - startTime;
			System.Text.StringBuilder output = new System.Text.StringBuilder();
			output.Append("============================\n\t\t\t\tProfile results:\n============================\n");
			
			int maxLength = 5;
			foreach(KeyValuePair<string, ProfilePoint> pair in profiles)
			{
				maxLength = Math.Max (pair.Key.Length,maxLength);
			}
			
			output.Append (" Name ".PadRight (maxLength)).
				Append("|").Append(" Total Time	".PadRight(20)).
				Append("|").Append(" Total Calls ".PadRight(20)).
				Append("|").Append(" Avg/Call ".PadRight(20));
			
			
			
			foreach(KeyValuePair<string, ProfilePoint> pair in profiles)
			{
				double totalTime = pair.Value.watch.Elapsed.TotalMilliseconds;
				int totalCalls = pair.Value.totalCalls;
				if (totalCalls < 1) continue;
				
				string name = pair.Key;
				
				output.Append ("\n").Append(name.PadRight(maxLength)).Append("| ");
				output.Append (totalTime.ToString("0.0").PadRight (20)).Append ("| ");
				output.Append (totalCalls.ToString().PadRight (20)).Append ("| ");
				output.Append ((totalTime / totalCalls).ToString("0.000").PadRight(20));
				output.Append (Pathfinding.AstarMath.FormatBytesBinary ((int)pair.Value.totalBytes).PadLeft(10));
				
				/*output.Append("\nProfile ");
				output.Append(pair.Key);
				output.Append(" took ");
				output.Append(totalTime.ToString("0"));
				output.Append(" ms to complete over ");
				output.Append(totalCalls);
				output.Append(" iteration");
				if (totalCalls != 1) output.Append("s");
				output.Append(", averaging ");
				output.Append((totalTime / totalCalls).ToString("0.0"));
				output.Append(" ms per call");*/
			}
			output.Append("\n\n============================\n\t\tTotal runtime: ");
			output.Append(endTime.TotalSeconds.ToString("F3"));
			output.Append(" seconds\n============================");
			Debug.Log(output.ToString());
		}

19 Source : ProfileHelper.cs
with GNU General Public License v3.0
from coconauts

public override string ToString () {
			string s = name + " #" + counter + " " + w.Elapsed.TotalMilliseconds.ToString("0.0 ms") + " avg: " + (w.Elapsed.TotalMilliseconds/counter).ToString("0.00 ms");
			if (PROFILE_MEM) {
				s += " avg mem: " + (mem/(1.0*counter)).ToString("0 bytes");
			}
			return s;
		}

19 Source : MainWindow.xaml.cs
with GNU General Public License v3.0
from CodeDead

private void RamClearingCompleted()
        {
            double ramSavings = _ramController.RamSavings / 1024 / 1024;
            string message;
            if (ramSavings < 0)
            {
                ramSavings = Math.Abs(ramSavings);
                _logController.AddLog(new RamLog("RAM usage increase: " + ramSavings.ToString("F2") + " MB"));
                message = ((string)Application.Current.FindResource("RamUsageIncreased"))?.Replace("%", ramSavings.ToString("F2"));
            }
            else
            {
                _logController.AddLog(new RamLog("RAM usage decrease: " + ramSavings.ToString("F2") + " MB"));
                message = ((string)Application.Current.FindResource("RamUsageSaved"))?.Replace("%", ramSavings.ToString("F2"));
            }

            try
            {
                if (!Properties.Settings.Default.RamCleaningMessage) return;
                // ReSharper disable once SwitchStatementMissingSomeCases
                switch (Visibility)
                {
                    default:
                        MessageBox.Show(message, "MemPlus", MessageBoxButton.OK, MessageBoxImage.Information);
                        break;
                    case Visibility.Hidden when TbiIcon.Visibility == Visibility.Visible:
                        TbiIcon.ShowBalloonTip("MemPlus", message, BalloonIcon.Info);
                        break;
                }
            }
            catch (Exception ex)
            {
                _logController.AddLog(new ErrorLog(ex.Message));
                MessageBox.Show(ex.Message, "MemPlus", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

19 Source : PythonAstPrinter.cs
with MIT License
from CoderNate

public string Visit(PyAst.ConstantExpression node) {
            string formatString(string rawString) {
                foreach (var charToEscape in charsToEscape) {
                    if (rawString.Contains(charToEscape)) {
                        rawString = rawString.Replace(charToEscape, "\\" + charToEscape);
                    }
                }
                return $"\"{ rawString }\"";
            }
            switch (node.Value) {
                case double val:
                    if (Math.Truncate(val) == val) {
                        // If we don't do this, the double value 1.0 will be output as integer 1
                        return val.ToString("0.0");
                    }
                    return node.Value.ToString();
                case char val:
                    return formatString(val.ToString());
                case string val:
                    return formatString(val);
                case int val:
                    return node.Value.ToString();
                case bool val:
                    return val ? "True" : "False";
                case null:
                    return "None";
                default:
                    throw new NotImplementedException($"Printing of constant expression {node.Value.GetType()} not implemented");
            }
        }

19 Source : BigNumberFormatter.cs
with Apache License 2.0
from coryleach

private static string InternalFormat(double arg)
    {

      int significantDigits = (int)(Math.Log10(arg) + 1);

      //Number of commas is number of digits divided by 3 and minus 1. 
      int commas = (significantDigits / 3) - 1;

      var formatBuilder = new StringBuilder();
      formatBuilder.Append("#");
      if (commas > 0)
      {
        //Add a comma to format to skip 3 number digits
        //Subtract 1 because we want to show the digits past one comma
        for (int i = 0; i < commas; i++)
        {
          formatBuilder.Append(",");
        }

        int index = commas;
        if ( index > 0 && index <= specialSymbols.Length )
        {
          formatBuilder.Append(specialSymbols[index - 1]);
        }
        else
        {
          //Number of special symbols needs to be subtracted so we don't
          //skip symbols
          index -= specialSymbols.Length;

          string symbol = string.Empty;

          while (index > 0)
          {

            var symbolIndex = (index - 1) % symbols.Length;

            symbol = symbols[symbolIndex] + symbol;

            index = (index - 1) / symbols.Length;

          }

          formatBuilder.Append(symbol);

        }

      }

      return arg.ToString(formatBuilder.ToString());

    }

19 Source : System_Double_Binding.cs
with MIT License
from CragonGame

static StackObject* ToString_17(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject* ptr_of_this_method;
            StackObject* __ret = ILIntepreter.Minus(__esp, 2);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.String @format = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Double instance_of_this_method = GetInstance(__domain, ptr_of_this_method, __mStack);

            var result_of_this_method = instance_of_this_method.ToString(@format);

            return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
        }

19 Source : ChartAxisLabel.cs
with MIT License
from craigbridges

private string GetDoubleString()
        {
            var format = this.DoubleFormat;
            var rounding = this.RoundingPlaces;
            var value = this.DoubleValue;

            value = Math.Round
            (
                value,
                rounding
            );

            if (String.IsNullOrEmpty(format))
            {
                return value.ToString();
            }
            else
            {
                return value.ToString
                (
                    format
                );
            }
        }

19 Source : SongDBUpdate.cs
with GNU General Public License v2.0
from CrazyKTV

private void SongDBUpdate_CheckDatabaseVersion()
        {
            bool UpdateDBStatus = false;
            double SongDBVer = Convert.ToDouble(Global.CrazyktvSongDBVer);
            string CashboxUpdDate = "";

            string VersionQuerySqlStr = "select * from ktv_Version";
            using (DataTable dt = CommonFunc.GetOleDbDataTable(Global.CrazyktvSongMgrDatabaseFile, VersionQuerySqlStr, ""))
            {
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        CashboxUpdDate = row["CashboxUpdDate"].ToString();
                    }
                    Global.CashboxUpdDate = DateTime.Parse(CashboxUpdDate);

                    this.BeginInvoke((Action)delegate()
                    {
                        SongMaintenance_DBVer1Value_Label.Text = SongDBVer.ToString("F2") + " 版";
                        Cashbox_UpdDateValue_Label.Text = (CultureInfo.CurrentCulture.Name == "zh-TW") ? DateTime.Parse(CashboxUpdDate).ToLongDateString() : DateTime.Parse(CashboxUpdDate).ToShortDateString();
                    });

                    if (Global.DBVerEnableDBVerUpdate == "True")
                    {
                        if (!Directory.Exists(Application.StartupPath + @"\SongMgr\Update")) Directory.CreateDirectory(Application.StartupPath + @"\SongMgr\Update");
                        
                        string url = "https://raw.githubusercontent.com/CrazyKTV/SongMgr/master/CrazyKTV_SongMgr/SongMgr/Update/UpdateDB.xml";
                        using (MemoryStream ms = CommonFunc.Download(url))
                        {
                            if (ms.Length > 0)
                            {
                                ms.Position = 0;
                                Global.CrazyktvSongDBVer = CommonFunc.LoadConfigXmlFile("", "SongDBVer", ms, true);

                                if (File.Exists(Global.CrazyktvDatabaseFile))
                                {
                                    if (Convert.ToDouble(Global.CrazyktvSongDBVer) > SongDBVer)
                                    {
                                        this.BeginInvoke((Action)delegate ()
                                        {
                                            if (MessageBox.Show("你確定要更新歌庫版本嗎?", "偵測到歌庫版本更新", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                                            {
                                                Global.SongMgrDBVerErrorUIStatus = false;
                                                MainTabControl.SelectedIndex = MainTabControl.TabPages.IndexOf(SongMaintenance_TabPage);
                                                SongMaintenance_TabControl.SelectedIndex = SongMaintenance_TabControl.TabPages.IndexOf(SongMaintenance_DBVer_TabPage);
                                                SongMaintenance_DBVerTooltip_Label.Text = "開始進行歌庫版本更新...";
                                                UpdateDBStatus = true;
                                                var UpdateDBTask = Task.Factory.StartNew(() => SongDBUpdate_UpdateDatabaseFile());
                                            }
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
                if (!UpdateDBStatus) SongDBUpdate_UpdateFinish();
            }
        }

19 Source : AccumulationBot.cs
with MIT License
from Crynners

public async Task Tick()
        {

            try
            {

                StringBuilder sbInformationMessage = new StringBuilder();
                Log.LogInformation("Start Tick: " + DateTime.Now);

                if (cryptoExchangeAPI == null)
                {
                    inicializeAPI();
                }

                var pair = $"{BotConfiguration.Currency}_{BotConfiguration.Fiat}";

                var initBalance = await cryptoExchangeAPI.getBalancesAsync();

                double FiatBalance = initBalance.Where(x => x.currency == BotConfiguration.Fiat).Sum(x => x.available);


                Dictionary<string, StringBuilder> sb_actions = new Dictionary<string, StringBuilder>();


                if (FiatBalance > BotConfiguration.ChunkSize)
                {
                    var response = await cryptoExchangeAPI.buyOrderAsync(BotConfiguration.ChunkSize);

                    Log.LogInformation($"Market buy {BotConfiguration.Currency} for {BotConfiguration.ChunkSize} {BotConfiguration.Fiat}");
                }
                else
                {
                    await SendMessageAsync($"Not enough money ({FiatBalance} {BotConfiguration.Fiat})", MessageTypeEnum.Warning);
                    return;
                }
      

                var afterBalance = await cryptoExchangeAPI.getBalancesAsync();
                double FiatAfterBuy = afterBalance.Where(x => x.currency == BotConfiguration.Fiat).Sum(x => x.available);

                double withdrawFee = await cryptoExchangeAPI.getWithdrawalFeeAsync();


                double available = afterBalance.Where(x => x.currency == BotConfiguration.Currency).Sum(x => x.available);
                double init = initBalance.Where(x => x.currency == BotConfiguration.Currency).Sum(x => x.available);

                double fee_cost = (withdrawFee / available);


                double TAKER_FEE = await cryptoExchangeAPI.getTakerFee();

                double buyPrice = ((FiatBalance - FiatAfterBuy) / TAKER_FEE) / (available - init);

                var feeInFiat = (withdrawFee * buyPrice).ToString("N2");

                var currentCryptoBalance = afterBalance.Where(x => x.currency == BotConfiguration.Currency).Sum(x => x.available);
                var currentCryptoBalanceInFiat = currentCryptoBalance * buyPrice;

                sbInformationMessage.Append("<b>Acreplacedulation:</b> " + (available - init).ToString("N8") + " " + BotConfiguration.Currency + " for " + BotConfiguration.ChunkSize.ToString("N2") + $" {BotConfiguration.Fiat} @ " + (buyPrice).ToString("N2") + $" {BotConfiguration.Fiat}").Append("\r\n");

                //Send them home
                if (BotConfiguration.WithdrawalEnabled && 
                    !String.IsNullOrEmpty(BotConfiguration.WithdrawalAddress) &&
                    fee_cost <= BotConfiguration.MaxWithdrawalPercentageFee &&
                    (BotConfiguration.MaxWithdrawalAbsoluteFee == -1 || (withdrawFee * buyPrice) <= BotConfiguration.MaxWithdrawalAbsoluteFee)
                    )
                {
                    var withdrawResult = await cryptoExchangeAPI.withdrawAsync(available, BotConfiguration.WithdrawalAddress);

                    if(withdrawResult == WithdrawalStateEnum.OK)
                    {
                        sbInformationMessage.Append("<b>Withdrawal:</b> " + available.ToString("N8") + " " + BotConfiguration.Currency + " to " + BotConfiguration.WithdrawalAddress + " with " + (fee_cost * 100).ToString("N2") + " % fee").Append("\r\n");
                    }else if(withdrawResult == WithdrawalStateEnum.InsufficientKeyPrivilages){
                        sbInformationMessage.Append($"<b>Withdrawal:</b>❌ Insufficient Key Privilages.").Append("\r\n");
                    }

                }
                else
                {
                    List<string> reason = new List<string>();
                    if (fee_cost > BotConfiguration.MaxWithdrawalPercentageFee)
                        reason.Add("Limit exceeded");
                    if (String.IsNullOrEmpty(BotConfiguration.WithdrawalAddress))
                        reason.Add("No address");
                    if (!BotConfiguration.WithdrawalEnabled)
                        reason.Add("Turned off");

                    var maxWithdrawalFeeInFiat = (BotConfiguration.MaxWithdrawalPercentageFee * currentCryptoBalanceInFiat).ToString("N2");

                    List<string> limits = new List<string>
                    {
                        $"{(BotConfiguration.MaxWithdrawalPercentageFee * 100).ToString("N2")} % ({maxWithdrawalFeeInFiat} {BotConfiguration.Fiat})"
                    };

                    if (BotConfiguration.MaxWithdrawalAbsoluteFee != -1)
                    {
                        limits.Add($"{BotConfiguration.MaxWithdrawalAbsoluteFee.ToString("N2")} {BotConfiguration.Fiat}");
                    }
                    

                    sbInformationMessage.Append($"<b>Withdrawal:</b> Denied - [{String.Join(", ", reason)}] - fee cost {(fee_cost * 100).ToString("N2")} % ({feeInFiat} {BotConfiguration.Fiat}), limit " + 
                        String.Join(" AND ", limits)).Append("\r\n");
                }

                _cosmosDbContext = new CosmosDbContext();

                var acreplacedulationSummary = await _cosmosDbContext.GetAcreplacedulationSummary(pair);

                AcreplacedulationSummary accSumOLD = null;

                //Update a CosmosDB record to the new ParreplacedionKey structure
                if (acreplacedulationSummary.Buys == 0)
                {
                    accSumOLD = await _cosmosDbContext.GetAcreplacedulationSummary(BotConfiguration.Currency);
                    acreplacedulationSummary.AcreplacedulatedCryptoAmount = accSumOLD.AcreplacedulatedCryptoAmount;
                    acreplacedulationSummary.Buys = accSumOLD.Buys;
                    acreplacedulationSummary.InvestedFiatAmount = accSumOLD.InvestedFiatAmount;
                }

                
                acreplacedulationSummary.Buys += 1;
                acreplacedulationSummary.InvestedFiatAmount += (FiatBalance - FiatAfterBuy);
                acreplacedulationSummary.AcreplacedulatedCryptoAmount += (available - init);

                await _cosmosDbContext.UpdateItemAsync(acreplacedulationSummary);

                if(accSumOLD != null)
                {
                    //Deleting an old record from a previous version of the bot
                    await _cosmosDbContext.DeleteItemAsync(accSumOLD.Id.ToString(), accSumOLD.CryptoName);
                }


                var profit = ((acreplacedulationSummary.AcreplacedulatedCryptoAmount * buyPrice) / acreplacedulationSummary.InvestedFiatAmount) - 1;

                StringBuilder sb = new StringBuilder();
                sb.Append("🛒 <b>[ACTIONS]</b>").Append("\r\n");
                sb.Append(sbInformationMessage.ToString());
                sb.Append("").Append("\r\n");
                sb.Append("ℹ️ <b>[SUMMARY]</b>").Append("\r\n");
                sb.Append("<b>Total acreplacedulation</b>: " + acreplacedulationSummary.AcreplacedulatedCryptoAmount.ToString("N8") + " " + BotConfiguration.Currency + " (" + acreplacedulationSummary.InvestedFiatAmount.ToString("N2") + $" {BotConfiguration.Fiat})").Append("\r\n");
                sb.Append("<b>Avg Acreplacedulated Price</b>: " + (acreplacedulationSummary.InvestedFiatAmount/acreplacedulationSummary.AcreplacedulatedCryptoAmount).ToString("N2") + $" {BotConfiguration.Fiat}/" + BotConfiguration.Currency).Append("\r\n");
                sb.Append("<b>Current Price</b>: " + buyPrice.ToString("N2") + $" {BotConfiguration.Fiat}/" + BotConfiguration.Currency).Append("\r\n");
                sb.Append("<b>Current Profit</b>: " + (profit * 100).ToString("N2") + " % (" + (profit * acreplacedulationSummary.InvestedFiatAmount).ToString("N2") + $" {BotConfiguration.Fiat})").Append("\r\n");

                sb.Append("<b>Fiat balance</b>: " + FiatAfterBuy.ToString("N2") + $" {BotConfiguration.Fiat}").Append("\r\n");
                sb.Append($"<b>Current balance</b>: {currentCryptoBalance.ToString("N8")} {BotConfiguration.Currency} ({currentCryptoBalanceInFiat.ToString("N2")} {BotConfiguration.Fiat})").Append("\r\n");

                await SendMessageAsync(sb.ToString());
            }
            catch (Exception ex)
            {
                await SendMessageAsync(ex.ToString(), MessageTypeEnum.Error);
                return;
            }

        }

19 Source : StringExtensions.cs
with Apache License 2.0
from cs-util-com

public static string ByteSizeToReadableString(long value) {
            if (value == 0) { return "0 Bytes"; }
            for (int t = thresholds.Length - 1; t > 0; t--) {
                if (value >= thresholds[t].Key) {
                    return ((double)value / thresholds[t].Key).ToString("0.00") + thresholds[t].Value;
                }
            }
            return "-" + ByteSizeToReadableString(-value); // negative bytes (common case optimised to the end of this routine)
        }

19 Source : FOStation.cs
with GNU General Public License v3.0
from cumulusmx

private void ProcessHistoryData()
		{
			int totalentries = datalist.Count;

			replacedulus.LogConsoleMessage("Processing history data, number of entries = " + totalentries);

			int rollHour = Math.Abs(replacedulus.GetHourInc());
			int luhour = replacedulus.LastUpdateTime.Hour;
			bool rolloverdone = luhour == rollHour;
			bool midnightraindone = luhour == 0;
			int recCount = datalist.Count;
			int processedCount = 0;

			while (datalist.Count > 0)
			{
				HistoryData historydata = datalist[datalist.Count - 1];

				DateTime timestamp = historydata.timestamp;

				replacedulus.LogMessage("Processing data for " + timestamp);

				int h = timestamp.Hour;

				//  if outside roll-over hour, roll-over yet to be done
				if (h != rollHour)
				{
					rolloverdone = false;
				}

				// In roll-over hour and roll-over not yet done
				if (h == rollHour && !rolloverdone)
				{
					// do roll-over
					replacedulus.LogMessage("Day roll-over " + timestamp.ToShortTimeString());
					DayReset(timestamp);

					rolloverdone = true;
				}

				// Not in midnight hour, midnight rain yet to be done
				if (h != 0)
				{
					midnightraindone = false;
				}

				// In midnight hour and midnight rain (and sun) not yet done
				if (h == 0 && !midnightraindone)
				{
					ResetMidnightRain(timestamp);
					ResetSunshineHours();
					midnightraindone = true;
				}

				// Indoor Humidity ======================================================
				if (historydata.inHum > 100 || historydata.inHum < 0)
				{
					// 255 is the overflow value, when RH gets below 10% - ignore
					replacedulus.LogMessage("Ignoring bad data: inhum = " + historydata.inHum);
				}
				else
				{
					DoIndoorHumidity(historydata.inHum);
				}

				// Indoor Temperature ===================================================
				if (historydata.inTemp < -50 || historydata.inTemp > 50)
				{
					replacedulus.LogMessage("Ignoring bad data: intemp = " + historydata.inTemp);
				}
				else
				{
					DoIndoorTemp(ConvertTempCToUser(historydata.inTemp));
				}

				// Pressure =============================================================

				if ((historydata.pressure < replacedulus.EwOptions.MinPressMB) || (historydata.pressure > replacedulus.EwOptions.MaxPressMB))
				{
					replacedulus.LogMessage("Ignoring bad data: pressure = " + historydata.pressure);
					replacedulus.LogMessage("                   offset = " + pressureOffset);
				}
				else
				{
					DoPressure(ConvertPressMBToUser(historydata.pressure), timestamp);
				}

				if (historydata.SensorContactLost)
				{
					replacedulus.LogMessage("Sensor contact lost; ignoring outdoor data");
				}
				else
				{
					// Outdoor Humidity =====================================================
					if (historydata.outHum > 100 || historydata.outHum < 0)
					{
						// 255 is the overflow value, when RH gets below 10% - ignore
						replacedulus.LogMessage("Ignoring bad data: outhum = " + historydata.outHum);
					}
					else
					{
						DoOutdoorHumidity(historydata.outHum, timestamp);
					}

					// Wind =================================================================
					if (historydata.windGust > 60 || historydata.windGust < 0)
					{
						replacedulus.LogMessage("Ignoring bad data: gust = " + historydata.windGust);
					}
					else if (historydata.windSpeed > 60 || historydata.windSpeed < 0)
					{
						replacedulus.LogMessage("Ignoring bad data: speed = " + historydata.windSpeed);
					}
					else
					{
						DoWind(ConvertWindMSToUser(historydata.windGust), historydata.windBearing, ConvertWindMSToUser(historydata.windSpeed), timestamp);
					}

					// Outdoor Temperature ==================================================
					if (historydata.outTemp < -50 || historydata.outTemp > 70)
					{
						replacedulus.LogMessage("Ignoring bad data: outtemp = " + historydata.outTemp);
					}
					else
					{
						DoOutdoorTemp(ConvertTempCToUser(historydata.outTemp), timestamp);
						// add in 'archivePeriod' minutes worth of temperature to the temp samples
						tempsamplestoday += historydata.interval;
						TempTotalToday += (OutdoorTemperature*historydata.interval);
					}

					// update chill hours
					if (OutdoorTemperature < replacedulus.ChillHourThreshold)
					{
						// add 1 minute to chill hours
						ChillHours += (historydata.interval / 60.0);
					}

					var raindiff = prevraintotal == -1 ? 0 : historydata.rainCounter - prevraintotal;

					// record time of last rain tip, to use in
					// normal running rain rate calc NB rain rate calc not currently used
					/*
					if (raindiff > 0)
					{
						lastraintip = timestamp;

						raininlasttip = raindiff;
					}
					else
					{
						lastraintip = DateTime.MinValue;

						raininlasttip = 0;
					}
					*/
					double rainrate;

					if (raindiff > 100)
					{
						replacedulus.LogMessage("Warning: large increase in rain gauge tip count: " + raindiff);
						rainrate = 0;
					}
					else
					{
						if (historydata.interval > 0)
						{
							rainrate = ConvertRainMMToUser((raindiff * 0.3) * (60.0 / historydata.interval));
						}
						else
						{
							rainrate = 0;
						}
					}

					DoRain(ConvertRainMMToUser(historydata.rainCounter*0.3), rainrate, timestamp);

					prevraintotal = historydata.rainCounter;

					OutdoorDewpoint = ConvertTempCToUser(MeteoLib.DewPoint(ConvertUserTempToC(OutdoorTemperature), OutdoorHumidity));

					CheckForDewpointHighLow(timestamp);

					// calculate wind chill

					if (ConvertUserWindToMS(WindAverage) < 1.5)
					{
						DoWindChill(OutdoorTemperature, timestamp);
					}
					else
					{
						// calculate wind chill from calibrated C temp and calibrated win in KPH
						DoWindChill(ConvertTempCToUser(MeteoLib.WindChill(ConvertUserTempToC(OutdoorTemperature), ConvertUserWindToKPH(WindAverage))), timestamp);
					}

					DoApparentTemp(timestamp);
					DoFeelsLike(timestamp);
					DoHumidex(timestamp);

					if (hreplacedolar)
					{
						if (historydata.uvVal < 0 || historydata.uvVal > 16)
						{
							replacedulus.LogMessage("Invalid UV-I value ignored: " + historydata.uvVal);
						}
						else
							DoUV(historydata.uvVal, timestamp);

						if (historydata.solarVal >= 0 && historydata.solarVal <= 300000)
						{
							DoSolarRad((int) Math.Floor(historydata.solarVal*replacedulus.LuxToWM2), timestamp);

							// add in archive period worth of sunshine, if sunny
							if ((SolarRad > CurrentSolarMax*replacedulus.SunThreshold/100) && (SolarRad >= replacedulus.SolarMinimum))
								SunshineHours += (historydata.interval/60.0);

							LightValue = historydata.solarVal;
						}
						else
						{
							replacedulus.LogMessage("Invalid solar value ignored: " + historydata.solarVal);
						}
					}
				}
				// add in 'following interval' minutes worth of wind speed to windrun
				replacedulus.LogMessage("Windrun: " + WindAverage.ToString(replacedulus.WindFormat) + replacedulus.Units.WindText + " for " + historydata.followinginterval + " minutes = " +
								(WindAverage*WindRunHourMult[replacedulus.Units.Wind]*historydata.followinginterval/60.0).ToString(replacedulus.WindRunFormat) + replacedulus.Units.WindRunText);

				WindRunToday += (WindAverage*WindRunHourMult[replacedulus.Units.Wind]*historydata.followinginterval/60.0);

				// update heating/cooling degree days
				UpdateDegreeDays(historydata.interval);

				// update dominant wind bearing
				CalculateDominantWindBearing(Bearing, WindAverage, historydata.interval);

				CheckForWindrunHighLow(timestamp);

				bw.ReportProgress((totalentries - datalist.Count)*100/totalentries, "processing");

				replacedulus.DoLogFile(timestamp,false);
				if (replacedulus.StationOptions.LogExtraSensors)
				{
					replacedulus.DoExtraLogFile(timestamp);
				}
				replacedulus.MySqlRealtimeFile(999, false, timestamp);

				AddRecentDataWithAq(timestamp, WindAverage, RecentMaxGust, WindLatest, Bearing, AvgBearing, OutdoorTemperature, WindChill, OutdoorDewpoint, HeatIndex,
					OutdoorHumidity, Pressure, RainToday, SolarRad, UV, Raincounter, FeelsLike, Humidex, ApparentTemperature, IndoorTemperature, IndoorHumidity, CurrentSolarMax, RainRate);
				DoTrendValues(timestamp);

				if (replacedulus.StationOptions.CalculatedET && timestamp.Minute == 0)
				{
					// Start of a new hour, and we want to calculate ET in replacedulus
					CalculateEvaoptranspiration(timestamp);
				}

				UpdatePressureTrendString();
				UpdateStatusPanel(timestamp);
				replacedulus.AddToWebServiceLists(timestamp);
				datalist.RemoveAt(datalist.Count - 1);

				if (!Program.service)
				{
					processedCount++;

					Console.Write("\r - processed " + (((double)processedCount) / recCount).ToString("P0"));
				}
			}

			if (!Program.service)
			{
				Console.WriteLine("");
			}
			replacedulus.LogConsoleMessage("End processing history data");
		}

19 Source : WS2300Station.cs
with GNU General Public License v3.0
from cumulusmx

private void GetAndProcessData()
		{
			string presstrend, forecast;
			double direction;

			DateTime now = DateTime.Now;

			// Indoor humidity =====================================================================
			if (!stop)
			{
				int inhum = Ws2300IndoorHumidity();
				if (inhum > -1 && inhum < 101)
				{
					DoIndoorHumidity(inhum);
				}
			}

			// Outdoor humidity ====================================================================
			if(!stop)
			{
				int outhum = Ws2300OutdoorHumidity();
				if ((outhum > 0) && (outhum <= 100) && ((previoushum == 999) || (Math.Abs(outhum - previoushum) < replacedulus.Spike.HumidityDiff)))
				{
					previoushum = outhum;
					DoOutdoorHumidity(outhum, now);
				}
			}

			// Indoor temperature ==================================================================
			if (!stop)
			{
				double intemp = Ws2300IndoorTemperature();
				if (intemp > -20)
				{
					DoIndoorTemp(ConvertTempCToUser(intemp));
				}
			}

			// Outdoor temperature ================================================================
			if (!stop)
			{
				double outtemp = Ws2300OutdoorTemperature();
				if ((outtemp > -60) && (outtemp < 60) && ((previoustemp == 999) || (Math.Abs(outtemp - previoustemp) < replacedulus.Spike.TempDiff)))
				{
					previoustemp = outtemp;
					DoOutdoorTemp(ConvertTempCToUser(outtemp), now);
				}
			}

			// Outdoor dewpoint ==================================================================
			if (!stop)
			{
				double dp = Ws2300OutdoorDewpoint();
				if (dp > -100 && dp < 60)
				{
					DoOutdoorDewpoint(ConvertTempCToUser(dp), now);
				}
			}

			// Pressure ==========================================================================
			if (!stop)
			{
				double pressure = Ws2300RelativePressure();
				if ((pressure > 900) && (pressure < 1200) && ((previouspress == 9999) || (Math.Abs(pressure - previouspress) < replacedulus.Spike.PressDiff)))
				{
					previouspress = pressure;
					DoPressure(ConvertPressMBToUser(pressure), now);
				}

				pressure = Ws2300AbsolutePressure();

				if ((Pressure > 850) && (Pressure < 1200))
				{
					StationPressure = pressure * replacedulus.Calib.Press.Mult + replacedulus.Calib.Press.Offset;
					// AltimeterPressure := ConvertOregonPress(StationToAltimeter(PressureHPa(StationPressure),AlreplacedudeM(Alreplacedude)));
				}
			}

			// Pressure trend and forecast =======================================================
			if (!stop)
			{
				int res = Ws2300PressureTrendAndForecast(out presstrend, out forecast);
				if (res > ERROR)
				{
					DoForecast(forecast, false);
					DoPressTrend(presstrend);
				}
			}

			// Wind ============================================================================
			if (!stop)
			{
				double wind = Ws2300CurrentWind(out direction);
				if ((wind > -1) && ((previouswind == 999) || (Math.Abs(wind - previouswind) < replacedulus.Spike.WindDiff)))
				{
					previouswind = wind;
					DoWind(ConvertWindMSToUser(wind), (int)direction, ConvertWindMSToUser(wind), now);
				}
				else
				{
					replacedulus.LogDebugMessage("Ignoring wind reading: wind=" + wind.ToString("F1") + " previouswind=" + previouswind.ToString("F1") + " sr=" +
											replacedulus.Spike.WindDiff.ToString("F1"));
				}

				// wind chill
				if (replacedulus.StationOptions.CalculatedWC)
				{
					DoWindChill(OutdoorTemperature, now);
				}
				else
				{
					double wc = Ws2300WindChill();
					if (wc > -100 && wc < 60)
					{
						DoWindChill(ConvertTempCToUser(wc), now);
					}
				}
			}

			// Rain ===========================================================================
			if (!stop)
			{
				double raintot = Ws2300RainTotal();
				if (raintot > -1)
				{
					DoRain(ConvertRainMMToUser(raintot), -1, now);
				}
			}

			if (!stop)
			{
				DoApparentTemp(now);
				DoFeelsLike(now);
				DoHumidex(now);
				UpdateStatusPanel(now);
				UpdateMQTT();
			}
		}

19 Source : HomeController.cs
with MIT License
from cwoodruff

public IActionResult Index()
        {
            ViewData["Home"] = _localizer["Home"];
            ViewData["About"] = _localizer["About"];
            ViewData["Contact"] = _localizer["Contact"];
            ViewData["Register"] = _localizer["Register"];
            ViewData["Login"] = _localizer["Login"];
            ViewData["Featured"] = _localizer["Featured"];
            ViewData["Album1Name"] = _localizer["Album1Name"];
            ViewData["Album1Descr"] = _localizer["Album1Descr"];
            ViewData["Album2Name"] = _localizer["Album2Name"];
            ViewData["Album2Descr"] = _localizer["Album2Descr"];
            ViewData["Album3Name"] = _localizer["Album3Name"];
            ViewData["Album3Descr"] = _localizer["Album3Descr"];
            ViewData["Album4Name"] = _localizer["Album4Name"];
            ViewData["Album4Descr"] = _localizer["Album4Descr"];
            ViewData["Album5Name"] = _localizer["Album5Name"];
            ViewData["Album5Descr"] = _localizer["Album5Descr"];
            ViewData["Album6Name"] = _localizer["Album6Name"];
            ViewData["Album6Descr"] = _localizer["Album6Descr"];

            var Album1Price = 9.99;
            var Album2Price = 10.99;
            var Album3Price = 14.99;
            var Album4Price = 7.99;
            var Album5Price = 8.99;
            var Album6Price = 9.99;

            ViewData["Album1Price"] = Album1Price.ToString("c");
            ViewData["Album2Price"] = Album2Price.ToString("c");
            ViewData["Album3Price"] = Album3Price.ToString("c");
            ViewData["Album4Price"] = Album4Price.ToString("c");
            ViewData["Album5Price"] = Album5Price.ToString("c");
            ViewData["Album6Price"] = Album6Price.ToString("c");

            return View();
        }

19 Source : CommonExtensions.cs
with GNU General Public License v3.0
from Cytoid

public static string ToHumanReadableFileSize(this ulong bytes)
    {
        // Determine the suffix and readable value
        string suffix;
        double readable;
        if (bytes >= 0x1000000000000000) // Exabyte
        {
            suffix = "EB";
            readable = bytes >> 50;
        }
        else if (bytes >= 0x4000000000000) // Petabyte
        {
            suffix = "PB";
            readable = bytes >> 40;
        }
        else if (bytes >= 0x10000000000) // Terabyte
        {
            suffix = "TB";
            readable = bytes >> 30;
        }
        else if (bytes >= 0x40000000) // Gigabyte
        {
            suffix = "GB";
            readable = bytes >> 20;
        }
        else if (bytes >= 0x100000) // Megabyte
        {
            suffix = "MB";
            readable = bytes >> 10;
        }
        else if (bytes >= 0x400) // Kilobyte
        {
            suffix = "KB";
            readable = bytes;
        }
        else
        {
            return bytes.ToString("0 B"); // Byte
        }

        // Divide by 1024 to get fractional value
        readable = readable / 1024;
        // Return formatted number with suffix
        return readable.ToString("0.## ") + suffix;
    }

19 Source : SiteInfoExtractor.cs
with GNU Lesser General Public License v3.0
from czsgeo

public void Complete()
        {
            table.Name = "SiteInfo";
            var path = Path.Combine(this.OutputDirectory, "SiteInfo.txt.xls");
            Utils.FileUtil.CheckOrCreateDirectory(this.OutputDirectory);

            var span = DateTime.Now - startTime;
            var m = span.TotalMinutes;
            var seconds = span.TotalSeconds;
            int FileCount = InputRawPathes.Length;
            ObjectTableWriter.Write(table, path);
            string info = "Completed, the total number is " + FileCount + ". The time consumption is " + m.ToString("0.000") + "m=" + seconds.ToString("0.00") + "s, with an average of " + (seconds / FileCount).ToString("0.000") + "s each file";

            log.Info(info);
        }

19 Source : NumeralFormatter.cs
with GNU Lesser General Public License v3.0
from czsgeo

public string Format(string format, object arg, IFormatProvider formatProvider)
        {
            NumeralFormatSymbol sym = new NumeralFormatSymbol(format); 
            int validCount = sym.FractionCount;
           // int.TryParse(format, out validCount);

            if (arg is double || arg is float)
            {
                double val = (double)arg;
                //可以正常记录
                if (IsSuitToString(val))
                {
                    if (ValidCount != validCount)
                    {
                        ZeroPad pad = new ZeroPad(validCount);
                        return  Gdp.Utils.StringUtil.FillSpaceLeft( val.ToString(pad.PadString), sym.StringWidth);
                    }
                    return Gdp.Utils.StringUtil.FillSpaceLeft(val.ToString("0.00000"), sym.StringWidth);
                }
                //整数则直接输出
                if (IsInt(val)) return Gdp.Utils.StringUtil.FillSpaceLeft(val.ToString(), sym.StringWidth);

                //采用科学计数法
                return Gdp.Utils.StringUtil.FillSpaceLeft(val.ToString("G" + (validCount-1)), sym.StringWidth);//0.12345E9
                //return Geo.Utils.StringUtil.FillSpaceLeft(currentVal.ToString("E" + validCount), sym.StringWidth);//0.12345E9
               // return currentVal.ToString("E4");
            }
            return arg.ToString();
        }

19 Source : RmsedNumeral.cs
with GNU Lesser General Public License v3.0
from czsgeo

public virtual string ToString(string format)
        {
            return Value.ToString(format) + "(" + Weight.ToString(format) + ")";
        }

19 Source : RinexFileNameBuilder.cs
with GNU Lesser General Public License v3.0
from czsgeo

public string GetPeriodCode(TimeSpan span)
        { 
            if (span.TotalSeconds < 60)
            {
                return  Math.Round(span.TotalSeconds).ToString("00") + "S";
            }
            if (span.TotalMinutes < 60)
            {
                return Math.Round(span.TotalMinutes).ToString("00") + "M";
            }
            if (span.TotalHours < 24)
            {
                return Math.Round(span.TotalHours).ToString("00") + "H";
            }
            return Math.Round(span.TotalDays).ToString("00") + "D";
        }

19 Source : DMS.cs
with GNU Lesser General Public License v3.0
from czsgeo

public string ToDms_sString()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(IsPlus ? "" : "-");
            sb.Append(Degree.ToString("00"));
            sb.Append(Minute.ToString("00"));
            sb.Append(Second.ToString("00.00####"));
            return sb.ToString();
        }

19 Source : DMS.cs
with GNU Lesser General Public License v3.0
from czsgeo

public string ToD_msString()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(IsPlus ? "" : "-");
            sb.Append(Degree.ToString("00"));
            sb.Append(".");
            sb.Append(Minute.ToString("00"));
            sb.Append(Second.ToString("00.00000000000").Replace(".", ""));
            return sb.ToString();
        }

19 Source : DMS.cs
with GNU Lesser General Public License v3.0
from czsgeo

public string ToHms_sString()
        {
            var degs = this.Degrees;
            var hourDeci = Degrees / 15.0;
            var hour = (int)(hourDeci);
            //var minuteDec = (hourDeci - hour) * 60.0;
            //var minute = (int)minuteDec;
            //var second = (hourDeci - minute / 60.0) * 3600.0;

            StringBuilder sb = new StringBuilder();
            sb.Append(IsPlus ? "" : "-");
            sb.Append(hour.ToString("00"));
            sb.Append(Minute.ToString("00"));
            sb.Append(Second.ToString("00.00####"));
            return sb.ToString();
        }

19 Source : DMS.cs
with GNU Lesser General Public License v3.0
from czsgeo

public string ToReadableDms()
        {
            string mark = "";
            if (!IsPlus) mark = "-";
            return mark + Degree + "°" + Minute.ToString("00") + "'" + Second.ToString("00.000000") + "˝";
        }

19 Source : DMS.cs
with GNU Lesser General Public License v3.0
from czsgeo

public string ToConciseString()
        {
            StringBuilder sb = new StringBuilder();
            //40°07'58  ˚
            string mark = "";
            if (!IsPlus) mark = "-";
            sb.Append(mark);
            if (
                    Degree != 0
                || (Minute == 0)
                )
            {
                sb.Append(Degree + "°");
            }

            if (Minute != 0)
            {
                sb.Append(Minute.ToString("00") + "'");
                if (Second != 0)
                    sb.Append(Second.ToString("00.######") + "˝");
            }
            return sb.ToString();
        }

19 Source : DMS.cs
with GNU Lesser General Public License v3.0
from czsgeo

public string ToHourAngleString()
        {
            string mark = "";
            if (!IsPlus) mark = "-";
            return mark + Degree + "h" + Minute.ToString("00") + "min" + Second.ToString("00.000000") + "s";
            
        }

See More Examples