System.Math.Min(int, int)

Here are the examples of the csharp api System.Math.Min(int, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

7133 Examples 7

19 View Source File : VirtualizingWrapPanel .cs
License : MIT License
Project Creator : 944095635

private ItemLayoutInfo GetLayoutInfo(Size availableSize, double itemHeight, ExtentInfo extentInfo)
        {
            if (_itemsControl == null)
            {
                return new ItemLayoutInfo();
            }

            // we need to ensure that there is one realized item prior to the first visible item, and one after the last visible item,
            // so that keyboard navigation works properly. For example, when focus is on the first visible item, and the user
            // navigates up, the ListBox selects the previous item, and the scrolls that into view - and this triggers the loading of the rest of the items 
            // in that row

            var firstVisibleLine = (int)Math.Floor(VerticalOffset / itemHeight);

            var firstRealizedIndex = Math.Max(extentInfo.ItemsPerLine * firstVisibleLine - 1, 0);
            var firstRealizedItemLeft = firstRealizedIndex % extentInfo.ItemsPerLine * ItemWidth - HorizontalOffset;
            // ReSharper disable once PossibleLossOfFraction
            var firstRealizedItemTop = firstRealizedIndex / extentInfo.ItemsPerLine * itemHeight - VerticalOffset;

            var firstCompleteLineTop = (firstVisibleLine == 0 ? firstRealizedItemTop : firstRealizedItemTop + ItemHeight);
            var completeRealizedLines = (int)Math.Ceiling((availableSize.Height - firstCompleteLineTop) / itemHeight);

            var lastRealizedIndex = Math.Min(firstRealizedIndex + completeRealizedLines * extentInfo.ItemsPerLine + 2, _itemsControl.Items.Count - 1);

            return new ItemLayoutInfo
            {
                FirstRealizedItemIndex = firstRealizedIndex,
                FirstRealizedItemLeft = firstRealizedItemLeft,
                FirstRealizedLineTop = firstRealizedItemTop,
                LastRealizedItemIndex = lastRealizedIndex,
            };
        }

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

internal void WriteTo(RichTextWriter writer, int startOffset, int endOffset)
		{
			if (writer == null)
				throw new ArgumentNullException("writer");
			int doreplacedentLineStartOffset = this.DoreplacedentLine.Offset;
			int doreplacedentLineEndOffset = doreplacedentLineStartOffset + this.DoreplacedentLine.Length;
			if (startOffset < doreplacedentLineStartOffset || startOffset > doreplacedentLineEndOffset)
				throw new ArgumentOutOfRangeException("startOffset", startOffset, "Value must be between " + doreplacedentLineStartOffset + " and " + doreplacedentLineEndOffset);
			if (endOffset < startOffset || endOffset > doreplacedentLineEndOffset)
				throw new ArgumentOutOfRangeException("endOffset", endOffset, "Value must be between startOffset and " + doreplacedentLineEndOffset);
			ISegment requestedSegment = new SimpleSegment(startOffset, endOffset - startOffset);

			List<HtmlElement> elements = new List<HtmlElement>();
			for (int i = 0; i < this.Sections.Count; i++) {
				HighlightedSection s = this.Sections[i];
				if (SimpleSegment.GetOverlap(s, requestedSegment).Length > 0) {
					elements.Add(new HtmlElement(s.Offset, i, false, s.Color));
					elements.Add(new HtmlElement(s.Offset + s.Length, i, true, s.Color));
				}
			}
			elements.Sort();

			IDoreplacedent doreplacedent = this.Doreplacedent;
			int textOffset = startOffset;
			foreach (HtmlElement e in elements) {
				int newOffset = Math.Min(e.Offset, endOffset);
				if (newOffset > startOffset) {
					doreplacedent.WriteTextTo(writer, textOffset, newOffset - textOffset);
				}
				textOffset = Math.Max(textOffset, newOffset);
				if (e.IsEnd)
					writer.EndSpan();
				else
					writer.BeginSpan(e.Color);
			}
			doreplacedent.WriteTextTo(writer, textOffset, endOffset - textOffset);
		}

19 View Source File : bidiagonal.cs
License : MIT License
Project Creator : 1CM69

public static void unpackqfrombidiagonal(ref double[,] qp, int m, int n, ref double[] tauq, int qcolumns, ref double[,] q)
  {
    double[] numArray1 = new double[0];
    double[] numArray2 = new double[0];
    if (m == 0 | n == 0 | qcolumns == 0)
      return;
    q = new double[m + 1, qcolumns + 1];
    double[] v = new double[m + 1];
    double[] work = new double[qcolumns + 1];
    for (int index1 = 1; index1 <= m; ++index1)
    {
      for (int index2 = 1; index2 <= qcolumns; ++index2)
        q[index1, index2] = index1 != index2 ? 0.0 : 1.0;
    }
    if (m >= n)
    {
      for (int m1 = Math.Min(n, qcolumns); m1 >= 1; --m1)
      {
        int num1 = m - m1 + 1;
        int num2 = m1 - 1;
        for (int index = 1; index <= num1; ++index)
          v[index] = qp[index + num2, m1];
        v[1] = 1.0;
        reflections.applyreflectionfromtheleft(ref q, tauq[m1], ref v, m1, m, 1, qcolumns, ref work);
      }
    }
    else
    {
      for (int index1 = Math.Min(m - 1, qcolumns - 1); index1 >= 1; --index1)
      {
        int num1 = m - index1;
        int num2 = index1 + 1 - 1;
        for (int index2 = 1; index2 <= num1; ++index2)
          v[index2] = qp[index2 + num2, index1];
        v[1] = 1.0;
        reflections.applyreflectionfromtheleft(ref q, tauq[index1], ref v, index1 + 1, m, 1, qcolumns, ref work);
      }
    }
  }

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

private void SkipImpl(int amountToSkip)
        {
            if (input.CanSeek)
            {
                long previousPosition = input.Position;
                input.Position += amountToSkip;
                if (input.Position != previousPosition + amountToSkip)
                {
                    throw InvalidProtocolBufferException.TruncatedMessage();
                }
            }
            else
            {
                byte[] skipBuffer = new byte[Math.Min(1024, amountToSkip)];
                while (amountToSkip > 0)
                {
                    int bytesRead = input.Read(skipBuffer, 0, Math.Min(skipBuffer.Length, amountToSkip));
                    if (bytesRead <= 0)
                    {
                        throw InvalidProtocolBufferException.TruncatedMessage();
                    }
                    amountToSkip -= bytesRead;
                }
            }
        }

19 View Source File : svd.cs
License : MIT License
Project Creator : 1CM69

public static bool svddecomposition(double[,] a, int m, int n, int uneeded, int vtneeded, int additionalmemory, ref double[] w, ref double[,] u, ref double[,] vt)
  {
    double[] tauq = new double[0];
    double[] taup = new double[0];
    double[] tau = new double[0];
    double[] e = new double[0];
    double[] numArray1 = new double[0];
    double[,] numArray2 = new double[0, 0];
    bool isupper = false;
    a = (double[,]) a.Clone();
    bool flag1 = true;
    if (m == 0 | n == 0)
      return flag1;
    int num1 = Math.Min(m, n);
    w = new double[num1 + 1];
    int num2 = 0;
    int num3 = 0;
    if (uneeded == 1)
    {
      num3 = m;
      num2 = num1;
      u = new double[num3 + 1, num2 + 1];
    }
    if (uneeded == 2)
    {
      num3 = m;
      num2 = m;
      u = new double[num3 + 1, num2 + 1];
    }
    int num4 = 0;
    int ncvt = 0;
    if (vtneeded == 1)
    {
      num4 = num1;
      ncvt = n;
      vt = new double[num4 + 1, ncvt + 1];
    }
    if (vtneeded == 2)
    {
      num4 = n;
      ncvt = n;
      vt = new double[num4 + 1, ncvt + 1];
    }
    if ((double) m > 1.6 * (double) n)
    {
      if (uneeded == 0)
      {
        qr.qrdecomposition(ref a, m, n, ref tau);
        for (int index1 = 2; index1 <= n; ++index1)
        {
          for (int index2 = 1; index2 <= index1 - 1; ++index2)
            a[index1, index2] = 0.0;
        }
        bidiagonal.tobidiagonal(ref a, n, n, ref tauq, ref taup);
        bidiagonal.unpackptfrombidiagonal(ref a, n, n, ref taup, num4, ref vt);
        bidiagonal.unpackdiagonalsfrombidiagonal(ref a, n, n, ref isupper, ref w, ref e);
        return bdsvd.bidiagonalsvddecomposition(ref w, e, n, isupper, false, ref u, 0, ref a, 0, ref vt, ncvt);
      }
      qr.qrdecomposition(ref a, m, n, ref tau);
      qr.unpackqfromqr(ref a, m, n, ref tau, num2, ref u);
      for (int index1 = 2; index1 <= n; ++index1)
      {
        for (int index2 = 1; index2 <= index1 - 1; ++index2)
          a[index1, index2] = 0.0;
      }
      bidiagonal.tobidiagonal(ref a, n, n, ref tauq, ref taup);
      bidiagonal.unpackptfrombidiagonal(ref a, n, n, ref taup, num4, ref vt);
      bidiagonal.unpackdiagonalsfrombidiagonal(ref a, n, n, ref isupper, ref w, ref e);
      bool flag2;
      if (additionalmemory < 1)
      {
        bidiagonal.multiplybyqfrombidiagonal(ref a, n, n, ref tauq, ref u, m, n, true, false);
        flag2 = bdsvd.bidiagonalsvddecomposition(ref w, e, n, isupper, false, ref u, m, ref a, 0, ref vt, ncvt);
      }
      else
      {
        double[] work = new double[Math.Max(m, n) + 1];
        bidiagonal.unpackqfrombidiagonal(ref a, n, n, ref tauq, n, ref numArray2);
        blas.copymatrix(ref u, 1, m, 1, n, ref a, 1, m, 1, n);
        blas.inplacetranspose(ref numArray2, 1, n, 1, n, ref work);
        flag2 = bdsvd.bidiagonalsvddecomposition(ref w, e, n, isupper, false, ref u, 0, ref numArray2, n, ref vt, ncvt);
        blas.matrixmatrixmultiply(ref a, 1, m, 1, n, false, ref numArray2, 1, n, 1, n, true, 1.0, ref u, 1, m, 1, n, 0.0, ref work);
      }
      return flag2;
    }
    if ((double) n > 1.6 * (double) m)
    {
      if (vtneeded == 0)
      {
        lq.lqdecomposition(ref a, m, n, ref tau);
        for (int index1 = 1; index1 <= m - 1; ++index1)
        {
          for (int index2 = index1 + 1; index2 <= m; ++index2)
            a[index1, index2] = 0.0;
        }
        bidiagonal.tobidiagonal(ref a, m, m, ref tauq, ref taup);
        bidiagonal.unpackqfrombidiagonal(ref a, m, m, ref tauq, num2, ref u);
        bidiagonal.unpackdiagonalsfrombidiagonal(ref a, m, m, ref isupper, ref w, ref e);
        double[] work = new double[m + 1];
        blas.inplacetranspose(ref u, 1, num3, 1, num2, ref work);
        bool flag2 = bdsvd.bidiagonalsvddecomposition(ref w, e, m, isupper, false, ref a, 0, ref u, num3, ref vt, 0);
        blas.inplacetranspose(ref u, 1, num3, 1, num2, ref work);
        return flag2;
      }
      lq.lqdecomposition(ref a, m, n, ref tau);
      lq.unpackqfromlq(ref a, m, n, ref tau, num4, ref vt);
      for (int index1 = 1; index1 <= m - 1; ++index1)
      {
        for (int index2 = index1 + 1; index2 <= m; ++index2)
          a[index1, index2] = 0.0;
      }
      bidiagonal.tobidiagonal(ref a, m, m, ref tauq, ref taup);
      bidiagonal.unpackqfrombidiagonal(ref a, m, m, ref tauq, num2, ref u);
      bidiagonal.unpackdiagonalsfrombidiagonal(ref a, m, m, ref isupper, ref w, ref e);
      double[] work1 = new double[Math.Max(m, n) + 1];
      blas.inplacetranspose(ref u, 1, num3, 1, num2, ref work1);
      bool flag3;
      if (additionalmemory < 1)
      {
        bidiagonal.multiplybypfrombidiagonal(ref a, m, m, ref taup, ref vt, m, n, false, true);
        flag3 = bdsvd.bidiagonalsvddecomposition(ref w, e, m, isupper, false, ref a, 0, ref u, num3, ref vt, n);
      }
      else
      {
        bidiagonal.unpackptfrombidiagonal(ref a, m, m, ref taup, m, ref numArray2);
        flag3 = bdsvd.bidiagonalsvddecomposition(ref w, e, m, isupper, false, ref a, 0, ref u, num3, ref numArray2, m);
        blas.copymatrix(ref vt, 1, m, 1, n, ref a, 1, m, 1, n);
        blas.matrixmatrixmultiply(ref numArray2, 1, m, 1, m, false, ref a, 1, m, 1, n, false, 1.0, ref vt, 1, m, 1, n, 0.0, ref work1);
      }
      blas.inplacetranspose(ref u, 1, num3, 1, num2, ref work1);
      return flag3;
    }
    if (m <= n)
    {
      bidiagonal.tobidiagonal(ref a, m, n, ref tauq, ref taup);
      bidiagonal.unpackqfrombidiagonal(ref a, m, n, ref tauq, num2, ref u);
      bidiagonal.unpackptfrombidiagonal(ref a, m, n, ref taup, num4, ref vt);
      bidiagonal.unpackdiagonalsfrombidiagonal(ref a, m, n, ref isupper, ref w, ref e);
      double[] work = new double[m + 1];
      blas.inplacetranspose(ref u, 1, num3, 1, num2, ref work);
      bool flag2 = bdsvd.bidiagonalsvddecomposition(ref w, e, num1, isupper, false, ref a, 0, ref u, num3, ref vt, ncvt);
      blas.inplacetranspose(ref u, 1, num3, 1, num2, ref work);
      return flag2;
    }
    bidiagonal.tobidiagonal(ref a, m, n, ref tauq, ref taup);
    bidiagonal.unpackqfrombidiagonal(ref a, m, n, ref tauq, num2, ref u);
    bidiagonal.unpackptfrombidiagonal(ref a, m, n, ref taup, num4, ref vt);
    bidiagonal.unpackdiagonalsfrombidiagonal(ref a, m, n, ref isupper, ref w, ref e);
    bool flag4;
    if (additionalmemory < 2 | uneeded == 0)
    {
      flag4 = bdsvd.bidiagonalsvddecomposition(ref w, e, num1, isupper, false, ref u, num3, ref a, 0, ref vt, ncvt);
    }
    else
    {
      double[,] numArray3 = new double[num1 + 1, m + 1];
      blas.copyandtranspose(ref u, 1, m, 1, num1, ref numArray3, 1, num1, 1, m);
      flag4 = bdsvd.bidiagonalsvddecomposition(ref w, e, num1, isupper, false, ref u, 0, ref numArray3, m, ref vt, ncvt);
      blas.copyandtranspose(ref numArray3, 1, num1, 1, m, ref u, 1, m, 1, num1);
    }
    return flag4;
  }

19 View Source File : svd.cs
License : MIT License
Project Creator : 1CM69

public static bool rmatrixsvd(double[,] a, int m, int n, int uneeded, int vtneeded, int additionalmemory, ref double[] w, ref double[,] u, ref double[,] vt)
  {
    double[] tauq = new double[0];
    double[] taup = new double[0];
    double[] tau = new double[0];
    double[] e = new double[0];
    double[] numArray1 = new double[0];
    double[,] numArray2 = new double[0, 0];
    bool isupper = false;
    a = (double[,]) a.Clone();
    bool flag1 = true;
    if (m == 0 | n == 0)
      return flag1;
    int n1 = Math.Min(m, n);
    w = new double[n1 + 1];
    int qcolumns = 0;
    int num1 = 0;
    if (uneeded == 1)
    {
      num1 = m;
      qcolumns = n1;
      u = new double[num1 - 1 + 1, qcolumns - 1 + 1];
    }
    if (uneeded == 2)
    {
      num1 = m;
      qcolumns = m;
      u = new double[num1 - 1 + 1, qcolumns - 1 + 1];
    }
    int num2 = 0;
    int ncvt = 0;
    if (vtneeded == 1)
    {
      num2 = n1;
      ncvt = n;
      vt = new double[num2 - 1 + 1, ncvt - 1 + 1];
    }
    if (vtneeded == 2)
    {
      num2 = n;
      ncvt = n;
      vt = new double[num2 - 1 + 1, ncvt - 1 + 1];
    }
    if ((double) m > 1.6 * (double) n)
    {
      if (uneeded == 0)
      {
        qr.rmatrixqr(ref a, m, n, ref tau);
        for (int index1 = 0; index1 <= n - 1; ++index1)
        {
          for (int index2 = 0; index2 <= index1 - 1; ++index2)
            a[index1, index2] = 0.0;
        }
        bidiagonal.rmatrixbd(ref a, n, n, ref tauq, ref taup);
        bidiagonal.rmatrixbdunpackpt(ref a, n, n, ref taup, num2, ref vt);
        bidiagonal.rmatrixbdunpackdiagonals(ref a, n, n, ref isupper, ref w, ref e);
        return bdsvd.rmatrixbdsvd(ref w, e, n, isupper, false, ref u, 0, ref a, 0, ref vt, ncvt);
      }
      qr.rmatrixqr(ref a, m, n, ref tau);
      qr.rmatrixqrunpackq(ref a, m, n, ref tau, qcolumns, ref u);
      for (int index1 = 0; index1 <= n - 1; ++index1)
      {
        for (int index2 = 0; index2 <= index1 - 1; ++index2)
          a[index1, index2] = 0.0;
      }
      bidiagonal.rmatrixbd(ref a, n, n, ref tauq, ref taup);
      bidiagonal.rmatrixbdunpackpt(ref a, n, n, ref taup, num2, ref vt);
      bidiagonal.rmatrixbdunpackdiagonals(ref a, n, n, ref isupper, ref w, ref e);
      bool flag2;
      if (additionalmemory < 1)
      {
        bidiagonal.rmatrixbdmultiplybyq(ref a, n, n, ref tauq, ref u, m, n, true, false);
        flag2 = bdsvd.rmatrixbdsvd(ref w, e, n, isupper, false, ref u, m, ref a, 0, ref vt, ncvt);
      }
      else
      {
        double[] work = new double[Math.Max(m, n) + 1];
        bidiagonal.rmatrixbdunpackq(ref a, n, n, ref tauq, n, ref numArray2);
        blas.copymatrix(ref u, 0, m - 1, 0, n - 1, ref a, 0, m - 1, 0, n - 1);
        blas.inplacetranspose(ref numArray2, 0, n - 1, 0, n - 1, ref work);
        flag2 = bdsvd.rmatrixbdsvd(ref w, e, n, isupper, false, ref u, 0, ref numArray2, n, ref vt, ncvt);
        blas.matrixmatrixmultiply(ref a, 0, m - 1, 0, n - 1, false, ref numArray2, 0, n - 1, 0, n - 1, true, 1.0, ref u, 0, m - 1, 0, n - 1, 0.0, ref work);
      }
      return flag2;
    }
    if ((double) n > 1.6 * (double) m)
    {
      if (vtneeded == 0)
      {
        lq.rmatrixlq(ref a, m, n, ref tau);
        for (int index1 = 0; index1 <= m - 1; ++index1)
        {
          for (int index2 = index1 + 1; index2 <= m - 1; ++index2)
            a[index1, index2] = 0.0;
        }
        bidiagonal.rmatrixbd(ref a, m, m, ref tauq, ref taup);
        bidiagonal.rmatrixbdunpackq(ref a, m, m, ref tauq, qcolumns, ref u);
        bidiagonal.rmatrixbdunpackdiagonals(ref a, m, m, ref isupper, ref w, ref e);
        double[] work = new double[m + 1];
        blas.inplacetranspose(ref u, 0, num1 - 1, 0, qcolumns - 1, ref work);
        bool flag2 = bdsvd.rmatrixbdsvd(ref w, e, m, isupper, false, ref a, 0, ref u, num1, ref vt, 0);
        blas.inplacetranspose(ref u, 0, num1 - 1, 0, qcolumns - 1, ref work);
        return flag2;
      }
      lq.rmatrixlq(ref a, m, n, ref tau);
      lq.rmatrixlqunpackq(ref a, m, n, ref tau, num2, ref vt);
      for (int index1 = 0; index1 <= m - 1; ++index1)
      {
        for (int index2 = index1 + 1; index2 <= m - 1; ++index2)
          a[index1, index2] = 0.0;
      }
      bidiagonal.rmatrixbd(ref a, m, m, ref tauq, ref taup);
      bidiagonal.rmatrixbdunpackq(ref a, m, m, ref tauq, qcolumns, ref u);
      bidiagonal.rmatrixbdunpackdiagonals(ref a, m, m, ref isupper, ref w, ref e);
      double[] work1 = new double[Math.Max(m, n) + 1];
      blas.inplacetranspose(ref u, 0, num1 - 1, 0, qcolumns - 1, ref work1);
      bool flag3;
      if (additionalmemory < 1)
      {
        bidiagonal.rmatrixbdmultiplybyp(ref a, m, m, ref taup, ref vt, m, n, false, true);
        flag3 = bdsvd.rmatrixbdsvd(ref w, e, m, isupper, false, ref a, 0, ref u, num1, ref vt, n);
      }
      else
      {
        bidiagonal.rmatrixbdunpackpt(ref a, m, m, ref taup, m, ref numArray2);
        flag3 = bdsvd.rmatrixbdsvd(ref w, e, m, isupper, false, ref a, 0, ref u, num1, ref numArray2, m);
        blas.copymatrix(ref vt, 0, m - 1, 0, n - 1, ref a, 0, m - 1, 0, n - 1);
        blas.matrixmatrixmultiply(ref numArray2, 0, m - 1, 0, m - 1, false, ref a, 0, m - 1, 0, n - 1, false, 1.0, ref vt, 0, m - 1, 0, n - 1, 0.0, ref work1);
      }
      blas.inplacetranspose(ref u, 0, num1 - 1, 0, qcolumns - 1, ref work1);
      return flag3;
    }
    if (m <= n)
    {
      bidiagonal.rmatrixbd(ref a, m, n, ref tauq, ref taup);
      bidiagonal.rmatrixbdunpackq(ref a, m, n, ref tauq, qcolumns, ref u);
      bidiagonal.rmatrixbdunpackpt(ref a, m, n, ref taup, num2, ref vt);
      bidiagonal.rmatrixbdunpackdiagonals(ref a, m, n, ref isupper, ref w, ref e);
      double[] work = new double[m + 1];
      blas.inplacetranspose(ref u, 0, num1 - 1, 0, qcolumns - 1, ref work);
      bool flag2 = bdsvd.rmatrixbdsvd(ref w, e, n1, isupper, false, ref a, 0, ref u, num1, ref vt, ncvt);
      blas.inplacetranspose(ref u, 0, num1 - 1, 0, qcolumns - 1, ref work);
      return flag2;
    }
    bidiagonal.rmatrixbd(ref a, m, n, ref tauq, ref taup);
    bidiagonal.rmatrixbdunpackq(ref a, m, n, ref tauq, qcolumns, ref u);
    bidiagonal.rmatrixbdunpackpt(ref a, m, n, ref taup, num2, ref vt);
    bidiagonal.rmatrixbdunpackdiagonals(ref a, m, n, ref isupper, ref w, ref e);
    bool flag4;
    if (additionalmemory < 2 | uneeded == 0)
    {
      flag4 = bdsvd.rmatrixbdsvd(ref w, e, n1, isupper, false, ref u, num1, ref a, 0, ref vt, ncvt);
    }
    else
    {
      double[,] numArray3 = new double[n1 - 1 + 1, m - 1 + 1];
      blas.copyandtranspose(ref u, 0, m - 1, 0, n1 - 1, ref numArray3, 0, n1 - 1, 0, m - 1);
      flag4 = bdsvd.rmatrixbdsvd(ref w, e, n1, isupper, false, ref u, 0, ref numArray3, m, ref vt, ncvt);
      blas.copyandtranspose(ref numArray3, 0, n1 - 1, 0, m - 1, ref u, 0, m - 1, 0, n1 - 1);
    }
    return flag4;
  }

19 View Source File : DellFanManagementGuiForm.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

private void TrayIconThread()
        {
            try
            {
                MethodInvoker updateInvoker = new(UpdateTrayIcon);

                while (!_formClosed)
                {
                    int waitTime = 1000; // One second.

                    if (trayIconCheckBox.Checked && animatedCheckBox.Checked)
                    {
                        // Grab state information that we need.
                        uint? averageRpm;
                        if (_state.Fan2Present)
                        {
                            averageRpm = (_state.Fan1Rpm + _state.Fan2Rpm) / 2;
                        }
                        else
                        {
                            averageRpm = _state.Fan1Rpm;
                        }

                        if (averageRpm > 250 && averageRpm < 10000)
                        {
                            try
                            {
                                BeginInvoke(updateInvoker);
                            }
                            catch (Exception)
                            {
                                // If the window handle is not here (not open yet, or closing), there could be an error.
                                // Silently ignore.
                            }

                            // Higher RPM = lower wait time = faster animation.
                            waitTime = 250000 / (int)averageRpm;
                        }
                    }

                    Thread.Sleep(Math.Min(waitTime, 1000));
                }
            }
            catch (Exception exception)
            {
                Log.Write(exception);
            }
        }

19 View Source File : lq.cs
License : MIT License
Project Creator : 1CM69

public static void rmatrixlq(ref double[,] a, int m, int n, ref double[] tau)
  {
    double[] numArray1 = new double[0];
    double[] numArray2 = new double[0];
    double tau1 = 0.0;
    int num1 = Math.Min(m, n);
    Math.Max(m, n);
    double[] work = new double[m + 1];
    double[] numArray3 = new double[n + 1];
    tau = new double[num1 - 1 + 1];
    int num2 = Math.Min(m, n);
    for (int n1 = 0; n1 <= num2 - 1; ++n1)
    {
      int num3 = n1 - 1;
      for (int index = 1; index <= n - n1; ++index)
        numArray3[index] = a[n1, index + num3];
      reflections.generatereflection(ref numArray3, n - n1, ref tau1);
      tau[n1] = tau1;
      int num4 = 1 - n1;
      for (int index = n1; index <= n - 1; ++index)
        a[n1, index] = numArray3[index + num4];
      numArray3[1] = 1.0;
      if (n1 < n)
        reflections.applyreflectionfromtheright(ref a, tau[n1], ref numArray3, n1 + 1, m - 1, n1, n - 1, ref work);
    }
  }

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

public void TransformRange(int index, int length, Func<T, T> converter)
		{
			if (root == null)
				return;
			int endIndex = index + length;
			int pos = index;
			while (pos < endIndex) {
				int endPos = Math.Min(endIndex, GetEndOfRun(pos));
				T oldValue = this[pos];
				T newValue = converter(oldValue);
				SetRange(pos, endPos - pos, newValue);
				pos = endPos;
			}
		}

19 View Source File : lq.cs
License : MIT License
Project Creator : 1CM69

public static void rmatrixlqunpackl(ref double[,] a, int m, int n, ref double[,] l)
  {
    if (m <= 0 | n <= 0)
      return;
    l = new double[m - 1 + 1, n - 1 + 1];
    for (int index = 0; index <= n - 1; ++index)
      l[0, index] = 0.0;
    for (int index1 = 1; index1 <= m - 1; ++index1)
    {
      for (int index2 = 0; index2 <= n - 1; ++index2)
        l[index1, index2] = l[0, index2];
    }
    for (int val1 = 0; val1 <= m - 1; ++val1)
    {
      int num = Math.Min(val1, n - 1);
      for (int index = 0; index <= num; ++index)
        l[val1, index] = a[val1, index];
    }
  }

19 View Source File : MP3FileWriter.cs
License : MIT License
Project Creator : 3wz

public override void Write(byte[] buffer, int offset, int count)
        {
            while (count > 0)
            {
                int blockSize = Math.Min(inBuffer.nBytes - inPosition, count);
                Buffer.BlockCopy(buffer, offset, inBuffer.bytes, inPosition, blockSize);

                inPosition += blockSize;
                count -= blockSize;
                offset += blockSize;

                if (inPosition >= inBuffer.nBytes)
                    Encode();
            }
        }

19 View Source File : RedisClientPool.cs
License : MIT License
Project Creator : 2881099

public static void PrevReheatConnectionPool(ObjectPool<RedisClient> pool, int minPoolSize)
        {
            if (minPoolSize <= 0) minPoolSize = Math.Min(5, pool.Policy.PoolSize);
            if (minPoolSize > pool.Policy.PoolSize) minPoolSize = pool.Policy.PoolSize;
            var initTestOk = true;
            var initStartTime = DateTime.Now;
            var initConns = new ConcurrentBag<Object<RedisClient>>();

            try
            {
                var conn = pool.Get();
                initConns.Add(conn);
                conn.Value.Ping();
            }
            catch (Exception ex)
            {
                initTestOk = false; //预热一次失败,后面将不进行
                pool.SetUnavailable(ex);
            }
            for (var a = 1; initTestOk && a < minPoolSize; a += 10)
            {
                if (initStartTime.Subtract(DateTime.Now).TotalSeconds > 3) break; //预热耗时超过3秒,退出
                var b = Math.Min(minPoolSize - a, 10); //每10个预热
                var initTasks = new Task[b];
                for (var c = 0; c < b; c++)
                {
                    initTasks[c] = TaskEx.Run(() =>
                    {
                        try
                        {
                            var conn = pool.Get();
                            initConns.Add(conn);
                        }
                        catch
                        {
                            initTestOk = false;  //有失败,下一组退出预热
                        }
                    });
                }
                Task.WaitAll(initTasks);
            }
            while (initConns.TryTake(out var conn)) pool.Return(conn);
        }

19 View Source File : qr.cs
License : MIT License
Project Creator : 1CM69

public static void rmatrixqrunpackq(ref double[,] a, int m, int n, ref double[] tau, int qcolumns, ref double[,] q)
  {
    double[] numArray1 = new double[0];
    double[] numArray2 = new double[0];
    if (m <= 0 | n <= 0 | qcolumns <= 0)
      return;
    int num1 = Math.Min(Math.Min(m, n), qcolumns);
    q = new double[m - 1 + 1, qcolumns - 1 + 1];
    double[] v = new double[m + 1];
    double[] work = new double[qcolumns - 1 + 1];
    for (int index1 = 0; index1 <= m - 1; ++index1)
    {
      for (int index2 = 0; index2 <= qcolumns - 1; ++index2)
        q[index1, index2] = index1 != index2 ? 0.0 : 1.0;
    }
    for (int m1 = num1 - 1; m1 >= 0; --m1)
    {
      int num2 = m1 - 1;
      for (int index = 1; index <= m - m1; ++index)
        v[index] = a[index + num2, m1];
      v[1] = 1.0;
      reflections.applyreflectionfromtheleft(ref q, tau[m1], ref v, m1, m - 1, 0, qcolumns - 1, ref work);
    }
  }

19 View Source File : Helpers.cs
License : MIT License
Project Creator : 71

internal static Type FindCommonType(Type a, Type b)
        {
            List<Type> aMap = new List<Type>();
            List<Type> bMap = new List<Type>();

            while (a != typeof(Compilation))
            {
                aMap.Insert(0, a);
                a = a.GetTypeInfo().BaseType;
            }

            while (b != typeof(Compilation))
            {
                bMap.Insert(0, b);
                b = b.GetTypeInfo().BaseType;
            }

            for (int i = 1; i < Math.Min(aMap.Count, bMap.Count); i++)
            {
                if (aMap[i] != bMap[i])
                    return aMap[i - 1];
            }

            return typeof(Compilation);
        }

19 View Source File : qr.cs
License : MIT License
Project Creator : 1CM69

public static void qrdecompositionunpacked(double[,] a, int m, int n, ref double[,] q, ref double[,] r)
  {
    double[] tau = new double[0];
    a = (double[,]) a.Clone();
    int num = Math.Min(m, n);
    if (n <= 0)
      return;
    q = new double[m + 1, m + 1];
    r = new double[m + 1, n + 1];
    qr.qrdecomposition(ref a, m, n, ref tau);
    for (int index = 1; index <= n; ++index)
      r[1, index] = 0.0;
    for (int index1 = 2; index1 <= m; ++index1)
    {
      for (int index2 = 1; index2 <= n; ++index2)
        r[index1, index2] = r[1, index2];
    }
    for (int index1 = 1; index1 <= num; ++index1)
    {
      for (int index2 = index1; index2 <= n; ++index2)
        r[index1, index2] = a[index1, index2];
    }
    qr.unpackqfromqr(ref a, m, n, ref tau, m, ref q);
  }

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

public static Mesh CreateLIBIGLMeshBoolean(Mesh m1_, Mesh m2_, int Difference_Union_Intersection = 0) {
            // return Unsafe.LIBIGL_MeshBoolean_Create(n);


            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //Clean Mesh
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            m1_.Vertices.UseDoublePrecisionVertices = true;
            m2_.Vertices.UseDoublePrecisionVertices = true;
            Mesh m1 = m1_.DuplicateMesh();
            Mesh m2 = m2_.DuplicateMesh();
            m1.Vertices.UseDoublePrecisionVertices = true;
            m2.Vertices.UseDoublePrecisionVertices = true;
            m1.Faces.ConvertQuadsToTriangles();
            m2.Faces.ConvertQuadsToTriangles();

            m1.Vertices.CombineIdentical(true, true);
            m1.Vertices.CullUnused();
            m1.Weld(3.14159265358979);
            m1.FillHoles();
            m1.RebuildNormals();

            m2.Vertices.CombineIdentical(true, true);
            m2.Vertices.CullUnused();
            m2.Weld(3.14159265358979);
            m2.FillHoles();
            m2.RebuildNormals();


            if (!m1.IsValid || !m1.IsClosed || !m2.IsValid || !m2.IsClosed)
                return null;


            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //Send Vertices and Faces to C++
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            double[] ptCoordArr1 = new double[m1.Vertices.Count * 3];
            for (int i = 0; i < m1.Vertices.Count; i++) {
                ptCoordArr1[i * 3 + 0] = m1.Vertices.Point3dAt(i).X;
                ptCoordArr1[i * 3 + 1] = m1.Vertices.Point3dAt(i).Y;
                ptCoordArr1[i * 3 + 2] = m1.Vertices.Point3dAt(i).Z;
            }
            var ptCount1 = (ulong)m1.Vertices.Count;


            int[] facesArr1 = m1.Faces.ToIntArray(true);
            var facesCount1 = (ulong)m1.Faces.Count;


            double[] ptCoordArr2 = new double[m2.Vertices.Count * 3];
            for (int i = 0; i < m2.Vertices.Count; i++) {
                ptCoordArr2[i * 3 + 0] = m2.Vertices.Point3dAt(i).X;
                ptCoordArr2[i * 3 + 1] = m2.Vertices.Point3dAt(i).Y;
                ptCoordArr2[i * 3 + 2] = m2.Vertices.Point3dAt(i).Z;
            }
            var ptCount2 = (ulong)m2.Vertices.Count;

            int[] facesArr2 = m2.Faces.ToIntArray(true);
            var facesCount2 = (ulong)m2.Faces.Count;

            ////Rhino.RhinoApp.WriteLine(ptCoordArr1.Length.ToString() + " " + ptCount1.ToString());
            ////Rhino.RhinoApp.WriteLine(facesArr1.Length.ToString() + " " + facesCount1.ToString());
            ////Rhino.RhinoApp.WriteLine(ptCoordArr2.Length.ToString() + " " + ptCount2.ToString());
            ////Rhino.RhinoApp.WriteLine(facesArr2.Length.ToString() + " " + facesCount2.ToString());



            ////Inputs
            IntPtr vertexCoordPointer = IntPtr.Zero;
            int nVertices = 0;
            IntPtr faceIndicesPointer = IntPtr.Zero;
            int nFaces = 0;

            //Call C++ method
            UnsafeLIBIGL.LIBIGL_MeshBoolean_Create(ptCoordArr1, ptCount1, facesArr1, facesCount1, ptCoordArr2, ptCount2, facesArr2, facesCount2, (ulong)Math.Max(0, Math.Min(Difference_Union_Intersection, 4)), ref vertexCoordPointer, ref nVertices, ref faceIndicesPointer, ref nFaces);




            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //Get Vertices and Faces from C++
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            //Convert faceIndicesPointer to C# int[]
            double[] verticesCoordinates = new double[nVertices * 3];
            Marshal.Copy(vertexCoordPointer, verticesCoordinates, 0, verticesCoordinates.Length);

            int[] faceIndices = new int[nFaces * 3];
            Marshal.Copy(faceIndicesPointer, faceIndices, 0, faceIndices.Length);

            ////Rhino.RhinoApp.WriteLine(verticesCoordinates.Length.ToString()  + " " + nVertices.ToString());
            ////Rhino.RhinoApp.WriteLine(faceIndices.Length.ToString() + " " + nFaces.ToString());



            //Create mesh
            Mesh mesh = new Mesh();
            for (int i = 0; i < verticesCoordinates.Length; i += 3)
                mesh.Vertices.Add(new Point3d(verticesCoordinates[i + 0], verticesCoordinates[i + 1], verticesCoordinates[i + 2]));

            for (int i = 0; i < faceIndices.Length; i += 3) {
                mesh.Faces.AddFace(faceIndices[i + 0], faceIndices[i + 1], faceIndices[i + 2]);
            }

            //mesh.Vertices.Align(0.01);
            mesh.Vertices.CombineIdentical(true, true);
            mesh.Vertices.CullUnused();
            mesh.Weld(3.14159265358979);
            mesh.FillHoles();
            mesh.RebuildNormals();


            //Release memory from output
            UnsafeLIBIGL.ReleaseDouble(vertexCoordPointer, true);
            UnsafeLIBIGL.ReleaseInt(faceIndicesPointer, true);


            return mesh;
        }

19 View Source File : Server.cs
License : MIT License
Project Creator : 1ZouLTReX1

public bool ReceiveOnce()
    {
        /*
         * returns one message in a byte array which then get processed by the client
         * one message may require serveral calls to '.Receive' function.
         */

        // Receive the response from the remote device.
        if (offset >= bytesRec)
        {
            if (SafeReceive(ref buffer, ref bytesRec, ref offset))
                return false;
        }

        len = Globals.DeSerializeLenPrefix(buffer, offset);
        offset += sizeof(int);

        while (len > 0)
        {
            cut = Math.Min(len, bytesRec - offset);
            ms.Write(buffer, offset, cut);
            len -= cut;
            offset += cut;

            if (len > 0)
            {
                // The left over of the previous message.
                if (SafeReceive(ref buffer, ref bytesRec, ref offset))
                    return false;
            }
        }

        // Process one message from the stream.
        data = ms.ToArray();
        // Clear the buffer.
        ms.SetLength(0);

        // Process the new received message.
        ProcessMessage(data);
        return true;
    }

19 View Source File : LogEvent.cs
License : MIT License
Project Creator : Abc-Arbitrage

[MethodImpl(MethodImplOptions.NoInlining)]
        private bool PrepareAppendSlow(int requestedBytes)
        {
            if (_dataPointer + requestedBytes <= _endOfBuffer && _argumentExhaustionStrategy == LogEventArgumentExhaustionStrategy.Allocate)
            {
                var newCapacity = Math.Min(_argPointers.Length * 2, _maxArgCapacity);
                if (newCapacity > _argPointers.Length)
                {
                    Array.Resize(ref _argPointers, newCapacity);
                    Array.Resize(ref _strings, newCapacity);
                    return true;
                }
            }

            _isTruncated = true;
            return false;
        }

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

public static int Clamp(this int amount, int low, int high)
        {
            return Math.Min(high, Math.Max(amount, low));
        }

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

public IEnumerable<HighlightedSection> GetHighlightedSections(int offset, int length)
		{
			int index = GetIndexForOffsetUseExistingSegment(offset);
			int pos = offset;
			int endOffset = offset + length;
			while (pos < endOffset) {
				int endPos = Math.Min(endOffset, GetEnd(index));
				yield return new HighlightedSection {
					Offset = pos,
					Length = endPos - pos,
					Color = stateChanges[index].Clone()
				};
				pos = endPos;
				index++;
			}
		}

19 View Source File : qr.cs
License : MIT License
Project Creator : 1CM69

public static void unpackqfromqr(ref double[,] a, int m, int n, ref double[] tau, int qcolumns, ref double[,] q)
  {
    double[] numArray1 = new double[0];
    double[] numArray2 = new double[0];
    if (m == 0 | n == 0 | qcolumns == 0)
      return;
    int num1 = Math.Min(Math.Min(m, n), qcolumns);
    q = new double[m + 1, qcolumns + 1];
    double[] v = new double[m + 1];
    double[] work = new double[qcolumns + 1];
    for (int index1 = 1; index1 <= m; ++index1)
    {
      for (int index2 = 1; index2 <= qcolumns; ++index2)
        q[index1, index2] = index1 != index2 ? 0.0 : 1.0;
    }
    for (int m1 = num1; m1 >= 1; --m1)
    {
      int num2 = m - m1 + 1;
      int num3 = m1 - 1;
      for (int index = 1; index <= num2; ++index)
        v[index] = a[index + num3, m1];
      v[1] = 1.0;
      reflections.applyreflectionfromtheleft(ref q, tau[m1], ref v, m1, m, 1, qcolumns, ref work);
    }
  }

19 View Source File : Client.cs
License : MIT License
Project Creator : 1ZouLTReX1

public Byte[] ReceiveOnce()
    {
        /*
         * returns one message in a byte array which then get processed by the client
         * one message may require serveral calls to '.Receive' function.
         */

        // Receive the response from the remote device.
        if (offset >= bytesRec)
        {
            if (SafeReceive(ref buffer, ref bytesRec, ref offset))
                return null;
        }

        len = Globals.DeSerializeLenPrefix(buffer, offset);
        offset += sizeof(int);

        while (len > 0)
        {
            cut = Math.Min(len, bytesRec - offset);
            ms.Write(buffer, offset, cut);
            len -= cut;
            offset += cut;

            if (len > 0)
            {
                // The left over of the previous message.
                if (SafeReceive(ref buffer, ref bytesRec, ref offset))
                    return null;
            }
        }

        // Process one message from the stream.
        data = ms.ToArray();
        // Clear the buffer.
        ms.SetLength(0);

        return data;
    }

19 View Source File : Program.cs
License : MIT License
Project Creator : 13xforever

internal static async Task Main(string[] args)
        {
            try
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("Drag .pkg files and/or folders onto this .exe to verify the packages.");
                    var isFirstChar = true;
                    var completedPath = false;
                    var path = new StringBuilder();
                    do
                    {
                        var keyInfo = Console.ReadKey(true);
                        if (isFirstChar)
                        {
                            isFirstChar = false;
                            if (keyInfo.KeyChar != '"')
                                return;
                        }
                        else
                        {
                            if (keyInfo.KeyChar == '"')
                            {
                                completedPath = true;
                                args = new[] {path.ToString()};
                            }
                            else
                                path.Append(keyInfo.KeyChar);
                        }
                    } while (!completedPath);
                    Console.Clear();
                }

                Console.OutputEncoding = new UTF8Encoding(false);
                Console.replacedle = replacedle;
                Console.CursorVisible = false;
                Console.WriteLine("Scanning for PKGs...");
                var pkgList = new List<FileInfo>();
                Console.ForegroundColor = ConsoleColor.Yellow;
                foreach (var item in args)
                {
                    var path = item.Trim('"');
                    if (File.Exists(path))
                        pkgList.Add(new FileInfo(path));
                    else if (Directory.Exists(path))
                        pkgList.AddRange(GetFilePaths(path, "*.pkg", SearchOption.AllDirectories).Select(p => new FileInfo(p)));
                    else
                        Console.WriteLine("Unknown path: " + path);
                }
                Console.ResetColor();
                if (pkgList.Count == 0)
                {
                    Console.WriteLine("No packages were found. Check paths, and try again.");
                    return;
                }

                var longestFilename = Math.Max(pkgList.Max(i => i.Name.Length), HeaderPkgName.Length);
                var sigWidth = Math.Max(HeaderSignature.Length, 8);
                var csumWidth = Math.Max(HeaderChecksum.Length, 5);
                var csumsWidth = 1 + sigWidth + 1 + csumWidth + 1;
                var idealWidth = longestFilename + csumsWidth;
                try
                {
                    if (idealWidth > Console.LargestWindowWidth)
                    {
                        longestFilename = Console.LargestWindowWidth - csumsWidth;
                        idealWidth = Console.LargestWindowWidth;
                    }
                    if (idealWidth > Console.WindowWidth)
                    {
                        Console.BufferWidth = Math.Max(Console.BufferWidth, idealWidth);
                        Console.WindowWidth = idealWidth;
                    }
                    Console.BufferHeight = Math.Max(Console.BufferHeight, Math.Min(9999, pkgList.Count + 10));
                }
                catch (PlatformNotSupportedException) { }
                Console.WriteLine($"{HeaderPkgName.Trim(longestFilename).PadRight(longestFilename)} {HeaderSignature.PadLeft(sigWidth)} {HeaderChecksum.PadLeft(csumWidth)}");
                using var cts = new CancellationTokenSource();
                Console.CancelKeyPress += (sender, eventArgs) => { cts.Cancel(); };
                var t = new Thread(() =>
                                   {
                                       try
                                       {
                                           var indicatorIdx = 0;
                                           while (!cts.Token.IsCancellationRequested)
                                           {
                                               Task.Delay(1000, cts.Token).ConfigureAwait(false).GetAwaiter().GetResult();
                                               if (cts.Token.IsCancellationRequested)
                                                   return;

                                               PkgChecker.Sync.Wait(cts.Token);
                                               try
                                               {
                                                   var frame = Animation[(indicatorIdx++) % Animation.Length];
                                                   var currentProgress = PkgChecker.CurrentFileProcessedBytes;
                                                   Console.replacedle = $"{replacedle} [{(double)(PkgChecker.ProcessedBytes + currentProgress) / PkgChecker.TotalFileSize * 100:0.00}%] {frame}";
                                                   if (PkgChecker.CurrentPadding > 0)
                                                   {
                                                       Console.CursorVisible = false;
                                                       var (top, left) = (Console.CursorTop, Console.CursorLeft);
                                                       Console.Write($"{(double)currentProgress / PkgChecker.CurrentFileSize * 100:0}%".PadLeft(PkgChecker.CurrentPadding));
                                                       Console.CursorTop = top;
                                                       Console.CursorLeft = left;
                                                       Console.CursorVisible = false;
                                                   }
                                               }
                                               finally
                                               {
                                                   PkgChecker.Sync.Release();
                                               }
                                           }
                                       }
                                       catch (TaskCanceledException)
                                       {
                                       }
                                   });
                t.Start();
                await PkgChecker.CheckAsync(pkgList, longestFilename, sigWidth, csumWidth, csumsWidth-2, cts.Token).ConfigureAwait(false);
                cts.Cancel(false);
                t.Join();
            }
            finally
            {
                Console.replacedle = replacedle;
                Console.WriteLine("Press any key to exit");
                Console.ReadKey();
                Console.WriteLine();
                Console.CursorVisible = true;
            }
        }

