System.Convert.ToInt32(double)

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

869 Examples 7

19 View Source File : ExcelDrawingBase.cs
License : Apache License 2.0
Project Creator : Appdynamics

internal int GetPixelWidth()
        {
            ExcelWorksheet ws = _drawings.Worksheet;
            decimal mdw = ws.Workbook.MaxFontWidth;

            int pix = -From.ColumnOff / EMU_PER_PIXEL;
            for (int col = From.Column + 1; col <= To.Column; col++)
            {
                pix += (int)decimal.Truncate(((256 * GetColumnWidth(col) + decimal.Truncate(128 / (decimal)mdw)) / 256) * mdw);
            }
            pix += Convert.ToInt32(Math.Round(Convert.ToDouble(To.ColumnOff) / EMU_PER_PIXEL,0));
            return pix;
        }

19 View Source File : DateTimeExtensions.cs
License : GNU General Public License v3.0
Project Creator : asimmon

private static string YearsAgo(TimeSpan ts)
        {
            var years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
            return years <= 1 ? "one year ago" : years + " years ago";
        }

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

public void ReloadFazes()
        {
            int fazeCount = IterationCount;

            if (fazeCount < 1)
            {
                fazeCount = 1;
            }

            if (TimeEnd == DateTime.MinValue ||
                TimeStart == DateTime.MinValue)
            {
                SendLogMessage(OsLocalization.Optimizer.Message12, LogMessageType.System);
                return;
            }

            int dayAll = Convert.ToInt32((TimeEnd - TimeStart).TotalDays);

            if (dayAll < 2)
            {
                SendLogMessage(OsLocalization.Optimizer.Message12, LogMessageType.System);
                return;
            }

            int daysOnInSample = (int)GetInSampleRecurs(dayAll, fazeCount, _lastInSample, dayAll);

            int daysOnForward = Convert.ToInt32(daysOnInSample * (_percentOnFilration / 100));

            Fazes = new List<OptimizerFaze>();

            DateTime time = _timeStart;

            for (int i = 0; i < fazeCount; i++)
            {
                OptimizerFaze newFaze = new OptimizerFaze();
                newFaze.TypeFaze = OptimizerFazeType.InSample;
                newFaze.TimeStart = time;
                newFaze.TimeEnd = time.AddDays(daysOnInSample);
                time = time.AddDays(daysOnForward);
                newFaze.Days = daysOnInSample;
                Fazes.Add(newFaze);

                if(_lastInSample 
                    && i +1 == fazeCount)
                {
                    newFaze.Days = daysOnInSample + daysOnForward;
                    break;
                }

                OptimizerFaze newFazeOut = new OptimizerFaze();
                newFazeOut.TypeFaze = OptimizerFazeType.OutOfSample;
                newFazeOut.TimeStart = newFaze.TimeStart.AddDays(daysOnInSample);
                newFazeOut.TimeEnd = newFazeOut.TimeStart.AddDays(daysOnForward);
                newFazeOut.TimeStart = newFazeOut.TimeStart.AddDays(1);
                newFazeOut.Days = daysOnForward;
                Fazes.Add(newFazeOut);
            }


            /*while (DaysInFazes(Fazes) != dayAll)
            {
                int daysGone = DaysInFazes(Fazes) - dayAll;

                for (int i = 0; i < Fazes.Count && daysGone != 0; i++)
                {

                    if (daysGone > 0)
                    {
                        Fazes[i].Days--;
                        if (Fazes[i].TypeFaze == OptimizerFazeType.InSample &&
                            i + 1 != Fazes.Count)
                        {
                            Fazes[i + 1].TimeStart = Fazes[i + 1].TimeStart.AddDays(-1);
                        }
                        else
                        {
                            Fazes[i].TimeStart = Fazes[i].TimeStart.AddDays(-1);
                        }
                        daysGone--;
                    }
                    else if (daysGone < 0)
                    {
                        Fazes[i].Days++;
                        if (Fazes[i].TypeFaze == OptimizerFazeType.InSample && 
                            i + 1 != Fazes.Count)
                        {
                            Fazes[i + 1].TimeStart = Fazes[i + 1].TimeStart.AddDays(+1);
                        }
                        else
                        {
                            Fazes[i].TimeStart = Fazes[i].TimeStart.AddDays(+1);
                        }
                        daysGone++;
                    }
                }
            }*/
        }

19 View Source File : ProgressBarEx.cs
License : GNU General Public License v3.0
Project Creator : antikmozib

protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        {
            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
            Point StartPoint = new Point(0, 0);
            Point EndPoint = new Point(0, this.Height);

            if (_ProgressDirection == ProgressDir.Vertical)
            {
                EndPoint = new Point(this.Width, 0);
            }

            using (GraphicsPath gp = new GraphicsPath())
            {
                Rectangle rec = new Rectangle(0, 0, this.Width, this.Height);
                int rad = Convert.ToInt32(rec.Height / 2.5);
                if (rec.Width < rec.Height)
                    rad = Convert.ToInt32(rec.Width / 2.5);

                using (LinearGradientBrush _BackColorBrush = new LinearGradientBrush(StartPoint, EndPoint, _BackColor, _GradiantColor))
                {
                    _BackColorBrush.Blend = bBlend;
                    if (_RoundedCorners)
                    {
                        gp.AddArc(rec.X, rec.Y, rad, rad, 180, 90);
                        gp.AddArc(rec.Right - (rad), rec.Y, rad, rad, 270, 90);
                        gp.AddArc(rec.Right - (rad), rec.Bottom - (rad), rad, rad, 0, 90);
                        gp.AddArc(rec.X, rec.Bottom - (rad), rad, rad, 90, 90);
                        gp.CloseFigure();
                        e.Graphics.FillPath(_BackColorBrush, gp);
                    }
                    else
                    {
                        e.Graphics.FillRectangle(_BackColorBrush, rec);
                    }
                }

                if (_Value > _Minimum)
                {
                    int lngth = Convert.ToInt32((double)(this.Width / (double)(_Maximum - _Minimum)) * _Value);
                    if (_ProgressDirection == ProgressDir.Vertical)
                    {
                        lngth = Convert.ToInt32((double)(this.Height / (double)(_Maximum - _Minimum)) * _Value);
                        rec.Y = rec.Height - lngth;
                        rec.Height = lngth;
                    }
                    else
                    {
                        rec.Width = lngth;
                    }

                    using (LinearGradientBrush _ProgressBrush = new LinearGradientBrush(StartPoint, EndPoint, _ProgressColor, _GradiantColor))
                    {
                        _ProgressBrush.Blend = bBlend;
                        if (_RoundedCorners)
                        {
                            if (_ProgressDirection == ProgressDir.Horizontal)
                            {
                                rec.Height -= 1;
                            }
                            else
                            {
                                rec.Width -= 1;
                            }

                            using (GraphicsPath gp2 = new GraphicsPath())
                            {
                                gp2.AddArc(rec.X, rec.Y, rad, rad, 180, 90);
                                gp2.AddArc(rec.Right - (rad), rec.Y, rad, rad, 270, 90);
                                gp2.AddArc(rec.Right - (rad), rec.Bottom - (rad), rad, rad, 0, 90);
                                gp2.AddArc(rec.X, rec.Bottom - (rad), rad, rad, 90, 90);
                                gp2.CloseFigure();
                                using (GraphicsPath gp3 = new GraphicsPath())
                                {
                                    using (Region rgn = new Region(gp))
                                    {
                                        rgn.Intersect(gp2);
                                        gp3.AddRectangles(rgn.GetRegionScans(new Matrix()));
                                    }
                                    e.Graphics.FillPath(_ProgressBrush, gp3);
                                }
                            }
                        }
                        else
                        {
                            e.Graphics.FillRectangle(_ProgressBrush, rec);
                        }
                    }
                }

                if (_Image != null)
                {
                    if (_ImageLayout == ImageLayoutType.Stretch)
                    {
                        e.Graphics.DrawImage(_Image, 0, 0, this.Width, this.Height);
                    }
                    else if (_ImageLayout == ImageLayoutType.None)
                    {
                        e.Graphics.DrawImage(_Image, 0, 0);
                    }
                    else
                    {
                        int xx = Convert.ToInt32((this.Width / 2) - (_Image.Width / 2));
                        int yy = Convert.ToInt32((this.Height / 2) - (_Image.Height / 2));
                        e.Graphics.DrawImage(_Image, xx, yy);
                    }
                }

                if (_ShowPercentage | _ShowText)
                {
                    string perc = "";
                    if (_ShowText)
                        perc = this.Text;
                    if (_ShowPercentage)
                        perc += Convert.ToString(Convert.ToInt32(((double)100 / (double)(_Maximum - _Minimum)) * _Value)) + "%";
                    using (StringFormat sf = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center })
                    {
                        e.Graphics.DrawString(perc, this.Font, _ForeColorBrush, new Rectangle(0, 0, this.Width, this.Height), sf);
                    }
                }

                if (_Border)
                {
                    rec = new Rectangle(0, 0, this.Width - 1, this.Height - 1);
                    if (_RoundedCorners)
                    {
                        gp.Reset();
                        gp.AddArc(rec.X, rec.Y, rad, rad, 180, 90);
                        gp.AddArc(rec.Right - (rad), rec.Y, rad, rad, 270, 90);
                        gp.AddArc(rec.Right - (rad), rec.Bottom - (rad), rad, rad, 0, 90);
                        gp.AddArc(rec.X, rec.Bottom - (rad), rad, rad, 90, 90);
                        gp.CloseFigure();
                        e.Graphics.DrawPath(_BorderPen, gp);
                    }
                    else
                    {
                        e.Graphics.DrawRectangle(_BorderPen, rec);
                    }
                }
            }
        }

19 View Source File : DoubleExtension.cs
License : MIT License
Project Creator : AlphaYu

public static int Floor(this double d)
        {
            return Convert.ToInt32(Math.Floor(d));
        }

19 View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj

private void mnuCheckForUpdates_Click(object sender, EventArgs e)
        {
            System.Threading.Tasks.Task<IReadOnlyList<Octokit.Release>> releases;
            Octokit.Release latest = null;

            ProgressDialog progressDownload = new ProgressDialog();

            Thread thread = new Thread(() =>
            {
                Octokit.GitHubClient client = new Octokit.GitHubClient(new Octokit.ProductHeaderValue("alexgracianoarj"));
                releases = client.Repository.Release.GetAll("alexgracianoarj", "nclreplaced");
                latest = releases.Result[0];

                if (progressDownload.InvokeRequired)
                    progressDownload.BeginInvoke(new Action(() => progressDownload.Close()));
            });

            thread.Start();

            progressDownload.Text = "Update";
            progressDownload.lblPleaseWait.Text = "Checking...";
            progressDownload.SetIndeterminate(true);

            progressDownload.ShowDialog();

            double latestVersion = Convert.ToDouble(latest.TagName.Replace("v", ""), System.Globalization.CultureInfo.InvariantCulture);
            double programVersion = Convert.ToDouble(Program.CurrentVersion.ToString(2), System.Globalization.CultureInfo.InvariantCulture);

            if (latestVersion > programVersion)
            {
                if (MessageBox.Show("There is a new version of NClreplaced.\n\nDo you want download the new version and install it now?", "NClreplaced", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes)
                {
                    thread = new Thread(() =>
                    {
                        WebClient wc = new WebClient();

                        wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler((sen, env) =>
                        {
                            double bytesIn = double.Parse(env.BytesReceived.ToString());
                            double totalBytes = double.Parse(env.TotalBytesToReceive.ToString());
                            double percentage = bytesIn / totalBytes * 100;

                            if (progressDownload.InvokeRequired)
                                progressDownload.BeginInvoke(new Action(() => progressDownload.SetIndeterminate(false)));

                            if (progressDownload.InvokeRequired)
                                progressDownload.BeginInvoke(new Action(() => progressDownload.lblPleaseWait.Text = "Downloaded " + Convert.ToInt32(percentage) + "% - " + (env.BytesReceived / 1024) + " KB of " + (env.TotalBytesToReceive / 1024) + " KB"));

                            if (progressDownload.InvokeRequired)
                                progressDownload.BeginInvoke(new Action(() => progressDownload.progressBar1.Value = Convert.ToInt32(percentage)));

                        });

                        wc.DownloadFileCompleted += new AsyncCompletedEventHandler((sen, env) =>
                        {
                            // Close the dialog if it hasn't been already
                            if (progressDownload.InvokeRequired)
                                progressDownload.BeginInvoke(new Action(() => progressDownload.Close()));

                            System.Diagnostics.Process.Start(Path.GetTempPath() + "NClreplaced_Update.exe");

                            Application.Exit();
                        });

                        wc.DownloadFileAsync(new Uri(latest.replacedets[0].BrowserDownloadUrl), Path.GetTempPath() + "NClreplaced_Update.exe");
                    });

                    thread.Start();

                    progressDownload.lblPleaseWait.Text = "Downloading...";

                    progressDownload.ShowDialog();
                }
            }
            else
            {
                MessageBox.Show("NClreplaced is already updated.", "NClreplaced", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

19 View Source File : WindowsTabControls.cs
License : MIT License
Project Creator : arsium

private void PaintTabText(System.Drawing.Graphics graph, int index)
		{
			string tabtext = this.TabPages[index].Text;

			System.Drawing.StringFormat format = new System.Drawing.StringFormat();
			format.Alignment = StringAlignment.Near;
			format.LineAlignment = StringAlignment.Center;
			format.Trimming = StringTrimming.EllipsisCharacter;

			Brush forebrush = null;

			if (this.TabPages[index].Enabled == false)
			{
				forebrush = new SolidBrush(Color.DeepSkyBlue);
			}
			else
			{
				forebrush = new SolidBrush(COLOR_FORE_BASE);
			}

			Font tabFont = this.Font;
			if (index == this.SelectedIndex)
			{
				if (this.TabPages[index].Enabled != false)
				{
					forebrush = new SolidBrush(_headSelectedBackColor);
				}
			}

			Rectangle rect = this.GetTabRect(index);

			var txtSize = GetStringWidth(tabtext, graph, tabFont);
			//INSTANT VB WARNING: Instant VB cannot determine whether both operands of this division are integer types - if they are then you should use the VB integer division operator:
			Rectangle rect2 = new Rectangle(Convert.ToInt32(rect.Left + (rect.Width - txtSize) / 2.0 - 1), rect.Top, rect.Width, rect.Height);

			graph.DrawString(tabtext, tabFont, forebrush, rect2, format);
		}

19 View Source File : BrowserDeviceAccessor.cs
License : MIT License
Project Creator : aguang-xyz

public async Task<int> GetDurationAsync()
        {
            return Convert.ToInt32(1000 * await InvokeAsync<double>("getDuration"));
        }

19 View Source File : Polyline.cs
License : MIT License
Project Creator : Autodesk

public void Densify(double maximumSpanLength)
        {
            var newPoints = new List<Point>();

            newPoints.Add(this[0]);

            for (int p = 1; p < Count; p++)
            {
                var v1 = this[p] - this[p - 1];
                double vectorLength = v1.Magnitude;

                // If the length of the line connecting two consecutive points is greater than max
                if (vectorLength > maximumSpanLength)
                {
                    // Densify between these two points
                    int numberToInsert = Convert.ToInt32(Math.Floor(vectorLength / maximumSpanLength) - 1);

                    // Calculate actual spacing such that new points will be evenly distributed
                    double actualSpacing = vectorLength / (1 + numberToInsert);

                    v1.Normalize();
                    Point tempEndPoint = this[p - 1];

                    // Add incremental points to the array
                    // Last one should end up the same with this[p]
                    for (int i = 1; i <= numberToInsert; i++)
                    {
                        Vector v2 = v1 * actualSpacing;
                        tempEndPoint = tempEndPoint + v2;
                        newPoints.Add(tempEndPoint);
                    }
                }
                newPoints.Add(this[p]);
            }

            Clear();

            AddRange(newPoints);
        }

19 View Source File : BrowserDeviceAccessor.cs
License : MIT License
Project Creator : aguang-xyz

public async Task<int> GetVolumeAsync()
        {
            return Convert.ToInt32(await InvokeAsync<double>("getVolume") * 100);
        }

19 View Source File : BuildingBlockProvider.cs
License : MIT License
Project Creator : AnnoDesigner

private bool ParseBuildingBlockerForAnno1800(XmlDoreplacedent ifoDoreplacedent, IBuildingInfo building)
        {
            try
            {
                var xf = 0;
                var zf = 0;
                string xc, zc = ""; // just information for checking line calculated mode

                // Change since 25-05-2021 - Fixing measurements of Buildings Buildblockers. 
                // Insttead of taking one XF * 2 and ZF * 2, it will check now the differences between 2 given XF's and ZF's
                // Get all 4 [Position] childs from xml .ifo doreplacedent
                XmlNode node1 = ifoDoreplacedent.FirstChild?[BUILDBLOCKER].FirstChild;
                XmlNode node2 = ifoDoreplacedent.FirstChild?[BUILDBLOCKER].FirstChild.NextSibling;
                XmlNode node3 = ifoDoreplacedent.FirstChild?[BUILDBLOCKER].FirstChild.NextSibling.NextSibling;
                XmlNode node4 = ifoDoreplacedent.FirstChild?[BUILDBLOCKER].FirstChild.NextSibling.NextSibling.NextSibling;

                //check of the nodes contains data
                if (string.IsNullOrEmpty(node1?.InnerText) || string.IsNullOrEmpty(node2?.InnerText) || string.IsNullOrEmpty(node3?.InnerText) || string.IsNullOrEmpty(node4?.InnerText))
                {
                    Console.WriteLine("-'X' and 'Z' are both 'Null' - Building will be skipped!");
                    return false;
                }

                building.BuildBlocker = new SerializableDictionary<int>();

                //Convert the strings to a Variable and replace the "." for a "," to keep calculatable numbers 
                var xfNormal1 = Convert.ToDouble(node1["xf"].InnerText.Replace(".", ","));
                var zfNormal1 = Convert.ToDouble(node1["zf"].InnerText.Replace(".", ","));
                var xfNormal2 = Convert.ToDouble(node2["xf"].InnerText.Replace(".", ","));
                var zfNormal2 = Convert.ToDouble(node2["zf"].InnerText.Replace(".", ","));
                var xfNormal3 = Convert.ToDouble(node3["xf"].InnerText.Replace(".", ","));
                var zfNormal3 = Convert.ToDouble(node3["zf"].InnerText.Replace(".", ","));
                var xfNormal4 = Convert.ToDouble(node4["xf"].InnerText.Replace(".", ","));
                var zfNormal4 = Convert.ToDouble(node4["zf"].InnerText.Replace(".", ","));

                // Calculation mode check highest number minus lowest number
                // example 1:  9 - -2 = 11
                // example 2: 2,5 - -2,5 = 5
                // This will give the right BuildBlocker[X] and BuildBlocker[Y] for all buildings from anno 1800

                // XF Calculation 
                if (xfNormal1 > xfNormal3)
                {
                    xf = Convert.ToInt32(xfNormal1 - xfNormal3);
                    xc = "MA";// just information for checking line calculated mode
                } else
                {
                    xf = Convert.ToInt32(xfNormal3 - xfNormal1);
                    xc = "MB";// just information for checking line calculated mode
                }

                // zf Calculation 
                if (zfNormal1 > zfNormal2)
                {
                    zf = Convert.ToInt32(zfNormal1 - zfNormal2);
                    zc = "MA";// just information for checking line calculated mode
                }
                else if (zfNormal1 == zfNormal2)
                {
                    if (zfNormal1 > zfNormal3)
                    {
                        zf = Convert.ToInt32(zfNormal1 - zfNormal3);
                        zc = "MB";// just information for checking line calculated mode
                    }
                    else
                    {
                        zf = Convert.ToInt32(zfNormal3 - zfNormal1);
                        zc = "MD";// just information for checking line calculated mode
                    }
                }
                else
                {
                    zf = Convert.ToInt32(zfNormal2 - zfNormal1);
                    zc = "MC";// just information for checking line calculated mode
                }

                
                if ((xf == 0 || zf == 0) && building.Identifier != "Trail_05x05") {
                    //when something goes wrong on the measurements, report and stop till a key is hit
                    Console.WriteLine("MEASUREMENTS GOING WRONG!!! CHECK THIS BUILDING");
                    Console.WriteLine(" Node 1 - XF: {0} | ZF: {1} ;\n Node 2 - XF: {2} | ZF: {3} ;\n Node 3 - XF: {4} | ZF: {5} ;\n Node 4 - XF: {6} | ZF: {7}", xfNormal1, zfNormal1, xfNormal2, zfNormal2, xfNormal3, zfNormal3, xfNormal4, zfNormal4);
                    Console.WriteLine("Building measurement is : {0} x {1} (Method {2} and {3})", xf, zf, xc, zc);
                    Console.WriteLine("Press a key to continue");
                    //Console.ReadKey();
                }

                //if both values are zero, then skip building
                if (xf < 1 && zf < 1)
                {
                    Console.WriteLine("-'X' and 'Z' are both 0 - Building will be skipped!");
                    return false;
                }

                if (xf > 0)
                {
                    building.BuildBlocker[X] = Math.Abs(xf);
                }
                else
                {
                    building.BuildBlocker[X] = 1;
                }

                if (zf > 0)
                {
                    building.BuildBlocker[Z] = Math.Abs(zf);
                }
                else
                {
                    building.BuildBlocker[Z] = 1;
                }
            }
            catch (NullReferenceException)
            {
                Console.WriteLine("-BuildBlocker not found, skipping");
                return false;
            }

            return true;
        }

19 View Source File : DownloadUpdateDialog.cs
License : MIT License
Project Creator : Analogy-LogViewer

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

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

19 View Source File : LightDataTableShared.cs
License : MIT License
Project Creator : AlenToma

protected void TypeValidation(ref object value, Type dataType, bool loadDefaultOnError, object defaultValue = null)
        {
            try
            {
                ValidateCulture();
                if (value == null || value is DBNull)
                {
                    value = ValueByType(dataType, defaultValue);
                    return;
                }

                if (IgnoreTypeValidation)
                    return;

                if (dataType == typeof(byte[]) && value.GetType() == typeof(string))
                {
                    if (value.ToString().Length % 4 == 0) // its a valid base64string
                        value = Convert.FromBase64String(value.ToString());
                    return;
                }

                if (dataType == typeof(int?) || dataType == typeof(int))
                {
                    if (double.TryParse(CleanValue(dataType, value).ToString(), NumberStyles.Float, Culture, out var douTal))
                        value = Convert.ToInt32(douTal);
                    else
                        if (loadDefaultOnError)
                        value = ValueByType(dataType, defaultValue);

                    return;
                }

                if (dataType == typeof(long?) || dataType == typeof(long))
                {
                    if (double.TryParse(CleanValue(dataType, value).ToString(), NumberStyles.Float, Culture, out var douTal))
                        value = Convert.ToInt64(douTal);
                    else
                    if (loadDefaultOnError)
                        value = ValueByType(dataType, defaultValue);

                    return;
                }

                if (dataType == typeof(float?) || dataType == typeof(float))
                {
                    if (float.TryParse(CleanValue(dataType, value).ToString(), NumberStyles.Float, Culture, out var douTal))
                        value = RoundingSettings.Round(douTal);
                    else
                    if (loadDefaultOnError)
                        value = ValueByType(dataType, defaultValue);

                    return;
                }

                if (dataType == typeof(decimal?) || dataType == typeof(decimal))
                {
                    if (decimal.TryParse(CleanValue(dataType, value).ToString(), NumberStyles.Float, Culture, out var decTal))
                        value = RoundingSettings.Round(decTal);
                    else
                    if (loadDefaultOnError)
                        value = ValueByType(dataType, defaultValue);
                    return;

                }

                if (dataType == typeof(double?) || dataType == typeof(double))
                {
                    if (double.TryParse(CleanValue(dataType, value).ToString(), NumberStyles.Float, Culture, out var douTal))
                        value = RoundingSettings.Round(douTal);
                    else
                    if (loadDefaultOnError)
                        value = ValueByType(dataType, defaultValue);
                    return;

                }

                if (dataType == typeof(DateTime?) || dataType == typeof(DateTime))
                {
                    if (DateTime.TryParse(value.ToString(), Culture, DateTimeStyles.None, out var dateValue))
                    {
                        if (dateValue < SqlDateTime.MinValue)
                            dateValue = SqlDateTime.MinValue.Value;
                        value = dateValue;

                    }
                    else
                    if (loadDefaultOnError)
                        value = ValueByType(dataType, defaultValue);
                    return;

                }

                if (dataType == typeof(bool?) || dataType == typeof(bool))
                {
                    if (bool.TryParse(value.ToString(), out var boolValue))
                        value = boolValue;
                    else
                    if (loadDefaultOnError)
                        value = ValueByType(dataType, defaultValue);
                    return;
                }

                if (dataType == typeof(TimeSpan?) || dataType == typeof(TimeSpan))
                {
                    if (TimeSpan.TryParse(value.ToString(), Culture, out var timeSpanValue))
                        value = timeSpanValue;
                    else
                    if (loadDefaultOnError)
                        value = ValueByType(dataType, defaultValue);
                    return;


                }

                if (dataType.IsEnum || (dataType.GenericTypeArguments?.FirstOrDefault()?.IsEnum ?? false))
                {

                    var type = dataType;
                    if ((dataType.GenericTypeArguments?.FirstOrDefault()?.IsEnum ?? false))
                        type = (dataType.GenericTypeArguments?.FirstOrDefault());
                    if (value is int || value is long)
                    {
                        if (Enum.IsDefined(type, Convert.ToInt32(value)))
                            value = Enum.ToObject(type, Convert.ToInt32(value));
                    }
                    else if (Enum.IsDefined(type, value))
                        value = Enum.Parse(type, value.ToString(), true);
                    else if (loadDefaultOnError)
                        value = Activator.CreateInstance(dataType);
                }
                else if (dataType == typeof(Guid) || dataType == typeof(Guid?))
                {
                    if (Guid.TryParse(value.ToString(), out Guid v))
                        value = v;
                    else if (loadDefaultOnError)
                        value = ValueByType(dataType, defaultValue);
                } else if (dataType == typeof(string))
                {
                    value = value.ToString();

                }


            }
            catch (Exception ex)
            {
                throw new Exception($"Error: InvalidType. ColumnType is {dataType.FullName} and the given value is of type {value.GetType().FullName} Original Exception {ex.Message}");

            }
        }

19 View Source File : RedeliveryPolicy.cs
License : Apache License 2.0
Project Creator : apache

public virtual int RedeliveryDelay(int redeliveredCounter)
        {
            int delay = 0;

            if (redeliveredCounter == 0)
            {
                // The first time through there is no delay, the Rollback should be immediate.
                return 0;
            }

            if (UseExponentialBackOff && BackOffMultiplier > 1)
            {
                delay = initialRedeliveryDelay * Convert.ToInt32(Math.Pow(BackOffMultiplier, redeliveredCounter - 1));
            }
            else
            {
                delay = InitialRedeliveryDelay;
            }

            if (UseCollisionAvoidance)
            {
                Random random = RandomNumberGenerator;
                double variance = (NextBool ? collisionAvoidanceFactor : collisionAvoidanceFactor *= -1) *
                                  random.NextDouble();
                delay += Convert.ToInt32(Convert.ToDouble(delay) * variance);
            }

            return delay;
        }

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

private void Select(int offset, int limit, int itemLimit, ICollection<T> items)
		{
			var selected = _select(offset, limit);

			foreach (var item in selected)
			{
				offset++;

				if (!_filter(item))
				{
					continue;
				}

				items.Add(item);

				if (items.Count >= itemLimit)
				{
					return;
				}
			}

			// If _select returned fewer items than were asked for, there must be no further items
			// to select, and so we should quit after processing the items we did get.
			if (selected.Length < limit)
			{
				return;
			}

			// For the next selection, set the limit to the median value between the original query
			// limit, and the number of remaining items needed.
			var reselectLimit = Convert.ToInt32(Math.Round((limit + (itemLimit - items.Count)) / 2.0, MidpointRounding.AwayFromZero));

			Select(offset, reselectLimit, itemLimit, items);
		}

19 View Source File : Rank.cs
License : Apache License 2.0
Project Creator : Appdynamics

public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
        {
            ValidateArguments(arguments, 2);
            var number = ArgToDecimal(arguments, 0);
            var refer = arguments.ElementAt(1);
            bool asc = false;
            if (arguments.Count() > 2)
            {
                asc = base.ArgToBool(arguments, 2);
            }
            var l = new List<double>();

            foreach (var c in refer.ValueAsRangeInfo)
            {
                var v = Utils.ConvertUtil.GetValueDouble(c.Value, false, true);
                if (!double.IsNaN(v))
                {
                    l.Add(v);
                }
            }
            l.Sort();
            double ix;
            if (asc)
            {
                ix = l.IndexOf(number)+1;
                if(_isAvg)
                {
                    int st = Convert.ToInt32(ix);
                    while (l.Count > st && l[st] == number) st++;
                    if (st > ix) ix = ix + ((st - ix) / 2D);
                }
            }
            else
            {
                ix = l.LastIndexOf(number);
                if (_isAvg)
                {
                    int st = Convert.ToInt32(ix)-1;
                    while (0 <= st && l[st] == number) st--;
                    if (st+1 < ix) ix = ix - ((ix - st - 1) / 2D);
                }
                ix = l.Count - ix;
            }
            if (ix <= 0 || ix>l.Count)
            {
                return new CompileResult(ExcelErrorValue.Create(eErrorType.NA), DataType.ExcelError);
            }
            else
            {
                return CreateResult(ix, DataType.Decimal);
            }
        }

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

public List<Candle> GetCandleHistory(string security, TimeSpan interval)
        {
            int oldInterval = Convert.ToInt32(interval.TotalMinutes);

            var needIntervalForQuery =
                CandlesCreator.DetermineAppropriateIntervalForRequest(oldInterval, _supportedIntervals, out var needInterval);

            var jsonCandles = RequestCandlesFromExchange(needIntervalForQuery, security);

            var oldCandles = CreateCandlesFromJson(jsonCandles);

            if (oldInterval == needInterval)
            {
                return oldCandles;
            }

            var newCandles = CandlesCreator.CreateCandlesRequiredInterval(needInterval, oldInterval, oldCandles);

            return newCandles;
        }

19 View Source File : Utilities.cs
License : MIT License
Project Creator : arsium

private static string ThreeNonZeroDigits(double value)
		{
			if (value >= 100)
			{
				// No digits after the decimal.
				return Microsoft.VisualBasic.Strings.Format(Convert.ToInt32(value));
			}
			else if (value >= 10)
			{
				// One digit after the decimal.
				return value.ToString("0.0");
			}
			else
			{
				return value.ToString("0.00");
			}
		}

19 View Source File : MainPage.xaml.cs
License : MIT License
Project Creator : Abdesol

private string equal(string exp)
        {
            string new_expr = "";
            foreach(char i in exp)
            {
                char ii = i;
                if (i == '×')
                {
                    ii = '*';
                }
                else if (i == '÷')
                {
                    ii = '/';
                }
                new_expr += ii;
            }
            try
            {
                Enreplacedy expr = new_expr;
                double output = (double)expr.EvalNumerical();
                if((output%1 == 0) == true)
                {
                    int o = Convert.ToInt32(output);
                    return Convert.ToString(o);
                }
                else
                {
                    return Convert.ToString(output);
                }
            }
            catch
            {
                return exp;
            }
        }

19 View Source File : Polyline.cs
License : MIT License
Project Creator : Autodesk

public static List<Polyline> ReadFromDUCTPictureFile(File file)
        {
            List<Polyline> polylines = new List<Polyline>();

            string CurCult = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
            try
            {
                System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-GB");

                string strBuff = "";
                using (
                    System.IO.FileStream FS = new System.IO.FileStream(file.Path,
                                                                       System.IO.FileMode.Open,
                                                                       System.IO.FileAccess.Read))
                {
                    using (System.IO.StreamReader SR = new System.IO.StreamReader(FS))
                    {
                        strBuff = SR.ReadToEnd();
                        SR.Close();
                    }
                    FS.Close();
                }
                strBuff = strBuff.Replace(Strings.Chr(9).ToString(), "");
                strBuff = strBuff.Replace(Strings.Chr(13).ToString(), "");
                string[] strSpl = strBuff.Split(Strings.Chr(10));

                List<List<int>> instructions = new List<List<int>>();
                List<Point> points = new List<Point>();

                // Check to see if the file is in inches or mm
                bool isInInches = strSpl[1].Trim().ToLower().EndsWith("inches");

                // Ignore the header lines just concentrate on the juicy bits
                for (int lineIndex = 5; lineIndex <= strSpl.Length - 1; lineIndex++)
                {
                    // Collect up all the numeric values on the line
                    List<double> elementsOnLine = new List<double>();
                    foreach (string stringElement in strSpl[lineIndex].Split(' '))
                    {
                        double value = 0;
                        if (double.TryParse(stringElement,
                                            NumberStyles.Any,
                                            CultureInfo.InvariantCulture,
                                            out value))
                        {
                            elementsOnLine.Add(value);
                        }
                    }
                    if (elementsOnLine.Count == 2)
                    {
                        // If there are two values then it is an instruction line
                        instructions.Add(new List<int>
                        {
                            Convert.ToInt32(elementsOnLine[0]),
                            Convert.ToInt32(elementsOnLine[1])
                        });
                    }
                    else if (elementsOnLine.Count >= 3)
                    {
                        // Otherwise it is a point data line
                        if (isInInches)
                        {
                            points.Add(new Point(elementsOnLine[0] * 25.4, elementsOnLine[1] * 25.4, elementsOnLine[2] * 25.4));
                        }
                        else
                        {
                            points.Add(new Point(elementsOnLine[0], elementsOnLine[1], elementsOnLine[2]));
                        }
                    }
                }

                // So we have all the data, now we need to populate the polyline and spline lists

                // This keeps track of which point we are looking at for the current instruction
                int pointIndex = 0;

                for (int instructionIndex = 0; instructionIndex <= instructions.Count - 1; instructionIndex++)
                {
                    if ((instructions[instructionIndex][0] & 1024) == 1024)
                    {
                        // Bezier curves
                        Spline spline = new Spline();
                        int pixelIndex = 1;
                        if ((instructions[instructionIndex][0] & 24) == 24)
                        {
                            pixelIndex = -1;
                        }
                        while (pixelIndex < instructions[instructionIndex][1])
                            if (pixelIndex == -1)
                            {
                                // First pixel only has tangency out
                                Vector directionOut = points[pointIndex + pixelIndex + 1] - points[pointIndex + pixelIndex];
                                double distanceOut = directionOut.Magnitude;
                                directionOut.Normalize();
                                spline.Add(new SplinePoint(points[pointIndex + pixelIndex],
                                                           directionOut,
                                                           distanceOut,
                                                           directionOut,
                                                           distanceOut));
                                pixelIndex += 3;
                            }
                            else if (instructions[instructionIndex][1] - pixelIndex == 1)
                            {
                                // Last pixel only has tangency in
                                Vector directionIn = points[pointIndex + pixelIndex] - points[pointIndex + pixelIndex - 1];
                                double distanceIn = directionIn.Magnitude;
                                directionIn.Normalize();
                                spline.Add(new SplinePoint(points[pointIndex + pixelIndex],
                                                           directionIn,
                                                           distanceIn,
                                                           directionIn,
                                                           distanceIn));
                                pixelIndex += 3;
                            }
                            else
                            {
                                // Pixel has tangency in and out
                                Vector directionIn = points[pointIndex + pixelIndex] - points[pointIndex + pixelIndex - 1];
                                double distanceIn = directionIn.Magnitude;
                                directionIn.Normalize();
                                Vector directionOut = points[pointIndex + pixelIndex + 1] - points[pointIndex + pixelIndex];
                                double distanceOut = directionOut.Magnitude;
                                directionOut.Normalize();
                                spline.Add(new SplinePoint(points[pointIndex + pixelIndex],
                                                           directionIn,
                                                           distanceIn,
                                                           directionOut,
                                                           distanceOut));
                                pixelIndex += 3;
                            }
                        if ((instructions[instructionIndex][0] & 24) == 0)
                        {
                            // Starting a new section
                            Polyline polyline = new Polyline(spline, 0.01);
                            polylines.Add(polyline);
                        }
                        else
                        {
                            // Continuing the last section
                            Polyline polyline = new Polyline(spline, 0.01);

                            // Add all points apart from the first one
                            for (int i = 1; i <= polyline.Count - 1; i++)
                            {
                                polylines[polylines.Count - 1].Add(polyline[i]);
                            }
                        }
                        pointIndex += instructions[instructionIndex][1];
                    }
                    else if ((instructions[instructionIndex][0] & 512) == 512)
                    {
                        // Conic arcs
                        Spline intermediateCurve = new Spline();
                        Spline spline = new Spline();
                        int pixelIndex = 0;
                        if ((instructions[instructionIndex][0] & 24) == 24)
                        {
                            pixelIndex = -1;
                        }
                        while (pixelIndex < instructions[instructionIndex][1])
                        {
                            intermediateCurve.Add(new SplinePoint(points[pointIndex + pixelIndex]));

                            // If there are three points on the curve
                            if (intermediateCurve.Count == 3)
                            {
                                intermediateCurve.FreeTangentsAndMagnitudes();
                                if (spline.Count != 0)
                                {
                                    // If the spline curve already has points then dont add the first one, just set the output tangent and magnitude 
                                    spline.Last().MagnitudeAfter = intermediateCurve[0].MagnitudeAfter;
                                    spline.Last().DirectionAfter = intermediateCurve[0].DirectionAfter;
                                }
                                else
                                {
                                    // else add first point
                                    spline.Add(intermediateCurve[0]);
                                }

                                // add second and third point
                                spline.Add(intermediateCurve[1]);
                                spline.Add(intermediateCurve[2]);
                                var p = intermediateCurve[2];

                                // reset intermediate curve and add last point
                                intermediateCurve.Clear();
                                intermediateCurve.Add(p.Clone());
                            }

                            pixelIndex += 1;
                        }
                        if ((instructions[instructionIndex][0] & 24) == 0)
                        {
                            // Starting a new section
                            Polyline polyline = new Polyline(spline, 0.01);
                            polylines.Add(polyline);
                        }
                        else
                        {
                            // Continuing the last section
                            Polyline polyline = new Polyline(spline, 0.01);

                            // Add all points apart from the first one
                            for (int i = 1; i <= polyline.Count - 1; i++)
                            {
                                polylines[polylines.Count - 1].Add(polyline[i]);
                            }
                        }
                        pointIndex += instructions[instructionIndex][1];
                    }
                    else
                    {
                        // Polylines
                        if ((instructions[instructionIndex][0] & 24) == 0)
                        {
                            // Starting a new section
                            Polyline polyline =
                                new Polyline(
                                    new List<Point>(points.GetRange(pointIndex, instructions[instructionIndex][1]).ToArray()));
                            polylines.Add(polyline);
                        }
                        else
                        {
                            // Continuing the last section
                            polylines[polylines.Count - 1].AddRange(
                                points.GetRange(pointIndex, instructions[instructionIndex][1]).ToArray());
                        }
                        pointIndex += instructions[instructionIndex][1];
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(CurCult);
            }

            return polylines;
        }

19 View Source File : GlobalMercator.cs
License : MIT License
Project Creator : AliFlux

public TileAddress GoogleTile(int tx, int ty, int zoom)
        {
            TileAddress retval = new TileAddress();
            try
            {
                retval.X = tx;
                retval.Y = Convert.ToInt32((Math.Pow(2, zoom) - 1) - ty);
                return retval;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

19 View Source File : DoubleExtension.cs
License : MIT License
Project Creator : AlphaYu

public static int Ceiling(this double a)
            => Convert.ToInt32(Math.Ceiling(a));

19 View Source File : TickIntervalConverter.cs
License : MIT License
Project Creator : Actipro

public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
		#endif
			var doubleValue = Math.Ceiling(System.Convert.ToDouble(value));
			int intValue = System.Convert.ToInt32(doubleValue);

			if (intValue == 0)
				return 1;
			if (intValue == 1)
				return 2;
			if(intValue == 2)
				return 4;
			if (intValue == 3)
				return 6;
			if (intValue == 4)
				return 8;

			return 10;
		}

19 View Source File : Utils.cs
License : MIT License
Project Creator : AmazingDM

public static async Task<int> TCPingAsync(IPAddress ip, int port, int timeout = 1000, CancellationToken ct = default)
        {
            using var client = new TcpClient(ip.AddressFamily);

            var stopwatch = Stopwatch.StartNew();

            var task = client.ConnectAsync(ip, port);

            var resTask = await Task.WhenAny(task, Task.Delay(timeout, ct));

            stopwatch.Stop();
            if (resTask == task && client.Connected)
            {
                var t = Convert.ToInt32(stopwatch.Elapsed.TotalMilliseconds);
                return t;
            }

            return timeout;
        }

19 View Source File : SsdpClient.cs
License : MIT License
Project Creator : aguang-xyz

private void SearchAndWaitForReplies(object sender, ElapsedEventArgs e)
        {
            var dgram = BuildSearchDgram(Convert.ToInt32(SearchInterval.TotalSeconds));

            using var client = BuildUdpClientForSearch();

            client.Send(dgram, dgram.Length, new IPEndPoint(MulticastAddress, MulticastPort));

            var startedAt = DateTimeOffset.Now;
            while (DateTimeOffset.Now < startedAt.AddMilliseconds(SearchInterval.TotalMilliseconds))
            {
                try
                {
                    var endpoint = new IPEndPoint(IPAddress.Any, 0);
                    var message = Encoding.UTF8.GetString(client.Receive(ref endpoint));
                    var serviceInfo = ParseReplyMessage(message);

                    if (serviceInfo != null)
                    {
                        TryAddService(serviceInfo);
                    }
                }
                catch (SocketException)
                {
                    // Ignored
                }
                catch (ObjectDisposedException)
                {
                    // Ignored
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception);
                }
            }
        }

19 View Source File : RandomizedInputTest.cs
License : Apache License 2.0
Project Creator : AnkiUniversal

private string RandomString(int size, bool lowerCase = false)
        {
            StringBuilder builder = new StringBuilder();
            Random random = new Random();
            char ch;
            for (int i = 0; i < size; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }
            if (lowerCase)
                return builder.ToString().ToLower();
            return builder.ToString();
        }

19 View Source File : ApnSender.cs
License : MIT License
Project Creator : andrei-m-code

private static int ToEpoch(DateTime time)
        {
            var span = DateTime.UtcNow - new DateTime(1970, 1, 1);
            return Convert.ToInt32(span.TotalSeconds);
        }

19 View Source File : UnitsCalculator.cs
License : MIT License
Project Creator : alaabenfatma

public static string SizeCalc(long byteCount)
        {
            string[] suf = {"B", "KB", "MB", "GB", "TB", "PB", "EB"};
            if (byteCount == 0)
                return "0" + suf[0];
            var bytes = Math.Abs(byteCount);
            var place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
            var num = Math.Round(bytes / Math.Pow(1024, place), 1);
            return Math.Sign(byteCount) * num + suf[place];
        }

19 View Source File : TPLinkSmartPlug.cs
License : Apache License 2.0
Project Creator : anthturner

public string SetCountDown(bool stateAtDelayExpiration, TimeSpan delay, string name = "")
        {
            // Clean-up the previous rule - if not done, the device responds with a "table is full" error
            Execute("count_down", "delete_all_rules", null, null);

            var retValue = Execute("count_down", "add_rule", null, new JObject
                {
                    new JProperty("enable", 1),
                    new JProperty("delay", Convert.ToInt32(delay.TotalSeconds)),
                    new JProperty("act", stateAtDelayExpiration? 1 : 0),
                    new JProperty("name", name)
                });

            return retValue["id"];
        }

19 View Source File : Helper.cs
License : MIT License
Project Creator : adamped

public static int toInt(this double value) => Convert.ToInt32(value);

19 View Source File : ConsumerTest.cs
License : Apache License 2.0
Project Creator : apache

[Test]
        [ConnectionSetup(null, "default")]
        [SessionSetup("default", "default", AckMode = AcknowledgementMode.AutoAcknowledge)]
        [TopicSetup("default", "testdest1", Name = "nms.test")]
        [ConsumerSetup("default", "testdest1", "con1")]
        [ProducerSetup("default", "testdest1", "pro1")]
        public void TestReceiveMessageSync()
        {
            const int NUM_MSGS = 100;
            const int CONUSMER_TIMEOUT = 25; // 25 ms to pull from consumer.
            const int BACKOFF_SLEEP = 500; // 0.5 secs to sleep when consumer pull times out.
            using (IConnection connection = this.GetConnection())
            using (IMessageConsumer consumer = this.GetConsumer("con1"))
            using (IMessageProducer producer = this.GetProducer("pro1"))
            {
                try
                {
                    connection.ExceptionListener += DefaultExceptionListener;
                    connection.Start();

                    SendMessages(producer, NUM_MSGS);

                    ITextMessage textMessage = null;
                    IMessage message = null;
                    int backoffCount = 0;
                    DateTime start = DateTime.Now;
                    TimeSpan duration;
                    while (msgCount < NUM_MSGS && backoffCount < 3)
                    {
                        while ((message = consumer.Receive(TimeSpan.FromMilliseconds(CONUSMER_TIMEOUT))) != null)
                        {
                            textMessage = message as ITextMessage;
                            replacedert.AreEqual("num:" + msgCount, textMessage.Text, "Received message out of order.");
                            msgCount++;
                        }
                        backoffCount++;
                        if (backoffCount < 3 && msgCount < NUM_MSGS)
                        {
                            System.Threading.Thread.Sleep(BACKOFF_SLEEP);
                        }
                    }

                    duration = (DateTime.Now - start);
                    int milis = Convert.ToInt32(duration.TotalMilliseconds);
                    replacedert.AreEqual(NUM_MSGS, msgCount, "Received {0} messages out of {1} in {0}ms.", msgCount, NUM_MSGS, milis);

                }
                catch (Exception ex)
                {
                    this.PrintTestFailureAndreplacedert(this.GetMethodName(), "Unexpected Exception.", ex);
                }
            }
        }

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

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

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

19 View Source File : SystemInfo.cs
License : Apache License 2.0
Project Creator : apache

public static bool TryParse(string s, out int val)
		{
#if NETCF
			val = 0;
			try
			{
				val = int.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);
				return true;
			}
			catch
			{
			}

			return false;
#else
			// Initialise out param
			val = 0;

			try
			{
				double doubleVal;
				if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal))
				{
					val = Convert.ToInt32(doubleVal);
					return true;
				}
			}
			catch
			{
				// Ignore exception, just return false
			}

			return false;
#endif
		}

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

private SimulatedMouseInput SimulateAngledInput(double angle, double magnitude)
        {
            SimulatedMouseInput mouseInputData;

            var moveX = Math.Round(magnitude * Math.Cos(angle), 4);
            var moveY = Math.Round(magnitude * Math.Sin(angle), 4);

            if (moveX == 0)
            {
                mouseInputData.x = 0;
                mouseInputData.y = (int)Math.Ceiling(moveY);
                mouseInputData.time = mouseInputData.y / moveY;
            }
            else if (moveY == 0)
            {
                mouseInputData.x = (int)Math.Ceiling(moveX);
                mouseInputData.y = 0;
                mouseInputData.time = mouseInputData.x / moveX;
            }
            else
            {
                var ratio =  moveY / moveX;
                int ceilX = 0;
                int ceilY = 0;
                double biggerX = 0;
                double biggerY = 0;
                double roundedBiggerX = 0;
                double roundedBiggerY = 0;
                double roundedRatio = -1;
                double factor = 10;

                while (Math.Abs(roundedRatio - ratio) > 0.01 &&
                    biggerX < 25000 &&
                    biggerY < 25000)
                {
                    roundedBiggerX = Math.Floor(biggerX);
                    roundedBiggerY = Math.Floor(biggerY);
                    ceilX = Convert.ToInt32(roundedBiggerX);
                    ceilY = Convert.ToInt32(roundedBiggerY);
                    roundedRatio =  ceilX > 0 ? ceilY / ceilX : -1;
                    biggerX = moveX * factor;
                    biggerY = moveY * factor;
                    factor *= 10;
                }

                var ceilMagnitude = Magnitude(ceilX, ceilY);
                var timeFactor = ceilMagnitude / magnitude;

                mouseInputData.x = ceilX;
                mouseInputData.y = ceilY;
                mouseInputData.time = timeFactor;

                if (mouseInputData.x == 1 && mouseInputData.time == 1)
                {
                    Console.WriteLine("Oops");
                }

            }

            mouseInputData.velocity = DecimalCheck(Velocity(mouseInputData.x, mouseInputData.y, mouseInputData.time));

            if (double.IsNaN(mouseInputData.velocity))
            {
                Console.WriteLine("oopsie");
            }

            mouseInputData.angle = angle;
            return mouseInputData;
        }

19 View Source File : ExcelDrawingBase.cs
License : Apache License 2.0
Project Creator : Appdynamics

internal int GetPixelHeight()
        {
            ExcelWorksheet ws = _drawings.Worksheet;

            int pix = -(From.RowOff / EMU_PER_PIXEL);
            for (int row = From.Row + 1; row <= To.Row; row++)
            {
                pix += (int)(GetRowHeight(row) / 0.75);
            }
            pix += Convert.ToInt32(Math.Round(Convert.ToDouble(To.RowOff) / EMU_PER_PIXEL, 0));
            return pix;
        }

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

public List<Candle> GetCandleHistory(string securityName, TimeSpan seriesTimeFrameSpan, int count, DateTime start, DateTime end)
        {
            try
            {
                lock (_candlesLocker)
                {

                    List<Candle> newCandles = null;


                    int tf = Convert.ToInt32(seriesTimeFrameSpan.TotalMinutes);

                    if (tf == 1 || tf == 2 || tf == 3)
                    {
                        // building candles from 1 minute / строим свечи из минуток
                        var rawCandles = GetBitfinexCandles("1m", securityName, count, start, end);
                        newCandles = TransformCandles(1, tf, rawCandles);
                    }
                    else if (tf == 5 || tf == 10 || tf == 20)
                    {
                        // building candles from 5 minutes / строим свечи из 5минуток
                        var rawCandles = GetBitfinexCandles("5m", securityName, count, start, end);
                        newCandles = TransformCandles(5, tf, rawCandles);
                    }
                    else if (tf == 15 || tf == 30 || tf == 45)
                    {
                        // building candles from 15 minutes / строим свечи из 15минуток
                        var rawCandles = GetBitfinexCandles("15m", securityName, count, start, end);
                        newCandles = TransformCandles(15, tf, rawCandles);
                    }
                    else if (tf == 60 || tf == 120 || tf == 240)
                    {
                        // building candles from 1 hour / строим свечи из часовиков
                        var rawCandles = GetBitfinexCandles("1h", securityName, count, start, end);
                        newCandles = TransformCandles(60, tf, rawCandles);
                    }
                    else if (tf == 1440)
                    {
                        // building candles from 1 day / строим свечи из дневок
                        var rawCandles = GetBitfinexCandles("1D", securityName, count, start, end);

                        List<Candle> daily = new List<Candle>();

                        for (int i = rawCandles.Count - 1; i > 0; i--)
                        {
                            Candle candle = new Candle();
                            candle.TimeStart = new DateTime(1970, 1, 1) + TimeSpan.FromMilliseconds(rawCandles[i][0]);
                            candle.Open = Convert.ToDecimal(rawCandles[i][1]);
                            candle.Close = Convert.ToDecimal(rawCandles[i][2]);
                            candle.High = Convert.ToDecimal(rawCandles[i][3]);
                            candle.Low = Convert.ToDecimal(rawCandles[i][4]);
                            candle.Volume = Convert.ToDecimal(rawCandles[i][5]);

                            daily.Add(candle);
                        }

                        newCandles = daily;
                    }


                    return newCandles;
                }
            }
            catch (Exception error)
            {
                SendLogMessage(error.ToString(), LogMessageType.Error);
                return null;
            }
        }

19 View Source File : WorkSheet.cs
License : Apache License 2.0
Project Creator : Appdynamics

public void StyleFill()
        {
            var ws = _pck.Workbook.Worksheets.Add("Fills");
            ws.Cells["A1:C3"].Style.Fill.Gradient.Type = ExcelFillGradientType.Linear;
            ws.Cells["A1:C3"].Style.Fill.Gradient.Color1.SetColor(Color.Red);
            ws.Cells["A1:C3"].Style.Fill.Gradient.Color2.SetColor(Color.Blue);

            ws.Cells["J20:J23"].Style.Fill.PatternType = ExcelFillStyle.Solid;
            ws.Cells["J20:J23"].Style.Fill.BackgroundColor.SetColor(0xFF,0x00,0XFF,0x00); //Green

            ws.Cells["A1"].Style.Fill.PatternType = ExcelFillStyle.MediumGray;
            ws.Cells["A1"].Style.Fill.BackgroundColor.SetColor(Color.ForestGreen);
            var r = ws.Cells["A2:A3"];
            r.Style.Fill.Gradient.Type = ExcelFillGradientType.Path;
            r.Style.Fill.Gradient.Left = 0.7;
            r.Style.Fill.Gradient.Right = 0.7;
            r.Style.Fill.Gradient.Top = 0.7;
            r.Style.Fill.Gradient.Bottom = 0.7;

            ws.Cells[4, 1, 4, 360].Style.Fill.Gradient.Type = ExcelFillGradientType.Path;

            for (double col = 1; col < 360; col++)
            {
                r = ws.Cells[4, Convert.ToInt32(col)];
                r.Style.Fill.Gradient.Degree = col;
                r.Style.Fill.Gradient.Left = col / 360;
                r.Style.Fill.Gradient.Right = col / 360;
                r.Style.Fill.Gradient.Top = col / 360;
                r.Style.Fill.Gradient.Bottom = col / 360;
            }
            r = ws.Cells["A5"];
            r.Style.Fill.Gradient.Left = .50;

            ws = _pck.Workbook.Worksheets.Add("FullFills");
            ws.Cells.Style.Fill.Gradient.Left = 0.25;
            ws.Cells["A1"].Value = "test";
            ws.Cells["A1"].RichText.Add("Test rt");
            ws.Cells.AutoFilter = true;
            replacedert.AreNotEqual(ws.Cells["A1:D5"].Value, null);
        }

19 View Source File : CreatePersonalAccessTokenService.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public async Task<string> CreatePersonalAccessTokenAsync(HttpContext context,
            bool isRefenceToken,
            int lifetimeDays,
            IEnumerable<string> apis, 
            IEnumerable<string> scopes, 
            IEnumerable<string> claimTypes)
        {
            CheckParams(apis);

            scopes ??= Array.Empty<string>();
            claimTypes ??= Array.Empty<string>();

            claimTypes = claimTypes.Where(c => c != JwtClaimTypes.Name &&
                c != JwtClaimTypes.ClientId &&
                c != JwtClaimTypes.Subject);

            var user = new ClaimsPrincipal(new ClaimsIdenreplacedy(context.User.Claims.Select(c =>
            {
                if (JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.TryGetValue(c.Type, out string newType))
                {
                    return new Claim(newType, c.Value);
                }
                return c;
            }), "Bearer", JwtClaimTypes.Name, JwtClaimTypes.Role));

            var clientId = user.Claims.First(c => c.Type == JwtClaimTypes.ClientId).Value;
            await ValidateRequestAsync(apis, scopes, user, clientId).ConfigureAwait(false);

            var issuer = context.GetIdenreplacedyServerIssuerUri();
            var sub = user.FindFirstValue(JwtClaimTypes.Subject) ?? user.FindFirstValue("nameid");
            var userName = user.Idenreplacedy.Name;

            return await _tokenService.CreateSecurityTokenAsync(new Token(IdenreplacedyServerConstants.TokenTypes.AccessToken)
            {
                AccessTokenType = isRefenceToken ? AccessTokenType.Reference : AccessTokenType.Jwt,
                Audiences = apis.ToArray(),
                ClientId = clientId,
                Claims = user.Claims.Where(c => claimTypes.Any(t => c.Type == t))
                    .Concat(new[]
                    {
                        new Claim(JwtClaimTypes.Name, userName),
                        new Claim(JwtClaimTypes.ClientId, clientId),
                        new Claim(JwtClaimTypes.Subject, sub)
                    })
                    .Concat(scopes.Select(s => new Claim("scope", s)))
                    .ToArray(),
                CreationTime = DateTime.UtcNow,
                Lifetime = Convert.ToInt32(TimeSpan.FromDays(lifetimeDays).TotalSeconds),
                Issuer = issuer
            });
        }

19 View Source File : WindowsTabControls.cs
License : MIT License
Project Creator : arsium

public static int GetStringWidth(string strSource, System.Drawing.Graphics g, System.Drawing.Font font)
		{
			string[] strs = strSource.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
			float fltWidth = 0;
			foreach (var item in strs)
			{
				System.Drawing.SizeF sizeF = g.MeasureString(strSource.Replace(" ", "A"), font);
				if (sizeF.Width > fltWidth)
				{
					fltWidth = sizeF.Width;
				}
			}

			return Convert.ToInt32(Math.Truncate(fltWidth));
		}

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

public List<Candle> GetCandleHistory(string nameSec, TimeSpan interval)
        {
            int oldInterval = Convert.ToInt32(interval.TotalSeconds);
            var diff = new TimeSpan(0, (int)(interval.TotalMinutes * CandlesDownloadLimit), 0);
            return GetCandles(oldInterval, nameSec, DateTime.Now - diff, DateTime.Now);
        }

19 View Source File : DateTimeExtension.cs
License : MIT License
Project Creator : ASF-Framework

public static int ToUnixTime32(this DateTime date)
        {
            var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            return Convert.ToInt32((date.ToUniversalTime() - epoch).TotalSeconds);
        }

19 View Source File : ResourceTokenBrokerService.cs
License : MIT License
Project Creator : 1iveowl

private async Task<IResourcePermission> GetOrCreateUserPermission(
            User user, 
            string userId,
            IPermissionScope permissionScope,
            CancellationToken ct)
        {
            var permissionId = userId.ToPermissionIdBy(permissionScope.Scope);

            try
            {
                var permission = user.GetPermission(permissionId);

                var permissionResponse = await permission.ReadAsync(
                    Convert.ToInt32(_resourceTokenTtl.TotalSeconds),
                    cancellationToken: ct);

                // If the permission does not exist, then create it.
                // Now sure if this statement is necessary, as an CosmosException is likely thrown if the Permission.ReadAsync fails:
                // however the doreplacedentation is not 100 % clear on this: https://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.cosmos.permission.readasync?view=azure-dotnet
                if (permissionResponse?.StatusCode != HttpStatusCode.OK 
                    || permissionResponse?.Resource?.ResourceParreplacedionKey.GetValueOrDefault() is null)
                {
                    return await UpsertPermission(user, userId, permissionId, permissionScope, ct);
                }

                // If the permission is wrongly configured, update it.
                if (permissionResponse?.Resource?.ResourceParreplacedionKey.ToParreplacedionKeyString() !=
                    userId.ToParreplacedionKeyBy(permissionScope.PermissionMode))
                {
                    return await UpsertPermission(user, userId, permissionId, permissionScope, ct);
                }

                var expiresUtc = DateTime.UtcNow + _resourceTokenTtl;

                var parreplacedionKeyValueJson = permissionResponse.Resource.ResourceParreplacedionKey.GetValueOrDefault().ToString();

                string parreplacedionKeyValue;

                try
                {
                    parreplacedionKeyValue = JArray.Parse(parreplacedionKeyValueJson)?.FirstOrDefault()?.Value<string>();

                    if (string.IsNullOrEmpty(parreplacedionKeyValue))
                    {
                        throw new ArgumentNullException(parreplacedionKeyValue);
                    }
                }
                catch (Exception ex)
                {
                    throw new ResourceTokenBrokerServiceException($"Unable to parse parreplacedion key from existing permission: {permissionId}. Unhandled exception: {ex}");
                }

                return new ResourcePermission(
                    permissionScope,
                    permissionResponse.Resource.Token,
                    permissionResponse.Resource.Id,
                    parreplacedionKeyValue,
                    expiresUtc);
            }
            catch (CosmosException ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    return await UpsertPermission(user, userId, permissionId, permissionScope, ct);
                }

                throw new ResourceTokenBrokerServiceException($"Unable to read or create user permissions. Unhandled exception: {ex}");
            }
        }

19 View Source File : DateTimeExtensions.cs
License : GNU General Public License v3.0
Project Creator : asimmon

private static string MonthsAgo(TimeSpan ts)
        {
            var months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
            return months <= 1 ? "one month ago" : months + " months ago";
        }

19 View Source File : LicenseInfo.cs
License : Apache License 2.0
Project Creator : Algoryx

public bool IsAboutToBeExpired( int days )
    {
      var diff = EndDate - DateTime.Now;
      return Convert.ToInt32( diff.TotalDays + 0.5 ) < days;
    }

19 View Source File : BrowserDeviceAccessor.cs
License : MIT License
Project Creator : aguang-xyz

public async Task<int> GetCurrentTimeAsync()
        {
            return Convert.ToInt32(1000 * await InvokeAsync<double>("getCurrentTime"));
        }

19 View Source File : DbQuery.cs
License : Apache License 2.0
Project Creator : 1448376744

private string ResolveUpdate()
        {
            var table = GetTableMetaInfo().TableName;
            var builder = new StringBuilder();
            if (_setExpressions.Count > 0)
            {
                var where = ResolveWhere();
                foreach (var item in _setExpressions)
                {
                    var column = new BooleanExpressionResovle(item.Column).Resovle();
                    var expression = new BooleanExpressionResovle(item.Expression, _parameters).Resovle();
                    builder.Append($"{column} = {expression},");
                }
                var sql = $"UPDATE {table} SET {builder.ToString().Trim(',')}{where}";
                return sql;
            }
            else
            {
                var filters = new GroupExpressionResovle(_filterExpression).Resovle().Split(',');
                var where = ResolveWhere();
                var columns = GetColumnMetaInfos();
                var updcolumns = columns
                    .Where(a => !filters.Contains(a.ColumnName))
                    .Where(a => !a.IsComplexType)
                    .Where(a => !a.IsIdenreplacedy && !a.IsPrimaryKey && !a.IsNotMapped)
                    .Where(a => !a.IsConcurrencyCheck)
                    .Select(s => $"{s.ColumnName} = @{s.CsharpName}");
                if (string.IsNullOrEmpty(where))
                {
                    var primaryKey = columns.Where(a => a.IsPrimaryKey).FirstOrDefault()
                        ?? columns.First();
                    where = $" WHERE {primaryKey.ColumnName} = @{primaryKey.CsharpName}";
                    if (columns.Exists(a => a.IsConcurrencyCheck))
                    {
                        var checkColumn = columns.Where(a => a.IsConcurrencyCheck).FirstOrDefault();
                        where += $" AND {checkColumn.ColumnName} = @{checkColumn.CsharpName}";
                    }
                }
                var sql = $"UPDATE {table} SET {string.Join(",", updcolumns)}";
                if (columns.Exists(a => a.IsConcurrencyCheck))
                {
                    var checkColumn = columns.Where(a => a.IsConcurrencyCheck).FirstOrDefault();
                    sql += $",{checkColumn.ColumnName} = @New{checkColumn.CsharpName}";
                    if (checkColumn.CsharpType.IsValueType)
                    {
                        var version = Convert.ToInt32((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds);
                        _parameters.Add($"New{checkColumn.CsharpName}", version);
                    }
                    else
                    {
                        var version = Guid.NewGuid().ToString("N");
                        _parameters.Add($"New{checkColumn.CsharpName}", version);
                    }
                }
                sql += where;
                return sql;
            }
        }

19 View Source File : ResourceTokenBrokerService.cs
License : MIT License
Project Creator : 1iveowl

private async Task<IResourcePermission> UpsertPermission(
            User user,
            string userId,
            string permissionId,
            IPermissionScope permissionScope,
            CancellationToken ct)
        {
            try
            {
                var parreplacedionKeyValue = userId.ToParreplacedionKeyBy(permissionScope.PermissionMode);

                var parreplacedionKey = new ParreplacedionKey(parreplacedionKeyValue);

                var permissionProperties = new PermissionProperties(
                    permissionId,
                    permissionScope.PermissionMode.ToCosmosPermissionMode(),
                    _container,
                    parreplacedionKey);

                var expiresUtc = DateTime.UtcNow + _resourceTokenTtl;

                var permissionResponse = await user.UpsertPermissionAsync(
                    permissionProperties,
                    Convert.ToInt32(_resourceTokenTtl.TotalSeconds),
                    cancellationToken: ct);

                if (permissionResponse?.StatusCode == HttpStatusCode.OK
                    || permissionResponse?.StatusCode == HttpStatusCode.Created)
                {
                    if (!string.IsNullOrEmpty(permissionResponse?.Resource?.Token)
                        && !string.IsNullOrEmpty(permissionResponse?.Resource?.Id))
                    {
                        return new ResourcePermission(
                            permissionScope,
                            permissionResponse.Resource.Token,
                            permissionResponse.Resource.Id,
                            parreplacedionKeyValue,
                            expiresUtc);
                    }
                }

                throw new ResourceTokenBrokerServiceException($"Unable to upsert permission for user. Token or Id is missing or invalid. Status code: {permissionResponse?.StatusCode}");
            }
            catch (Exception ex)
            {
                throw new ResourceTokenBrokerServiceException($"Unable to upsert new permission for user. Unhandled exception: {ex}");
            }
        }

19 View Source File : MainControl.xaml.cs
License : MIT License
Project Creator : Actipro

private static TimeAggregatedDataGenerator CreateIntegerDataGenerator(Trend trend, Random rand) {
			var generator = new TimeAggregatedDataGenerator() { 
				DataPointCount = 12, 
				StartAmount = 100000 + Convert.ToInt32(400000 * rand.NextDouble()), 
				StepRange = 30000, 
				Trend = trend 
			};
			generator.Generate();
			return generator;
		}

19 View Source File : MagicLaboratory.cs
License : MIT License
Project Creator : alaabenfatma

public static string RandomString(int size)
        {
            var builder = new StringBuilder();
            char ch;
            for (var i = 0; i < size; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }

            return builder.ToString();
        }

19 View Source File : SystemMenuManager.cs
License : Apache License 2.0
Project Creator : AnkiUniversal

public static void ShowMenu(Window targetWindow, Point menuLocation)
        {
            if (targetWindow == null)
                throw new ArgumentNullException("TargetWindow is null.");

            int x, y;

            try
            {
                x = Convert.ToInt32(menuLocation.X);
                y = Convert.ToInt32(menuLocation.Y);
            }
            catch (OverflowException)
            {
                x = 0;
                y = 0;
            }

            uint WM_SYSCOMMAND = 0x112, TPM_LEFTALIGN = 0x0000, TPM_RETURNCMD = 0x0100;           

            IntPtr window = new WindowInteropHelper(targetWindow).Handle;

            IntPtr wMenu = NativeMethods.GetSystemMenu(window, false);

            int command = NativeMethods.TrackPopupMenuEx(wMenu, TPM_LEFTALIGN | TPM_RETURNCMD, x, y, window, IntPtr.Zero);

            if (command == 0)
                return;

            NativeMethods.PostMessage(window, WM_SYSCOMMAND, new IntPtr(command), IntPtr.Zero);
        }

See More Examples