19 View Source File : RedisReader.cs
License : MIT License
Project Creator : 2881099

public void ReadBulkBytes(Stream destination, int bufferSize, bool checkType = true)
        {
            if (checkType)
                ExpectType(RedisMessage.Bulk);
            int size = (int)ReadInt(false);
            if (size == -1)
                return;

            byte[] buffer = new byte[bufferSize];
            int position = 0;
            while (position < size)
            {
                int bytes_to_buffer = Math.Min(buffer.Length, size - position);
                int bytes_read = 0;
                while (bytes_read < bytes_to_buffer)
                {
                    int bytes_to_read = Math.Min(bytes_to_buffer - bytes_read, size - position);
                    bytes_read += _io.Read(buffer, bytes_read, bytes_to_read);
                }
                position += bytes_read;
                destination.Write(buffer, 0, bytes_read);
            }
            //Console.WriteLine($"ReadBulkBytes2: {Encoding.UTF8.GetString(buffer)}");
            ExpectBytesRead(size, position);
            ReadCRLF();
        }

19 View Source File : lq.cs
License : MIT License
Project Creator : 1CM69

public static void lqdecomposition(ref double[,] a, int m, int n, ref double[] tau)
  {
    double[] numArray1 = new double[0];
    double[] numArray2 = new double[0];
    double tau1 = 0.0;
    int num1 = Math.Min(m, n);
    Math.Max(m, n);
    double[] work = new double[m + 1];
    double[] numArray3 = new double[n + 1];
    tau = new double[num1 + 1];
    int num2 = Math.Min(m, n);
    for (int n1 = 1; n1 <= num2; ++n1)
    {
      int n2 = n - n1 + 1;
      int num3 = n1 - 1;
      for (int index = 1; index <= n2; ++index)
        numArray3[index] = a[n1, index + num3];
      reflections.generatereflection(ref numArray3, n2, ref tau1);
      tau[n1] = tau1;
      int num4 = 1 - n1;
      for (int index = n1; index <= n; ++index)
        a[n1, index] = numArray3[index + num4];
      numArray3[1] = 1.0;
      if (n1 < n)
        reflections.applyreflectionfromtheright(ref a, tau[n1], ref numArray3, n1 + 1, m, n1, n, ref work);
    }
  }

19 View Source File : ExtendedFingerDetector.cs
License : MIT License
Project Creator : 39M

void OnValidate() {
      int required = 0, forbidden = 0;
      PointingState[] stateArray = { Thumb, Index, Middle, Ring, Pinky };
      for(int i=0; i<stateArray.Length; i++) {
        var state = stateArray[i];
        switch (state) {
          case PointingState.Extended:
            required++;
            break;
          case PointingState.NotExtended:
            forbidden++;
            break;
          default:
            break;
        }
        MinimumExtendedCount = Math.Max(required, MinimumExtendedCount);
        MaximumExtendedCount = Math.Min(5 - forbidden, MaximumExtendedCount);
        MaximumExtendedCount = Math.Max(required, MaximumExtendedCount);
      }
    
    }

19 View Source File : RedisClientPool.cs
License : MIT License
Project Creator : 2881099

public static void PrevReheatConnectionPool(ObjectPool<RedisClient> pool, int minPoolSize)
        {
            if (minPoolSize <= 0) minPoolSize = Math.Min(5, pool.Policy.PoolSize);
            if (minPoolSize > pool.Policy.PoolSize) minPoolSize = pool.Policy.PoolSize;
            var initTestOk = true;
            var initStartTime = DateTime.Now;
            var initConns = new ConcurrentBag<Object<RedisClient>>();

            try
            {
                var conn = pool.Get();
                initConns.Add(conn);
                pool.Policy.OnCheckAvailable(conn);
            }
            catch (Exception ex)
            {
                initTestOk = false; //预热一次失败,后面将不进行
                pool.SetUnavailable(ex);
            }
            for (var a = 1; initTestOk && a < minPoolSize; a += 10)
            {
                if (initStartTime.Subtract(DateTime.Now).TotalSeconds > 3) break; //预热耗时超过3秒,退出
                var b = Math.Min(minPoolSize - a, 10); //每10个预热
                var initTasks = new Task[b];
                for (var c = 0; c < b; c++)
                {
                    initTasks[c] = TaskEx.Run(() =>
                    {
                        try
                        {
                            var conn = pool.Get();
                            initConns.Add(conn);
                            pool.Policy.OnCheckAvailable(conn);
                        }
                        catch
                        {
                            initTestOk = false;  //有失败,下一组退出预热
                        }
                    });
                }
                Task.WaitAll(initTasks);
            }
            while (initConns.TryTake(out var conn)) pool.Return(conn);
        }

19 View Source File : qr.cs
License : MIT License
Project Creator : 1CM69

public static void rmatrixqr(ref double[,] a, int m, int n, ref double[] tau)
  {
    double[] numArray1 = new double[0];
    double[] numArray2 = new double[0];
    double tau1 = 0.0;
    if (m <= 0 | n <= 0)
      return;
    int num1 = Math.Min(m, n);
    double[] work = new double[n - 1 + 1];
    double[] numArray3 = new double[m + 1];
    tau = new double[num1 - 1 + 1];
    int num2 = num1;
    for (int m1 = 0; m1 <= num2 - 1; ++m1)
    {
      int num3 = m1 - 1;
      for (int index = 1; index <= m - m1; ++index)
        numArray3[index] = a[index + num3, m1];
      reflections.generatereflection(ref numArray3, m - m1, ref tau1);
      tau[m1] = tau1;
      int num4 = 1 - m1;
      for (int index = m1; index <= m - 1; ++index)
        a[index, m1] = numArray3[index + num4];
      numArray3[1] = 1.0;
      if (m1 < n)
        reflections.applyreflectionfromtheleft(ref a, tau[m1], ref numArray3, m1, m - 1, m1 + 1, n - 1, ref work);
    }
  }

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

internal byte[] ReadRawBytes(int size)
        {
            if (size < 0)
            {
                throw InvalidProtocolBufferException.NegativeSize();
            }

            if (totalBytesRetired + bufferPos + size > currentLimit)
            {
                // Read to the end of the stream (up to the current limit) anyway.
                SkipRawBytes(currentLimit - totalBytesRetired - bufferPos);
                // Then fail.
                throw InvalidProtocolBufferException.TruncatedMessage();
            }

            if (size <= bufferSize - bufferPos)
            {
                // We have all the bytes we need already.
                byte[] bytes = new byte[size];
                ByteArray.Copy(buffer, bufferPos, bytes, 0, size);
                bufferPos += size;
                return bytes;
            }
            else if (size < buffer.Length)
            {
                // Reading more bytes than are in the buffer, but not an excessive number
                // of bytes.  We can safely allocate the resulting array ahead of time.

                // First copy what we have.
                byte[] bytes = new byte[size];
                int pos = bufferSize - bufferPos;
                ByteArray.Copy(buffer, bufferPos, bytes, 0, pos);
                bufferPos = bufferSize;

                // We want to use RefillBuffer() and then copy from the buffer into our
                // byte array rather than reading directly into our byte array because
                // the input may be unbuffered.
                RefillBuffer(true);

                while (size - pos > bufferSize)
                {
                    Buffer.BlockCopy(buffer, 0, bytes, pos, bufferSize);
                    pos += bufferSize;
                    bufferPos = bufferSize;
                    RefillBuffer(true);
                }

                ByteArray.Copy(buffer, 0, bytes, pos, size - pos);
                bufferPos = size - pos;

                return bytes;
            }
            else
            {
                // The size is very large.  For security reasons, we can't allocate the
                // entire byte array yet.  The size comes directly from the input, so a
                // maliciously-crafted message could provide a bogus very large size in
                // order to trick the app into allocating a lot of memory.  We avoid this
                // by allocating and reading only a small chunk at a time, so that the
                // malicious message must actually *be* extremely large to cause
                // problems.  Meanwhile, we limit the allowed size of a message elsewhere.

                // Remember the buffer markers since we'll have to copy the bytes out of
                // it later.
                int originalBufferPos = bufferPos;
                int originalBufferSize = bufferSize;

                // Mark the current buffer consumed.
                totalBytesRetired += bufferSize;
                bufferPos = 0;
                bufferSize = 0;

                // Read all the rest of the bytes we need.
                int sizeLeft = size - (originalBufferSize - originalBufferPos);
                List<byte[]> chunks = new List<byte[]>();

                while (sizeLeft > 0)
                {
                    byte[] chunk = new byte[Math.Min(sizeLeft, buffer.Length)];
                    int pos = 0;
                    while (pos < chunk.Length)
                    {
                        int n = (input == null) ? -1 : input.Read(chunk, pos, chunk.Length - pos);
                        if (n <= 0)
                        {
                            throw InvalidProtocolBufferException.TruncatedMessage();
                        }
                        totalBytesRetired += n;
                        pos += n;
                    }
                    sizeLeft -= chunk.Length;
                    chunks.Add(chunk);
                }

                // OK, got everything.  Now concatenate it all into one buffer.
                byte[] bytes = new byte[size];

                // Start by copying the leftover bytes from this.buffer.
                int newPos = originalBufferSize - originalBufferPos;
                ByteArray.Copy(buffer, originalBufferPos, bytes, 0, newPos);

                // And now all the chunks.
                foreach (byte[] chunk in chunks)
                {
                    Buffer.BlockCopy(chunk, 0, bytes, newPos, chunk.Length);
                    newPos += chunk.Length;
                }

                // Done.
                return bytes;
            }
        }

19 View Source File : qr.cs
License : MIT License
Project Creator : 1CM69

public static void qrdecomposition(ref double[,] a, int m, int n, ref double[] tau)
  {
    double[] numArray1 = new double[0];
    double[] numArray2 = new double[0];
    double tau1 = 0.0;
    int num1 = Math.Min(m, n);
    double[] work = new double[n + 1];
    double[] numArray3 = new double[m + 1];
    tau = new double[num1 + 1];
    int num2 = Math.Min(m, n);
    for (int m1 = 1; m1 <= num2; ++m1)
    {
      int n1 = m - m1 + 1;
      int num3 = m1 - 1;
      for (int index = 1; index <= n1; ++index)
        numArray3[index] = a[index + num3, m1];
      reflections.generatereflection(ref numArray3, n1, ref tau1);
      tau[m1] = tau1;
      int num4 = 1 - m1;
      for (int index = m1; index <= m; ++index)
        a[index, m1] = numArray3[index + num4];
      numArray3[1] = 1.0;
      if (m1 < n)
        reflections.applyreflectionfromtheleft(ref a, tau[m1], ref numArray3, m1, m, m1 + 1, n, ref work);
    }
  }

19 View Source File : DateTimeFuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

public DateTime GenerateDateTimeBetween(DateTime minValue, DateTime maxValue)
        {
            var nbDays = (maxValue - minValue).Days;

            var midInterval = (minValue.AddDays(nbDays/2));

            var maxDaysAllowedBefore = (midInterval - minValue).Days;
            var maxDaysAllowedAfter = (maxValue - midInterval).Days;
            var maxDays = Math.Min(maxDaysAllowedBefore, maxDaysAllowedAfter);

            return midInterval.AddDays(_fuzzer.GenerateInteger(-maxDays, maxDays));
        }

19 View Source File : qr.cs
License : MIT License
Project Creator : 1CM69

public static void rmatrixqrunpackr(ref double[,] a, int m, int n, ref double[,] r)
  {
    if (m <= 0 | n <= 0)
      return;
    int num = Math.Min(m, n);
    r = new double[m - 1 + 1, n - 1 + 1];
    for (int index = 0; index <= n - 1; ++index)
      r[0, index] = 0.0;
    for (int index1 = 1; index1 <= m - 1; ++index1)
    {
      for (int index2 = 0; index2 <= n - 1; ++index2)
        r[index1, index2] = r[0, index2];
    }
    for (int index1 = 0; index1 <= num - 1; ++index1)
    {
      for (int index2 = index1; index2 <= n - 1; ++index2)
        r[index1, index2] = a[index1, index2];
    }
  }

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

public static Mesh CreateLIBIGLMeshBoolean(Mesh[] m_, int Difference_Union_Intersection = 0) {

            //var watch = new System.Diagnostics.Stopwatch();
            //watch.Start();
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //Clean Mesh
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            var meshes = new List<Mesh>(m_.Length);

            for (int i = 0; i < m_.Length; i++) {

                if (!m_[i].IsClosed)
                    continue;

                m_[i].Vertices.UseDoublePrecisionVertices = true;
                Mesh m = m_[i].DuplicateMesh();
                m.Vertices.UseDoublePrecisionVertices = true;
                m.Faces.ConvertQuadsToTriangles();
                m.Vertices.CombineIdentical(true, true);
                m.Vertices.CullUnused();
                m.Weld(3.14159265358979);
                m.FillHoles();
                m.RebuildNormals();
                m.Vertices.UseDoublePrecisionVertices = true;

                if (m.IsValid && m.IsClosed)
                    meshes.Add(m);
            }

            if (meshes.Count < 2)
                return null;

            //watch.Stop();
            //Rhino.RhinoApp.WriteLine($"Execution Time Clean Mesh: {watch.ElapsedMilliseconds} ms");
            //watch.Reset();
            //watch.Start();
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //Send Vertices and Faces to C++
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////




            int numberOfVertices = 0;
            int numberOfFaces = 0;
            foreach (Mesh tempMesh in meshes) {
                numberOfVertices += tempMesh.Vertices.Count;
                numberOfFaces += tempMesh.Faces.Count;
            }

            double[] coord = new double[numberOfVertices * 3];
            int[] vertexArrayCount = new int[meshes.Count + 1]; vertexArrayCount[0] = 0;

            int[] faceID = new int[numberOfFaces * 3];
            int[] faceArrayCount = new int[meshes.Count + 1]; faceArrayCount[0] = 0;

            int nMesh = meshes.Count;



            for (int i = 0; i < meshes.Count; i++) {

                vertexArrayCount[i + 1] = vertexArrayCount[i] + meshes[i].Vertices.Count;
                faceArrayCount[i + 1] = faceArrayCount[i] + meshes[i].Faces.Count;

                for (int j = 0; j < meshes[i].Vertices.Count; j++) {
                    int n = vertexArrayCount[i] * 3;
                    coord[n + (j * 3 + 0)] = meshes[i].Vertices.Point3dAt(j).X;
                    coord[n + (j * 3 + 1)] = meshes[i].Vertices.Point3dAt(j).Y;
                    coord[n + (j * 3 + 2)] = meshes[i].Vertices.Point3dAt(j).Z;
                    ////Rhino.RhinoApp.WriteLine((n + (j * 3 + 0).ToString() + " " + meshes[i].Vertices[j].X.ToString()));
                    ////Rhino.RhinoApp.WriteLine((n + (j * 3 + 1).ToString() + " " + meshes[i].Vertices[j].Y.ToString()));
                    ////Rhino.RhinoApp.WriteLine((n + (j * 3 + 2).ToString() + " " + meshes[i].Vertices[j].Z.ToString()));
                }

                for (int j = 0; j < meshes[i].Faces.Count; j++) {
                    int n = faceArrayCount[i] * 3;
                    faceID[n + (j * 3 + 0)] = meshes[i].Faces[j].A;
                    faceID[n + (j * 3 + 1)] = meshes[i].Faces[j].B;
                    faceID[n + (j * 3 + 2)] = meshes[i].Faces[j].C;
                }

            }


            //watch.Stop();
            //Rhino.RhinoApp.WriteLine($"Execution Copy coordinates: {watch.ElapsedMilliseconds} ms");
            //watch.Reset();
            //watch.Start();


            //Rhino.RhinoApp.WriteLine(coord.Length.ToString());
            //foreach(var c in vertexArrayCount)
            //Rhino.RhinoApp.Write(c.ToString()+" ");
            //Rhino.RhinoApp.WriteLine();
            //Rhino.RhinoApp.WriteLine(faceID.Length.ToString());
            // foreach (var c in faceArrayCount)
            //Rhino.RhinoApp.Write(c.ToString() + " ");
            //Rhino.RhinoApp.WriteLine();
            //Rhino.RhinoApp.WriteLine(nMesh.ToString());




            ////Inputs
            IntPtr vertexCoordPointer = IntPtr.Zero;
            int nVertices = 0;
            IntPtr faceIndicesPointer = IntPtr.Zero;
            int nFaces = 0;
            IntPtr facesColorsPointer = IntPtr.Zero;
            int nFaceColors = 0;
            int numberOfValidMeshes = -1;

            //Call C++ method
            UnsafeLIBIGL.LIBIGL_MeshBoolean_CreateArray(
                coord, vertexArrayCount,
                faceID, faceArrayCount,
                (ulong)nMesh,

                (ulong)Math.Max(0, Math.Min(Difference_Union_Intersection, 2)),

                ref vertexCoordPointer, ref nVertices,
                ref faceIndicesPointer, ref nFaces,
                ref facesColorsPointer, ref nFaceColors,
                ref numberOfValidMeshes);//

            //watch.Stop();
            //Rhino.RhinoApp.WriteLine($"Execution LIBIGL_MeshBoolean_CreateArray: {watch.ElapsedMilliseconds} ms");
            //watch.Reset();
            //watch.Start();
            //Rhino.RhinoApp.WriteLine(numberOfValidMeshes.ToString());
            // return null;


            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //Get Vertices and Faces from C++
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            //Convert faceIndicesPointer to C# int[]
            double[] verticesCoordinates = new double[nVertices * 3];
            Marshal.Copy(vertexCoordPointer, verticesCoordinates, 0, verticesCoordinates.Length);

            int[] faceIndices = new int[nFaces * 3];
            Marshal.Copy(faceIndicesPointer, faceIndices, 0, faceIndices.Length);

            int[] faceColorsIndices = new int[nFaceColors];
            Marshal.Copy(facesColorsPointer, faceColorsIndices, 0, faceColorsIndices.Length);

            //Rhino.RhinoApp.WriteLine(verticesCoordinates.Length.ToString()  + " " + nVertices.ToString());
            //Rhino.RhinoApp.WriteLine(faceIndices.Length.ToString() + " " + nFaces.ToString());



            //Create mesh
            Mesh r_ = new Mesh();
            for (int i = 0; i < verticesCoordinates.Length; i += 3)
                r_.Vertices.Add(new Point3d(verticesCoordinates[i + 0], verticesCoordinates[i + 1], verticesCoordinates[i + 2]));

            for (int i = 0; i < faceIndices.Length; i += 3) {
                r_.Faces.AddFace(faceIndices[i + 0], faceIndices[i + 1], faceIndices[i + 2]);
            }


            //mesh.Vertices.Align(0.01);
            //mesh.Vertices.CombineIdentical(true, true);
            //mesh.Vertices.CullUnused();
            //mesh.Weld(3.14159265358979);
            //mesh.FillHoles();
            r_.RebuildNormals();


            //watch.Stop();
            //Rhino.RhinoApp.WriteLine($"Execution Construct mesh: {watch.ElapsedMilliseconds} ms");
            //watch.Reset();
            //watch.Start();

            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //Colorize Cuts
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            //Mesh r_ = r.DuplicateMesh();
            r_.Unweld(0, true);
            r_.VertexColors.CreateMonotoneMesh(System.Drawing.Color.Black);


            Interval[] domains = new Interval[meshes.Count];

            int count = 0;
            for (int i = 0; i < meshes.Count; i++) {

                domains[i] = new Interval(count, count + meshes[i].Faces.Count);
                count += meshes[i].Faces.Count;
                //if (i == 0)
                //  count += meshes[1].Faces.Count;
                //groups[i] = new List<Mesh>();
            }



            var colorWhite = System.Drawing.Color.FromArgb(200, 200, 200);

            double colorScale = 255.0 / meshes.Count;

            int[] colors = new int[faceColorsIndices.Length];
            for (int i = 0; i < faceColorsIndices.Length; i++) {



                for (int j = 0; j < domains.Length; j++) {
                    if (domains[j].IncludesParameter(faceColorsIndices[i])) {

                        int c = (int)(colorScale * j);

                        if (c == 0) {

                            r_.VertexColors.SetColor(r_.Faces[i].A, colorWhite);
                            r_.VertexColors.SetColor(r_.Faces[i].B, colorWhite);
                            r_.VertexColors.SetColor(r_.Faces[i].C, colorWhite);
                        } else {
                            var colorRed = System.Drawing.Color.FromArgb(255, c, 0);
                            r_.VertexColors.SetColor(r_.Faces[i].A, colorRed);
                            r_.VertexColors.SetColor(r_.Faces[i].B, colorRed);
                            r_.VertexColors.SetColor(r_.Faces[i].C, colorRed);
                        }


                        colors[i] = j;
                    }
                }


            }


            //watch.Stop();
            //Rhino.RhinoApp.WriteLine($"Execution Create Colors: {watch.ElapsedMilliseconds} ms");
            //watch.Reset();
            //watch.Start();


            //Release memory from output
            UnsafeLIBIGL.ReleaseDouble(vertexCoordPointer, true);
            UnsafeLIBIGL.ReleaseInt(faceIndicesPointer, true);
            UnsafeLIBIGL.ReleaseInt(facesColorsPointer, true);

            //watch.Stop();
            //Rhino.RhinoApp.WriteLine($"Execution Release Memory: {watch.ElapsedMilliseconds} ms");
            //watch.Reset();


            return r_;
        }

19 View Source File : FScrollBar.cs
License : MIT License
Project Creator : 0xLaileb

private void MouseScroll(MouseEventArgs e)
        {
            int value = Value;

            switch (OrientationValue)
            {
                case Orientation.Vertical:
                    if (e.Y < 0) value -= SmallStep;
                    else if (e.Y > rectangle_region.Height) value += SmallStep;
                    else value = Maximum * (e.Y - ThumbSize / 2) / (rectangle_region.Height - ThumbSize);
                    rectangle_value = new Rectangle(
                    rectangle_region.X,
                    rectangle_region.Y + (Value * (rectangle_region.Height - ThumbSize) / Maximum),
                    rectangle_region.Width,
                    ThumbSize);
                    break;
                case Orientation.Horizontal:
                    if (e.X < 0) value -= SmallStep;
                    else if (e.X > rectangle_region.Width) value += SmallStep;
                    else value = Maximum * (e.X - ThumbSize / 2) / (rectangle_region.Width - ThumbSize);
                    rectangle_value = new Rectangle(
                    rectangle_region.X + (Value * (rectangle_region.Width - ThumbSize) / Maximum),
                    rectangle_region.Y,
                    ThumbSize,
                    rectangle_region.Height);
                    break;
            }
            Value = Math.Max(0, Math.Min(Maximum, value));
        }

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

public static Mesh CreateLIBIGLMeshBooleanNoColors(Mesh[] m_, int Difference_Union_Intersection = 0) {

            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //Clean Mesh
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            var meshes = new List<Mesh>(m_.Length);

            for (int i = 0; i < m_.Length; i++) {

                if (!m_[i].IsClosed)
                    continue;

                m_[i].Vertices.UseDoublePrecisionVertices = true;
                Mesh m = m_[i].DuplicateMesh();
                m.Vertices.UseDoublePrecisionVertices = true;
                m.Faces.ConvertQuadsToTriangles();
                m.Vertices.CombineIdentical(true, true);
                m.Vertices.CullUnused();
                m.Weld(3.14159265358979);
                m.FillHoles();
                m.RebuildNormals();
                m.Vertices.UseDoublePrecisionVertices = true;

                if (m.IsValid && m.IsClosed)
                    meshes.Add(m);
            }

            if (meshes.Count < 2)
                return null;




            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //Send Vertices and Faces to C++
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////




            int numberOfVertices = 0;
            int numberOfFaces = 0;
            foreach (Mesh tempMesh in meshes) {
                numberOfVertices += tempMesh.Vertices.Count;
                numberOfFaces += tempMesh.Faces.Count;
            }

            double[] coord = new double[numberOfVertices * 3];
            int[] vertexArrayCount = new int[meshes.Count + 1];
            vertexArrayCount[0] = 0;

            int[] faceID = new int[numberOfFaces * 3];
            int[] faceArrayCount = new int[meshes.Count + 1];
            faceArrayCount[0] = 0;

            int nMesh = meshes.Count;



            for (int i = 0; i < meshes.Count; i++) {

                vertexArrayCount[i + 1] = vertexArrayCount[i] + meshes[i].Vertices.Count;
                faceArrayCount[i + 1] = faceArrayCount[i] + meshes[i].Faces.Count;

                for (int j = 0; j < meshes[i].Vertices.Count; j++) {
                    int n = vertexArrayCount[i] * 3;
                    coord[n + (j * 3 + 0)] = meshes[i].Vertices.Point3dAt(j).X;
                    coord[n + (j * 3 + 1)] = meshes[i].Vertices.Point3dAt(j).Y;
                    coord[n + (j * 3 + 2)] = meshes[i].Vertices.Point3dAt(j).Z;
                    ////Rhino.RhinoApp.WriteLine((n + (j * 3 + 0).ToString() + " " + meshes[i].Vertices[j].X.ToString()));
                    ////Rhino.RhinoApp.WriteLine((n + (j * 3 + 1).ToString() + " " + meshes[i].Vertices[j].Y.ToString()));
                    ////Rhino.RhinoApp.WriteLine((n + (j * 3 + 2).ToString() + " " + meshes[i].Vertices[j].Z.ToString()));
                }

                for (int j = 0; j < meshes[i].Faces.Count; j++) {
                    int n = faceArrayCount[i] * 3;
                    faceID[n + (j * 3 + 0)] = meshes[i].Faces[j].A;
                    faceID[n + (j * 3 + 1)] = meshes[i].Faces[j].B;
                    faceID[n + (j * 3 + 2)] = meshes[i].Faces[j].C;
                }

            }


            //Rhino.RhinoApp.WriteLine(coord.Length.ToString());
            //foreach(var c in vertexArrayCount)
            //Rhino.RhinoApp.Write(c.ToString()+" ");
            //Rhino.RhinoApp.WriteLine();
            //Rhino.RhinoApp.WriteLine(faceID.Length.ToString());
            // foreach (var c in faceArrayCount)
            //Rhino.RhinoApp.Write(c.ToString() + " ");
            //Rhino.RhinoApp.WriteLine();
            //Rhino.RhinoApp.WriteLine(nMesh.ToString());




            ////Inputs
            IntPtr vertexCoordPointer = IntPtr.Zero;
            int nVertices = 0;
            IntPtr faceIndicesPointer = IntPtr.Zero;
            int nFaces = 0;


            //Call C++ method
            UnsafeLIBIGL.LIBIGL_MeshBoolean_CreateArrayNoColors(
                coord, vertexArrayCount,
                faceID, faceArrayCount,
                (ulong)nMesh,

                (ulong)Math.Max(0, Math.Min(Difference_Union_Intersection, 2)),

                ref vertexCoordPointer, ref nVertices,
                ref faceIndicesPointer, ref nFaces);//
                                                    //Rhino.RhinoApp.WriteLine(numberOfValidMeshes.ToString());
                                                    // return null;


            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //Get Vertices and Faces from C++
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            //Convert faceIndicesPointer to C# int[]
            double[] verticesCoordinates = new double[nVertices * 3];
            Marshal.Copy(vertexCoordPointer, verticesCoordinates, 0, verticesCoordinates.Length);

            int[] faceIndices = new int[nFaces * 3];
            Marshal.Copy(faceIndicesPointer, faceIndices, 0, faceIndices.Length);


            //Rhino.RhinoApp.WriteLine(verticesCoordinates.Length.ToString()  + " " + nVertices.ToString());
            //Rhino.RhinoApp.WriteLine(faceIndices.Length.ToString() + " " + nFaces.ToString());



            //Create mesh
            Mesh r_ = new Mesh();
            for (int i = 0; i < verticesCoordinates.Length; i += 3)
                r_.Vertices.Add(new Point3d(verticesCoordinates[i + 0], verticesCoordinates[i + 1], verticesCoordinates[i + 2]));

            for (int i = 0; i < faceIndices.Length; i += 3) {
                r_.Faces.AddFace(faceIndices[i + 0], faceIndices[i + 1], faceIndices[i + 2]);
            }

            //mesh.Vertices.Align(0.01);
            //mesh.Vertices.CombineIdentical(true, true);
            //mesh.Vertices.CullUnused();
            //mesh.Weld(3.14159265358979);
            //mesh.FillHoles();
            r_.RebuildNormals();


            //Release memory from output
            UnsafeLIBIGL.ReleaseDouble(vertexCoordPointer, true);
            UnsafeLIBIGL.ReleaseInt(faceIndicesPointer, true);



            return r_;
        }

19 View Source File : Tunneler.cs
License : MIT License
Project Creator : 1upD

public override void Step(AlifeMap map)
        {
            try {
                int seed = this.X + this.Y + this.Z + (int)this.Direction + this.Height + this.Width + (int)System.DateTime.Now.Ticks;

                // Get random number
                Random random = new Random(seed);
                double sample = random.NextDouble();

                // Check turn probability. If turning, change direction 90 degrees
                if (sample < this.ProbTurn)
                {
                    sample = random.NextDouble();
                    int polarity = sample > 0.5 ? 1 : -1;
                    this.Direction = AlifeDirectionOperations.Add(this.Direction, polarity);
                }

                // Get new random seed
                sample = random.NextDouble();

                // Check reproduction probability
                if (sample < this.ProbReproduce)
                {
                    sample = random.NextDouble();
                    int polarity = sample > 0.5 ? 1 : -1;
                    AlifeDirection childDirection = AlifeDirectionOperations.Add(this.Direction, polarity);
                    int widthDecay = random.Next(this.MinWidthDecayRate, this.MaxWidthDecayRate);
                    int heightDecay = random.Next(this.MinHeightDecayRate, this.MaxHeightDecayRate);
                    Tunneler child = new Tunneler(this.Style, this.X, this.Y, this.Z, this.Width - widthDecay, this.Height - heightDecay, this.MaxLifetime - this.LifetimeDecayRate, this.MaxLifetime - this.LifetimeDecayRate, this.ProbReproduce, this.ProbTurn, this.ProbAscend, childDirection);
                    map.Agents.Add(child);
                }
                else
                {
                    sample = random.NextDouble();
                    if (sample < this.ProbSpawnRoomer)
                    {
                        Roomer child = new Roomer(x: this.X, y: this.Y, z: this.Z, style: this.Style, height: Math.Max(this.Height, 2), maxWidth: Math.Min(this.Width * 2, 3), mustDeploy: false);
                        map.Agents.Add(child);
                        }
                }

                // Get new random seed
                sample = random.NextDouble();

                // Check a s c e n d probability
                if (sample < this.ProbAscend)
                {
                    sample = random.NextDouble();
                        int verticalDistance = random.Next(1, Math.Min(this.Height, this.MaxVerticalDrop));
                    int polarity = sample > 0.5 ? verticalDistance : -verticalDistance;
                    this.Z += polarity;
                }
                else
                {
                    // Update location
                    switch (this.Direction)
                    {
                        case AlifeDirection.East:
                            this.X++;
                            break;
                        case AlifeDirection.North:
                            this.Y++;
                            break;
                        case AlifeDirection.West:
                            this.X--;
                            break;
                        case AlifeDirection.South:
                            this.Y--;
                            break;
                        case AlifeDirection.Up:
                            this.Z++;
                            break;
                        case AlifeDirection.Down:
                            this.Z--;
                            break;
                    }

                }


                // Mark location
                // Nasty nested four loop to handle the added spaces from the height and width
                bool vertical = this.Direction == AlifeDirection.North || this.Direction == AlifeDirection.South;
                for (int x = this.X; x <= (vertical ? this.X + this.Width : this.X); x++)
                {
                    for (int y = this.Y; y <= (vertical ? this.Y : this.Y + this.Width); y++)
                    {
                        for (int z = this.Z; z <= this.Z + this.Height; z++)
                        {
                            map.MarkLocation(this.Style, x, y, z);
                        }
                    }
                }

            if (this.Lifetime == 1 && this.SpawnRoomerOnDeath)
            {
                    log.Debug(string.Format("Tunneler died at {0}, {1}, {2}.", this.X, this.Y, this.Z));

                    // Add a roomer
                    Roomer child = new Roomer(x: this.X, y: this.Y, z: this.Z, style: this.Style, height: Math.Max(this.Height, 2), maxWidth: Math.Min(this.Width * 2, 3));
                    map.Agents.Add(child);
                }

            this.Lifetime--;
            }
            catch (Exception e){
                log.Error("Error in Tunneler Step function: ", e);
            }
        }

19 View Source File : ConsoleProgressBar.cs
License : MIT License
Project Creator : a-luna

internal void UpdateText(string text)
        {
            // Get length of common portion
            var commonPrefixLength = 0;
            var commonLength = Math.Min(_currentText.Length, text.Length);
            while (commonPrefixLength < commonLength && text[commonPrefixLength] == _currentText[commonPrefixLength])
                commonPrefixLength++;

            // Backtrack to the first differing character
            var outputBuilder = new StringBuilder();
            outputBuilder.Append('\b', _currentText.Length - commonPrefixLength);

            // Output new suffix
            outputBuilder.Append(text.Substring(commonPrefixLength));

            // If the new text is shorter than the old one: delete overlapping characters
            var overlapCount = _currentText.Length - text.Length;
            if (overlapCount > 0)
            {
                outputBuilder.Append(' ', overlapCount);
                outputBuilder.Append('\b', overlapCount);
            }

            //Console.Write($"{Caption}{outputBuilder}");
            Console.Write(outputBuilder);
            _currentText = text;
        }

19 View Source File : bidiagonal.cs
License : MIT License
Project Creator : 1CM69

public static void rmatrixbd(ref double[,] a, int m, int n, ref double[] tauq, ref double[] taup)
  {
    double[] numArray1 = new double[0];
    double[] numArray2 = new double[0];
    double tau = 0.0;
    if (n <= 0 | m <= 0)
      return;
    Math.Min(m, n);
    int num1 = Math.Max(m, n);
    double[] work = new double[num1 + 1];
    double[] numArray3 = new double[num1 + 1];
    if (m >= n)
    {
      tauq = new double[n - 1 + 1];
      taup = new double[n - 1 + 1];
    }
    else
    {
      tauq = new double[m - 1 + 1];
      taup = new double[m - 1 + 1];
    }
    if (m >= n)
    {
      for (int m1 = 0; m1 <= n - 1; ++m1)
      {
        int num2 = m1 - 1;
        for (int index = 1; index <= m - m1; ++index)
          numArray3[index] = a[index + num2, m1];
        reflections.generatereflection(ref numArray3, m - m1, ref tau);
        tauq[m1] = tau;
        int num3 = 1 - m1;
        for (int index = m1; index <= m - 1; ++index)
          a[index, m1] = numArray3[index + num3];
        numArray3[1] = 1.0;
        reflections.applyreflectionfromtheleft(ref a, tau, ref numArray3, m1, m - 1, m1 + 1, n - 1, ref work);
        if (m1 < n - 1)
        {
          int num4 = m1 + 1 - 1;
          for (int index = 1; index <= n - m1 - 1; ++index)
            numArray3[index] = a[m1, index + num4];
          reflections.generatereflection(ref numArray3, n - 1 - m1, ref tau);
          taup[m1] = tau;
          int num5 = 1 - (m1 + 1);
          for (int index = m1 + 1; index <= n - 1; ++index)
            a[m1, index] = numArray3[index + num5];
          numArray3[1] = 1.0;
          reflections.applyreflectionfromtheright(ref a, tau, ref numArray3, m1 + 1, m - 1, m1 + 1, n - 1, ref work);
        }
        else
          taup[m1] = 0.0;
      }
    }
    else
    {
      for (int n1 = 0; n1 <= m - 1; ++n1)
      {
        int num2 = n1 - 1;
        for (int index = 1; index <= n - n1; ++index)
          numArray3[index] = a[n1, index + num2];
        reflections.generatereflection(ref numArray3, n - n1, ref tau);
        taup[n1] = tau;
        int num3 = 1 - n1;
        for (int index = n1; index <= n - 1; ++index)
          a[n1, index] = numArray3[index + num3];
        numArray3[1] = 1.0;
        reflections.applyreflectionfromtheright(ref a, tau, ref numArray3, n1 + 1, m - 1, n1, n - 1, ref work);
        if (n1 < m - 1)
        {
          int num4 = n1 + 1 - 1;
          for (int index = 1; index <= m - 1 - n1; ++index)
            numArray3[index] = a[index + num4, n1];
          reflections.generatereflection(ref numArray3, m - 1 - n1, ref tau);
          tauq[n1] = tau;
          int num5 = 1 - (n1 + 1);
          for (int index = n1 + 1; index <= m - 1; ++index)
            a[index, n1] = numArray3[index + num5];
          numArray3[1] = 1.0;
          reflections.applyreflectionfromtheleft(ref a, tau, ref numArray3, n1 + 1, m - 1, n1 + 1, n - 1, ref work);
        }
        else
          tauq[n1] = 0.0;
      }
    }
  }

19 View Source File : DellSmbiosSmi.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

private static uint? GetSecurityKeyNew(SmiPreplacedword which, string preplacedword, PreplacedwordProperties properties)
        {
            // NOTE – Non-functional, need to figure out the string pointer before it will work.

            if (GetPreplacedwordFormat(which, properties) == SmiPreplacedwordFormat.Scancode)
            {
                throw new NotImplementedException("BIOS wants scancode-encoded preplacedwords, but only ASCII-encoded preplacedwords are supported at this time.");
            }

            SmiObject message = new SmiObject
            {
                Clreplaced = (Clreplaced)which,
                Selector = Selector.VerifyPreplacedwordNew
            };

            // Allocate a buffer for the preplacedword.
            int bufferSize = properties.MaximumLength * 2;
            IntPtr buffer = Marshal.AllocHGlobal(bufferSize);

            // Zero out the buffer.
            for (byte index = 0; index < bufferSize; index++)
            {
                Marshal.WriteByte(buffer, index, 0);
            }

            // Copy preplacedword into the buffer (ASCII-encoded).
            byte[] preplacedwordBytes = ASCIIEncoding.ASCII.GetBytes(preplacedword);
            Marshal.Copy(preplacedwordBytes, 0, buffer, Math.Min(preplacedword.Length, bufferSize));

            message.Input1 = (uint)buffer.ToInt32();

            ExecuteCommand(ref message);

            Marshal.FreeHGlobal(buffer);

            if (message.Input1 == (uint)SmiPreplacedwordCheckResult.Correct)
            {
                return message.Input2;
            }
            else
            {
                return null;
            }
        }

19 View Source File : bidiagonal.cs
License : MIT License
Project Creator : 1CM69

public static void tobidiagonal(ref double[,] a, int m, int n, ref double[] tauq, ref double[] taup)
  {
    double[] numArray1 = new double[0];
    double[] numArray2 = new double[0];
    double tau = 0.0;
    int num1 = Math.Min(m, n);
    int num2 = Math.Max(m, n);
    double[] work = new double[num2 + 1];
    double[] numArray3 = new double[num2 + 1];
    taup = new double[num1 + 1];
    tauq = new double[num1 + 1];
    if (m >= n)
    {
      for (int m1 = 1; m1 <= n; ++m1)
      {
        int n1 = m - m1 + 1;
        int num3 = m1 - 1;
        for (int index = 1; index <= n1; ++index)
          numArray3[index] = a[index + num3, m1];
        reflections.generatereflection(ref numArray3, n1, ref tau);
        tauq[m1] = tau;
        int num4 = 1 - m1;
        for (int index = m1; index <= m; ++index)
          a[index, m1] = numArray3[index + num4];
        numArray3[1] = 1.0;
        reflections.applyreflectionfromtheleft(ref a, tau, ref numArray3, m1, m, m1 + 1, n, ref work);
        if (m1 < n)
        {
          int n2 = n - m1;
          int num5 = m1 + 1;
          int num6 = num5 - 1;
          for (int index = 1; index <= n2; ++index)
            numArray3[index] = a[m1, index + num6];
          reflections.generatereflection(ref numArray3, n2, ref tau);
          taup[m1] = tau;
          int num7 = 1 - num5;
          for (int index = num5; index <= n; ++index)
            a[m1, index] = numArray3[index + num7];
          numArray3[1] = 1.0;
          reflections.applyreflectionfromtheright(ref a, tau, ref numArray3, m1 + 1, m, m1 + 1, n, ref work);
        }
        else
          taup[m1] = 0.0;
      }
    }
    else
    {
      for (int n1 = 1; n1 <= m; ++n1)
      {
        int n2 = n - n1 + 1;
        int num3 = n1 - 1;
        for (int index = 1; index <= n2; ++index)
          numArray3[index] = a[n1, index + num3];
        reflections.generatereflection(ref numArray3, n2, ref tau);
        taup[n1] = tau;
        int num4 = 1 - n1;
        for (int index = n1; index <= n; ++index)
          a[n1, index] = numArray3[index + num4];
        numArray3[1] = 1.0;
        reflections.applyreflectionfromtheright(ref a, tau, ref numArray3, n1 + 1, m, n1, n, ref work);
        if (n1 < m)
        {
          int n3 = m - n1;
          int num5 = n1 + 1;
          int num6 = num5 - 1;
          for (int index = 1; index <= n3; ++index)
            numArray3[index] = a[index + num6, n1];
          reflections.generatereflection(ref numArray3, n3, ref tau);
          tauq[n1] = tau;
          int num7 = 1 - num5;
          for (int index = num5; index <= m; ++index)
            a[index, n1] = numArray3[index + num7];
          numArray3[1] = 1.0;
          reflections.applyreflectionfromtheleft(ref a, tau, ref numArray3, n1 + 1, m, n1 + 1, n, ref work);
        }
        else
          tauq[n1] = 0.0;
      }
    }
  }

19 View Source File : LogEventTests.EdgeCases.cs
License : MIT License
Project Creator : Abc-Arbitrage

[Test]
        public void should_ignore_ascii_string_if_buffer_is_not_large_enough_for_header(
            [Range(_bufferSize - 2 * _asciiHeaderSize, _bufferSize)] int firstStringLength)
        {
            var largeString1 = new string('a', firstStringLength);
            var asciiBytes1 = Encoding.ASCII.GetBytes(largeString1);
            _logEvent.AppendAsciiString(asciiBytes1, asciiBytes1.Length);

            var largeString2 = new string('b', _bufferSize);
            var asciiBytes2 = Encoding.ASCII.GetBytes(largeString2);
            _logEvent.AppendAsciiString(asciiBytes2, asciiBytes2.Length);

            _logEvent.WriteToStringBuffer(_output);

            var expectedTextLength = Math.Min(firstStringLength, _bufferSize - _asciiHeaderSize);
            Check.That(_output.ToString()).IsEqualTo(new string('a', expectedTextLength) + LogManager.Config.TruncatedMessageSuffix);
        }

19 View Source File : Rectangle.cs
License : zlib License
Project Creator : 0x0ade

public void Intersect(Rectangle rect) {
            if (!IntersectsWithInclusive(rect)) {
                x = y = width = height = 0;
                return;
            }

            x = Math.Max(Left, rect.Left);
            y = Math.Max(Top, rect.Top);
            width = Math.Min(Right, rect.Right) - x;
            height = Math.Min(Bottom, rect.Bottom) - y;
        }

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

public IEnumerable<HighlightedSection> GetHighlightedSections(int offset, int length)
		{
			int index = GetIndexForOffset(offset);
			int pos = offset;
			int endOffset = offset + length;
			while (pos < endOffset) {
				int endPos = Math.Min(endOffset, GetEnd(index));
				yield return new HighlightedSection {
					Offset = pos,
					Length = endPos - pos,
					Color = stateChanges[index]
				};
				pos = endPos;
				index++;
			}
		}

19 View Source File : bidiagonal.cs
License : MIT License
Project Creator : 1CM69

public static void unpackptfrombidiagonal(ref double[,] qp, int m, int n, ref double[] taup, int ptrows, ref double[,] pt)
  {
    double[] numArray1 = new double[0];
    double[] numArray2 = new double[0];
    if (m == 0 | n == 0 | ptrows == 0)
      return;
    pt = new double[ptrows + 1, n + 1];
    double[] v = new double[n + 1];
    double[] work = new double[ptrows + 1];
    for (int index1 = 1; index1 <= ptrows; ++index1)
    {
      for (int index2 = 1; index2 <= n; ++index2)
        pt[index1, index2] = index1 != index2 ? 0.0 : 1.0;
    }
    if (m >= n)
    {
      for (int index1 = Math.Min(n - 1, ptrows - 1); index1 >= 1; --index1)
      {
        int num1 = n - index1;
        int num2 = index1 + 1 - 1;
        for (int index2 = 1; index2 <= num1; ++index2)
          v[index2] = qp[index1, index2 + num2];
        v[1] = 1.0;
        reflections.applyreflectionfromtheright(ref pt, taup[index1], ref v, 1, ptrows, index1 + 1, n, ref work);
      }
    }
    else
    {
      for (int n1 = Math.Min(m, ptrows); n1 >= 1; --n1)
      {
        int num1 = n - n1 + 1;
        int num2 = n1 - 1;
        for (int index = 1; index <= num1; ++index)
          v[index] = qp[n1, index + num2];
        v[1] = 1.0;
        reflections.applyreflectionfromtheright(ref pt, taup[n1], ref v, 1, ptrows, n1, n, ref work);
      }
    }
  }

19 View Source File : lq.cs
License : MIT License
Project Creator : 1CM69

public static void rmatrixlqunpackq(ref double[,] a, int m, int n, ref double[] tau, int qrows, ref double[,] q)
  {
    double[] numArray1 = new double[0];
    double[] numArray2 = new double[0];
    if (m <= 0 | n <= 0 | qrows <= 0)
      return;
    int num1 = Math.Min(Math.Min(m, n), qrows);
    q = new double[qrows - 1 + 1, n - 1 + 1];
    double[] v = new double[n + 1];
    double[] work = new double[qrows + 1];
    for (int index1 = 0; index1 <= qrows - 1; ++index1)
    {
      for (int index2 = 0; index2 <= n - 1; ++index2)
        q[index1, index2] = index1 != index2 ? 0.0 : 1.0;
    }
    for (int n1 = num1 - 1; n1 >= 0; --n1)
    {
      int num2 = n1 - 1;
      for (int index = 1; index <= n - n1; ++index)
        v[index] = a[n1, index + num2];
      v[1] = 1.0;
      reflections.applyreflectionfromtheright(ref q, tau[n1], ref v, 0, qrows - 1, n1, n - 1, ref work);
    }
  }

19 View Source File : Rectangle.cs
License : zlib License
Project Creator : 0x0ade

public static Rectangle Union(Rectangle a, Rectangle b)
            => FromLTRB(
                Math.Min(a.Left, b.Left),
                Math.Min(a.Top, b.Top),
                Math.Max(a.Right, b.Right),
                Math.Max(a.Bottom, b.Bottom)
            );

19 View Source File : SourceDocumentProvider.cs
License : MIT License
Project Creator : 0xd4d

public IEnumerable<(string line, Span span, bool partial)> GetLines(string file, int startLine, int startColumn, int endLine, int endColumn) {
			if (startLine < 1 || endLine < 1 || startColumn < 1 || endColumn < 1)
				yield break;
			var lines = GetDoreplacedent(file)?.Lines;
			if (lines is null || lines.Length == 0)
				yield break;
			startLine = Math.Min(startLine, lines.Length);
			endLine = Math.Min(endLine, lines.Length);
			startLine--;
			endLine--;
			startColumn--;
			endColumn--;
			if (endLine < startLine)
				yield break;
			if (startLine == endLine && endColumn < startColumn)
				yield break;
			for (int lineNo = startLine; lineNo <= endLine; lineNo++) {
				var line = lines[lineNo];
				int scol = 0;
				int ecol = line.Length;
				if (lineNo == startLine)
					scol = startColumn;
				if (lineNo == endLine)
					ecol = endColumn;
				// Sometimes happens with .xaml files
				if (scol > line.Length || ecol > line.Length || scol > ecol)
					break;
				bool partial = IsPartial(line, startLine, endLine, startColumn, endColumn, lineNo);
				yield return (line, new Span(scol, ecol), partial);
			}
		}

19 View Source File : GeneratorClass.cs
License : MIT License
Project Creator : 188867052

private static string GetCrefNamespace(string cref, string @namespace)
        {
            IList<string> sameString = new List<string>();
            var splitNamespace = @namespace.Split('.');
            var splitCref = cref.Split('.');
            int minLength = Math.Min(splitNamespace.Length, splitCref.Length);
            for (int i = 0; i < minLength; i++)
            {
                if (splitCref[i] == splitNamespace[i])
                {
                    sameString.Add(splitCref[i]);
                }
                else
                {
                    break;
                }
            }

            cref = cref.Substring(string.Join('.', sameString).Length + 1);
            return cref;
        }

19 View Source File : lq.cs
License : MIT License
Project Creator : 1CM69

public static void unpackqfromlq(ref double[,] a, int m, int n, ref double[] tau, int qrows, ref double[,] q)
  {
    double[] numArray1 = new double[0];
    double[] numArray2 = new double[0];
    if (m == 0 | n == 0 | qrows == 0)
      return;
    int num1 = Math.Min(Math.Min(m, n), qrows);
    q = new double[qrows + 1, n + 1];
    double[] v = new double[n + 1];
    double[] work = new double[qrows + 1];
    for (int index1 = 1; index1 <= qrows; ++index1)
    {
      for (int index2 = 1; index2 <= n; ++index2)
        q[index1, index2] = index1 != index2 ? 0.0 : 1.0;
    }
    for (int n1 = num1; n1 >= 1; --n1)
    {
      int num2 = n - n1 + 1;
      int num3 = n1 - 1;
      for (int index = 1; index <= num2; ++index)
        v[index] = a[n1, index + num3];
      v[1] = 1.0;
      reflections.applyreflectionfromtheright(ref q, tau[n1], ref v, 1, qrows, n1, n, ref work);
    }
  }

19 View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099

public static object FromObject(this Type targetType, object value, Encoding encoding = null)
    {
        if (targetType == typeof(object)) return value;
        if (encoding == null) encoding = Encoding.UTF8;
        var valueIsNull = value == null;
        var valueType = valueIsNull ? typeof(string) : value.GetType();
        if (valueType == targetType) return value;
        if (valueType == typeof(byte[])) //byte[] -> guid
        {
            if (targetType == typeof(Guid))
            {
                var bytes = value as byte[];
                return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? tryguid : Guid.Empty;
            }
            if (targetType == typeof(Guid?))
            {
                var bytes = value as byte[];
                return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? (Guid?)tryguid : null;
            }
        }
        if (targetType == typeof(byte[])) //guid -> byte[]
        {
            if (valueIsNull) return null;
            if (valueType == typeof(Guid) || valueType == typeof(Guid?))
            {
                var bytes = new byte[16];
                var guidN = ((Guid)value).ToString("N");
                for (var a = 0; a < guidN.Length; a += 2)
                    bytes[a / 2] = byte.Parse($"{guidN[a]}{guidN[a + 1]}", NumberStyles.HexNumber);
                return bytes;
            }
            return encoding.GetBytes(value.ToInvariantCultureToString());
        }
        else if (targetType.IsArray)
        {
            if (value is Array valueArr)
            {
                var targetElementType = targetType.GetElementType();
                var sourceArrLen = valueArr.Length;
                var target = Array.CreateInstance(targetElementType, sourceArrLen);
                for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueArr.GetValue(a), encoding), a);
                return target;
            }
            //if (value is IList valueList)
            //{
            //    var targetElementType = targetType.GetElementType();
            //    var sourceArrLen = valueList.Count;
            //    var target = Array.CreateInstance(targetElementType, sourceArrLen);
            //    for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueList[a], encoding), a);
            //    return target;
            //}
        }
        var func = _dicFromObject.GetOrAdd(targetType, tt =>
        {
            if (tt == typeof(object)) return vs => vs;
            if (tt == typeof(string)) return vs => vs;
            if (tt == typeof(char[])) return vs => vs == null ? null : vs.ToCharArray();
            if (tt == typeof(char)) return vs => vs == null ? default(char) : vs.ToCharArray(0, 1).FirstOrDefault();
            if (tt == typeof(bool)) return vs =>
            {
                if (vs == null) return false;
                switch (vs.ToLower())
                {
                    case "true":
                    case "1":
                        return true;
                }
                return false;
            };
            if (tt == typeof(bool?)) return vs =>
            {
                if (vs == null) return false;
                switch (vs.ToLower())
                {
                    case "true":
                    case "1":
                        return true;
                    case "false":
                    case "0":
                        return false;
                }
                return null;
            };
            if (tt == typeof(byte)) return vs => vs == null ? 0 : (byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(byte?)) return vs => vs == null ? null : (byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (byte?)tryval : null);
            if (tt == typeof(decimal)) return vs => vs == null ? 0 : (decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(decimal?)) return vs => vs == null ? null : (decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (decimal?)tryval : null);
            if (tt == typeof(double)) return vs => vs == null ? 0 : (double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(double?)) return vs => vs == null ? null : (double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (double?)tryval : null);
            if (tt == typeof(float)) return vs => vs == null ? 0 : (float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(float?)) return vs => vs == null ? null : (float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (float?)tryval : null);
            if (tt == typeof(int)) return vs => vs == null ? 0 : (int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(int?)) return vs => vs == null ? null : (int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (int?)tryval : null);
            if (tt == typeof(long)) return vs => vs == null ? 0 : (long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(long?)) return vs => vs == null ? null : (long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (long?)tryval : null);
            if (tt == typeof(sbyte)) return vs => vs == null ? 0 : (sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(sbyte?)) return vs => vs == null ? null : (sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (sbyte?)tryval : null);
            if (tt == typeof(short)) return vs => vs == null ? 0 : (short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(short?)) return vs => vs == null ? null : (short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (short?)tryval : null);
            if (tt == typeof(uint)) return vs => vs == null ? 0 : (uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(uint?)) return vs => vs == null ? null : (uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (uint?)tryval : null);
            if (tt == typeof(ulong)) return vs => vs == null ? 0 : (ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(ulong?)) return vs => vs == null ? null : (ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ulong?)tryval : null);
            if (tt == typeof(ushort)) return vs => vs == null ? 0 : (ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(ushort?)) return vs => vs == null ? null : (ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ushort?)tryval : null);
            if (tt == typeof(DateTime)) return vs => vs == null ? DateTime.MinValue : (DateTime.TryParse(vs, out var tryval) ? tryval : DateTime.MinValue);
            if (tt == typeof(DateTime?)) return vs => vs == null ? null : (DateTime.TryParse(vs, out var tryval) ? (DateTime?)tryval : null);
            if (tt == typeof(DateTimeOffset)) return vs => vs == null ? DateTimeOffset.MinValue : (DateTimeOffset.TryParse(vs, out var tryval) ? tryval : DateTimeOffset.MinValue);
            if (tt == typeof(DateTimeOffset?)) return vs => vs == null ? null : (DateTimeOffset.TryParse(vs, out var tryval) ? (DateTimeOffset?)tryval : null);
            if (tt == typeof(TimeSpan)) return vs => vs == null ? TimeSpan.Zero : (TimeSpan.TryParse(vs, out var tryval) ? tryval : TimeSpan.Zero);
            if (tt == typeof(TimeSpan?)) return vs => vs == null ? null : (TimeSpan.TryParse(vs, out var tryval) ? (TimeSpan?)tryval : null);
            if (tt == typeof(Guid)) return vs => vs == null ? Guid.Empty : (Guid.TryParse(vs, out var tryval) ? tryval : Guid.Empty);
            if (tt == typeof(Guid?)) return vs => vs == null ? null : (Guid.TryParse(vs, out var tryval) ? (Guid?)tryval : null);
            if (tt == typeof(BigInteger)) return vs => vs == null ? 0 : (BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(BigInteger?)) return vs => vs == null ? null : (BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (BigInteger?)tryval : null);
            if (tt.NullableTypeOrThis().IsEnum)
            {
                var tttype = tt.NullableTypeOrThis();
                var ttdefval = tt.CreateInstanceGetDefaultValue();
                return vs =>
                {
                    if (string.IsNullOrWhiteSpace(vs)) return ttdefval;
                    return Enum.Parse(tttype, vs, true);
                };
            }
            var localTargetType = targetType;
            var localValueType = valueType;
            return vs =>
            {
                if (vs == null) return null;
                throw new NotSupportedException($"convert failed {localValueType.DisplayCsharp()} -> {localTargetType.DisplayCsharp()}");
            };
        });
        var valueStr = valueIsNull ? null : (valueType == typeof(byte[]) ? encoding.GetString(value as byte[]) : value.ToInvariantCultureToString());
        return func(valueStr);
    }

See More Examples