System.Collections.Generic.List.Add(double)

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

1151 Examples 7

19 Source : Formatter.Array1.List.cs
with MIT License
from 1996v

public List<Double> Deserialize(ref BssomReader reader, ref BssomDeserializeContext context)
        {
            if (reader.TryReadNullWithEnsureArray1BuildInType(BssomType.Float64Code))
            {
                return default;
            }

            context.Option.Security.DepthStep(ref context);
            reader.SkipVariableNumber();
            int len = reader.ReadVariableNumber();
            List<double> val = new List<Double>(len);
            for (int i = 0; i < len; i++)
            {
                val.Add(reader.ReadFloat64WithOutTypeHead());
            }
            context.Depth--;
            return val;
        }

19 Source : LunarYear.cs
with MIT License
from 6tail

private void compute()
        {
            // 节气(中午12点)
            double[] jq = new double[27];
            // 合朔,即每月初一(中午12点)
            double[] hs = new double[16];
            // 每月天数
            int[] dayCounts = new int[hs.Length - 1];

            int currentYear = this.year;

            int year = currentYear - 2000;
            // 从上年的大雪到下年的立春
            for (int i = 0, j = Lunar.JIE_QI_IN_USE.Length; i < j; i++)
            {
                // 精确的节气
                double t = 36525 * ShouXingUtil.saLonT((year + (17 + i) * 15d / 360) * ShouXingUtil.PI_2);
                t += ShouXingUtil.ONE_THIRD - ShouXingUtil.dtT(t);
                jieQiJulianDays.Add(t + Solar.J2000);
                // 按中午12点算的节气
                if (i > 0 && i < 28)
                {
                    jq[i - 1] = Math.Round(t);
                }
            }

            // 冬至前的初一
            double w = ShouXingUtil.calcShuo(jq[0]);
            if (w > jq[0])
            {
                w -= 29.5306;
            }
            // 递推每月初一
            for (int i = 0, j = hs.Length; i < j; i++)
            {
                hs[i] = ShouXingUtil.calcShuo(w + 29.5306 * i);
            }
            // 每月天数
            for (int i = 0, j = dayCounts.Length; i < j; i++)
            {
                dayCounts[i] = (int)(hs[i + 1] - hs[i]);
            }

            int currentYearLeap = -1;
            try
            {
                currentYearLeap = LEAP[currentYear];
            }
            catch { }
            if (-1 == currentYearLeap)
            {
                currentYearLeap = -1;
                if (hs[13] <= jq[24])
                {
                    int i = 1;
                    while (hs[i + 1] > jq[2 * i] && i < 13)
                    {
                        i++;
                    }
                    currentYearLeap = i;
                }
            }

            int prevYear = currentYear - 1;
            int prevYearLeap = -1;
            try
            {
                prevYearLeap = LEAP[prevYear];
            }
            catch { }
            prevYearLeap = -1 == prevYearLeap ? -1 : prevYearLeap - 12;

            int y = prevYear;
            int m = 11;
            for (int i = 0, j = dayCounts.Length; i < j; i++)
            {
                int cm = m;
                bool isNextLeap = false;
                if (y == currentYear && i == currentYearLeap)
                {
                    cm = -cm;
                }
                else if (y == prevYear && i == prevYearLeap)
                {
                    cm = -cm;
                }
                if (y == currentYear && i + 1 == currentYearLeap)
                {
                    isNextLeap = true;
                }
                else if (y == prevYear && i + 1 == prevYearLeap)
                {
                    isNextLeap = true;
                }
                this.months.Add(new LunarMonth(y, cm, dayCounts[i], hs[i] + Solar.J2000));
                if (!isNextLeap)
                {
                    m++;
                }
                if (m == 13)
                {
                    m = 1;
                    y++;
                }
            }
        }

19 Source : TextRangeProvider.cs
with MIT License
from Abdesol

public double[] GetBoundingRectangles()
		{
			Log("{0}.GetBoundingRectangles()", ID);
			var textView = textArea.TextView;
			var source = PresentationSource.FromVisual(this.textArea);
			var result = new List<double>();
			foreach (var rect in BackgroundGeometryBuilder.GetRectsForSegment(textView, segment)) {
				var tl = textView.PointToScreen(rect.TopLeft);
				var br = textView.PointToScreen(rect.BottomRight);
				result.Add(tl.X);
				result.Add(tl.Y);
				result.Add(br.X - tl.X);
				result.Add(br.Y - tl.Y);
			}
			return result.ToArray();
		}

19 Source : ShapePolyLineM.cs
with Microsoft Public License
from abfo

private void ParsePolyLineM(byte[] shapeData, out RectangleD boundingBox, out List<PointD[]> parts)
        {
            boundingBox = new RectangleD();
            parts = null;

            // metadata is validated by the base clreplaced
            if (shapeData == null)
            {
                throw new ArgumentNullException("shapeData");
            }

            // Note, shapeData includes an 8 byte header so positions below are +8
            // Position     Field       Value       Type        Number      Order
            // Byte 0       Shape Type  23          Integer     1           Little
            // Byte 4       Box         Box         Double      4           Little
            // Byte 36      NumParts    NumParts    Integer     1           Little
            // Byte 40      NumPoints   NumPoints   Integer     1           Little
            // Byte 44      Parts       Parts       Integer     NumParts    Little
            // Byte X       Points      Points      Point       NumPoints   Little
            // Byte Y*      Mmin        Mmin        Double      1           Little
            // Byte Y + 8*  Mmax        Mmax        Double      1           Little
            // Byte Y + 16* Marray      Marray      Double      NumPoints   Little

            //
            // *optional

            // validation step 1 - must have at least 8 + 4 + (4*8) + 4 + 4 bytes = 52
            if (shapeData.Length < 44)
            {
                throw new InvalidOperationException("Invalid shape data");
            }

            // extract bounding box, number of parts and number of points
            boundingBox = ParseBoundingBox(shapeData, 12, ProvidedOrder.Little);
            int numParts = EndianBitConverter.ToInt32(shapeData, 44, ProvidedOrder.Little);
            int numPoints = EndianBitConverter.ToInt32(shapeData, 48, ProvidedOrder.Little);            

            // validation step 2 - we're expecting 4 * numParts + (16 + 8 * numPoints for m extremes and values) + 16 * numPoints + 52 bytes total
            if (shapeData.Length != 52 + (4 * numParts) + 16 + 8 * numPoints + (16 * numPoints))
            {
                throw new InvalidOperationException("Invalid shape data");
            }

            // now extract the parts
            int partsOffset = 52 + (4 * numParts);
            parts = new List<PointD[]>(numParts);
            for (int part = 0; part < numParts; part++)
            {
                // this is the index of the start of the part in the points array
                int startPart = (EndianBitConverter.ToInt32(shapeData, 52 + (4 * part), ProvidedOrder.Little) * 16) + partsOffset;

                int numBytes;
                if (part == numParts - 1)
                {
                    // it's the last part so we go to the end of the point array
                    numBytes = shapeData.Length - startPart;

                    // remove bytes for M extreme block
                    numBytes -= numPoints * 8 + 16;
                }
                else
                {
                    // we need to get the next part
                    int nextPart = (EndianBitConverter.ToInt32(shapeData, 52 + (4 * (part + 1)), ProvidedOrder.Little) * 16) + partsOffset;
                    numBytes = nextPart - startPart;
                }

                // the number of 16-byte points to read for this segment
                int numPointsInPart = (numBytes) / 16;

                PointD[] points = new PointD[numPointsInPart];
                for (int point = 0; point < numPointsInPart; point++)
                {
                    points[point] = new PointD(EndianBitConverter.ToDouble(shapeData, startPart + (16 * point), ProvidedOrder.Little),
                        EndianBitConverter.ToDouble(shapeData, startPart + 8 + (16 * point), ProvidedOrder.Little));
                }

                parts.Add(points);
            }

            // parse M information
            Mmin = EndianBitConverter.ToDouble(shapeData, 52 + (4 * numParts) + (16 * numPoints), ProvidedOrder.Little);
            Mmax = EndianBitConverter.ToDouble(shapeData, 52 + 8 + (4 * numParts) + (16 * numPoints), ProvidedOrder.Little);

            M.Clear();
            for (int i = 0; i < numPoints; i++)
            {
                double _m = EndianBitConverter.ToDouble(shapeData, 52 + 16 + (4 * numParts) + (16 * numPoints) + i * 8, ProvidedOrder.Little);
                M.Add(_m);
            }
        }

19 Source : VitalSignsBatch.cs
with MIT License
from ABTSoftware

public void UpdateData(IList<VitalSignsData> dataList)
        {
            XValues.Clear();

            ECGHeartRateValuesA.Clear();
            BloodPressureValuesA.Clear();
            BloodVolumeValuesA.Clear();
            BloodOxygenationValuesA.Clear();

            ECGHeartRateValuesB.Clear();
            BloodPressureValuesB.Clear();
            BloodVolumeValuesB.Clear();
            BloodOxygenationValuesB.Clear();

            foreach (VitalSignsData data in dataList)
            {
                XValues.Add(data.XValue);

                if (data.IsATrace)
                {
                    ECGHeartRateValuesA.Add(data.ECGHeartRate);
                    BloodPressureValuesA.Add(data.BloodPressure);
                    BloodVolumeValuesA.Add(data.BloodVolume);
                    BloodOxygenationValuesA.Add(data.BloodOxygenation);

                    ECGHeartRateValuesB.Add(double.NaN);
                    BloodPressureValuesB.Add(double.NaN);
                    BloodVolumeValuesB.Add(double.NaN);
                    BloodOxygenationValuesB.Add(double.NaN);
                }
                else
                {
                    ECGHeartRateValuesB.Add(data.ECGHeartRate);
                    BloodPressureValuesB.Add(data.BloodPressure);
                    BloodVolumeValuesB.Add(data.BloodVolume);
                    BloodOxygenationValuesB.Add(data.BloodOxygenation);

                    ECGHeartRateValuesA.Add(double.NaN);
                    BloodPressureValuesA.Add(double.NaN);
                    BloodVolumeValuesA.Add(double.NaN);
                    BloodOxygenationValuesA.Add(double.NaN);
                }
            }

            LastVitalSignsData = dataList.Last();
        }

19 Source : VitalSignsBatch.cs
with MIT License
from ABTSoftware

public void UpdateData(IList<VitalSignsData> dataList)
        {
            XValues.Clear();

            ECGHeartRateValuesA.Clear();
            BloodPressureValuesA.Clear();
            BloodVolumeValuesA.Clear();
            BloodOxygenationValuesA.Clear();

            ECGHeartRateValuesB.Clear();
            BloodPressureValuesB.Clear();
            BloodVolumeValuesB.Clear();
            BloodOxygenationValuesB.Clear();

            foreach (VitalSignsData data in dataList)
            {
                XValues.Add(data.XValue);

                if (data.IsATrace)
                {
                    ECGHeartRateValuesA.Add(data.ECGHeartRate);
                    BloodPressureValuesA.Add(data.BloodPressure);
                    BloodVolumeValuesA.Add(data.BloodVolume);
                    BloodOxygenationValuesA.Add(data.BloodOxygenation);

                    ECGHeartRateValuesB.Add(double.NaN);
                    BloodPressureValuesB.Add(double.NaN);
                    BloodVolumeValuesB.Add(double.NaN);
                    BloodOxygenationValuesB.Add(double.NaN);
                }
                else
                {
                    ECGHeartRateValuesB.Add(data.ECGHeartRate);
                    BloodPressureValuesB.Add(data.BloodPressure);
                    BloodVolumeValuesB.Add(data.BloodVolume);
                    BloodOxygenationValuesB.Add(data.BloodOxygenation);

                    ECGHeartRateValuesA.Add(double.NaN);
                    BloodPressureValuesA.Add(double.NaN);
                    BloodVolumeValuesA.Add(double.NaN);
                    BloodOxygenationValuesA.Add(double.NaN);
                }
            }

            LastVitalSignsData = dataList.Last();
        }

19 Source : DataManager.cs
with MIT License
from ABTSoftware

public double[] LoadWaveformData()
        {
            var values = new List<double>();
            var asm = replacedembly.GetExecutingreplacedembly();
            var resourceString = asm.GetManifestResourceNames().Single(x => x.Contains("Waveform.txt.gz"));

            using (var stream = asm.GetManifestResourceStream(resourceString))
            using (var gz = new GZipStream(stream, CompressionMode.Decompress))
            using (var streamReader = new StreamReader(gz))
            {
                string line = streamReader.ReadLine();
                while (line != null)
                {
                    values.Add(double.Parse(line, NumberFormatInfo.InvariantInfo));
                    line = streamReader.ReadLine();
                }
            }

            return values.ToArray();
        }

19 Source : SweepingEcg.xaml.cs
with MIT License
from ABTSoftware

private double[] LoadWaveformData(string filename)
        {
            var values = new List<double>();

            // Load the waveform.csv file for the source data 
            var asm = typeof (SweepingEcg).replacedembly; 
            var resourceString = asm.GetManifestResourceNames().Single(x => x.Contains(filename));

            using (var stream = asm.GetManifestResourceStream(resourceString))
            using (var streamReader = new StreamReader(stream))
            {
                string line = streamReader.ReadLine();
                while (line != null)
                {
                    values.Add(double.Parse(line, NumberFormatInfo.InvariantInfo));
                    line = streamReader.ReadLine();
                }
            }

            return values.ToArray();
        }

19 Source : MillimeterDivisionsTickProvider.cs
with MIT License
from ABTSoftware

private static double[] GenerateTicks(DoubleRange tickRange, double size)
        {
            var ticks = new List<double>();

            var step = tickRange.Diff / size;
            for (int i = 0; i < size; i++)
            {
                ticks.Add(tickRange.Min + step * i);
            }

            return ticks.ToArray();
        }

19 Source : RandomWalkGenerator.cs
with MIT License
from ABTSoftware

public XyData GetRandomWalkSeries(int count)
        {
            var doubleSeries = new XyData();
            var xData = new List<double>(count);
            var yData = new List<double>(count);

            doubleSeries.XData = xData;
            doubleSeries.YData = yData;

            // Generate a slightly positive biased random walk
            // y[i] = y[i-1] + random, 
            // where random is in the range -0.5, +0.5
            for (int i = 0; i < count; i++)
            {
                var next = Next();

                xData.Add(next.X);
                yData.Add(next.Y);
            }

            return doubleSeries;
        }

19 Source : Hatch.cs
with GNU Lesser General Public License v3.0
from acnicholas

private bool replacedignFillGridsFromString(string[] grids, double scale, double rotationAngle)
        {
            var newFillGrids = new List<FillGrid>();
            foreach (string s in grids) {
                if (string.IsNullOrEmpty(s.Trim()))
                {
                    continue;
                }
                string[] segs = s.Split(',');
                if (segs.Count() < 5)
                {
                    return false;
                }
                var f = new FillGrid();
                List<double> lineSegs = new List<double>();
                if (!double.TryParse(segs[0], out var angle)) {
                    return false;
                }
                if (!double.TryParse(segs[1], out var x)) {
                    return false;
                }
                if (!double.TryParse(segs[2], out var y)) {
                    return false;
                }
                if (!double.TryParse(segs[3], out var shift)) {
                    return false;
                }
                if (!double.TryParse(segs[4], out var offset)) {
                    return false;
                }
                for (int i = 5; i < segs.Length; i++)
                {
                    if (!double.TryParse(segs[i], out var individualSeg))
                    {
                        return false;
                    }
                    individualSeg *= scale;
                    lineSegs.Add(Math.Abs(individualSeg.ToFeet()));
                }
                x *= scale;
                y *= scale;
                shift *= scale;
                offset *= scale;
                angle += rotationAngle;
                f.Angle = angle.ToRad();
                f.Origin = new UV(x.ToFeet(), y.ToFeet());
                f.Shift = shift.ToFeet();
                f.Offset = offset.ToFeet();
                f.SetSegments(lineSegs);
                newFillGrids.Add(f);              
            }
            fillPattern.SetFillGrids(newFillGrids);
            return true;
        }

19 Source : HatchCanvas.cs
with GNU Lesser General Public License v3.0
from acnicholas

private DrawingVisual CreateDrawingVisualHatch(Hatch hatch)
        {
            DrawingVisual drawingVisual = new DrawingVisual();
            if (hatch == null) {
                return drawingVisual;
            }

            DrawingContext drawingContext = drawingVisual.RenderOpen();

            double dx = 0;
            double dy = 0;

            var scale = hatch.IsDrafting ? 10 : 1;

            drawingContext.PushClip(new RectangleGeometry(new Rect(0, 0, width, height)));
            drawingContext.DrawRectangle(Brushes.White, null, new Rect(0, 0, width, height));
            drawingContext.PushTransform(new TranslateTransform(width / 2, height / 2));
            drawingContext.DrawEllipse(null, new Pen(Brushes.LightBlue, 1), new Point(0, 0), 10, 10);
            drawingContext.DrawLine(new Pen(Brushes.LightBlue, 1), new Point(-20, 0), new Point(20, 0));
            drawingContext.DrawLine(new Pen(Brushes.LightBlue, 1), new Point(0, -20), new Point(0, 20));
            drawingContext.PushTransform(new ScaleTransform(canvreplacedcale, canvreplacedcale));

            double maxLength = width > height ? width / canvreplacedcale * 2 : height / canvreplacedcale * 2;

            foreach (var fillGrid in hatch.HatchPattern.GetFillGrids()) {
                double scaledSequenceLength = GetDashedLineLength(fillGrid, 1, scale);
                double initialShiftOffset = scaledSequenceLength > 0 ? (int)Math.Floor(maxLength / scaledSequenceLength) * scaledSequenceLength : maxLength;
                if (scaledSequenceLength > maxLength / 4) {
                    initialShiftOffset = scaledSequenceLength * 16;
                }

                var segsInMM = new List<double>();
                foreach (var s in fillGrid.GetSegments()) {
                    segsInMM.Add(s.ToMM(scale));
                }

                if (Math.Abs(fillGrid.Offset) < 0.001) {
                    continue;
                }

                int b = 0;

                var pen = new Pen(Brushes.Black, 1);
                pen.DashStyle = new DashStyle(segsInMM, initialShiftOffset);

                double a = fillGrid.Angle.ToDeg();
                drawingContext.PushTransform(new RotateTransform(-a, fillGrid.Origin.U.ToMM(scale), -fillGrid.Origin.V.ToMM(scale)));

                double replacedulativeShift = 0;

                while (Math.Abs(dy) < maxLength * 2) {
                    b++;
                    if (b > 100) {
                        break;
                    }
                    double x = fillGrid.Origin.U.ToMM(scale) - initialShiftOffset;
                    double y = -fillGrid.Origin.V.ToMM(scale);
                    drawingContext.PushTransform(new TranslateTransform(x + dx, y - dy));
                    drawingContext.DrawLine(pen, new Point(0, 0), new Point(initialShiftOffset * 2, 0));
                    drawingContext.Pop();
                    drawingContext.PushTransform(new TranslateTransform(x - dx, y + dy));
                    drawingContext.DrawLine(pen, new Point(0, 0), new Point(initialShiftOffset * 2, 0));
                    drawingContext.Pop();
                    dx += fillGrid.Shift.ToMM(scale);
                    replacedulativeShift += fillGrid.Shift.ToMM(scale);
                    if (Math.Abs(replacedulativeShift) > scaledSequenceLength) {
                        dx -= scaledSequenceLength;
                        replacedulativeShift = 0;
                    }
                    dy += fillGrid.Offset.ToMM(scale);
                }
                drawingContext.Pop();
                dx = 0;
                dy = 0;
            }
            drawingContext.Pop();
            drawingContext.Pop();
            drawingContext.Pop();

            drawingContext.DrawText(
                new FormattedText(
                    string.Format(System.Globalization.CultureInfo.InvariantCulture, "Scale: {0}", scale * canvreplacedcale),
                    System.Globalization.CultureInfo.InvariantCulture,
                    FlowDirection.LeftToRight,
                    new Typeface("arial"),
                    10,
                    Brushes.LightBlue,
                    1),
                new Point(10, 10));

            drawingContext.Close();
            return drawingVisual;
        }

19 Source : DelimitedDoubleListTypeConverter.cs
with MIT License
from Actipro

public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
			var delimitedString = value as string;
			if (!string.IsNullOrEmpty(delimitedString)) {
				double numberValue;
				var list = new List<double>();
				var numberStrings = delimitedString.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
				foreach (var numberString in numberStrings) {
					if (double.TryParse(numberString, out numberValue))
						list.Add(numberValue);
				}

				return list;
			}

			return base.ConvertFrom(context, culture, value);
		}

19 Source : _mnMatrix.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _mnMatrix AddAnotherMatrix(_mnMatrix matrix)
        {
            var MatrixComponents = new List<_nVector>();
            int i = 1, j = 1;
            foreach (var vctor in rows)
            {
                var tmpVctor = new List<double>();
                foreach (var component in vctor.Value.vector)
                {
                    tmpVctor.Add(component + matrix.GetValueAt(i, j));
                    j++;
                }
                MatrixComponents.Add(new _nVector(tmpVctor));
                j = 1;
                i++;
            }
            return new _mnMatrix(MatrixComponents, i, j);

        }

19 Source : _nMatrix.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _nVector GetColumn(int index)
        {
            var col = new List<double>();
            foreach (var row in rows)
            {
                col.Add(row.Value.vector[index]);
            }
            return new _nVector(col);
        }

19 Source : _nMatrix.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _nVector GetSubRow(int m, int k)
        {
            var mRows = new List<_nVector>();
            int skipRows = n - m, skipCols = n - k;
            var nVector = new List<double>();
            for (int j = skipCols; j < n; j++)
            {
                nVector.Add(rows[skipRows].vector[j]);
            }
            var tempNVector = new _nVector(nVector);


            return tempNVector;

        }

19 Source : _nMatrix.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _nMatrix GetSubMatrix(int m)
        {
            var mRows = new List<_nVector>();
            int skipRows = n - m, skipCols = n - m;
            for (int i = skipRows; i < n; i++)
            {
                var nVector = new List<double>();
                for (int j = skipRows; j < n; j++)
                {
                    nVector.Add(rows[i].vector[j]);
                }
                var tempNVector = new _nVector(nVector);
                mRows.Add(tempNVector);
            }
            return new _nMatrix(mRows, m);

        }

19 Source : _nMatrix.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _mnMatrix GetSubMatrix(int m, int k)
        {
            var mRows = new List<_nVector>();
            int skipRows = m, skipCols = k;
            for (int i = skipRows; i < n; i++)
            {
                var nVector = new List<double>();
                for (int j = skipCols; j < n; j++)
                {
                    nVector.Add(rows[i].vector[j]);
                }
                var tempNVector = new _nVector(nVector);
                mRows.Add(tempNVector);
            }
            return new _mnMatrix(mRows, n - k, n - m);

        }

19 Source : _nMatrix.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _nMatrix MultiplyByScalar(double scalar)
        {
            var MatrixComponents = new List<_nVector>();
            int i = 1, j = 1;
            foreach (var vctor in rows)
            {
                var tmpVctor = new List<double>();
                foreach (var component in vctor.Value.vector)
                {
                    tmpVctor.Add(component * scalar);
                    j++;
                }
                MatrixComponents.Add(new _nVector(tmpVctor));
                j = 1;
                i++;
            }
            return new _nMatrix(MatrixComponents, n);

        }

19 Source : _nMatrix.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _nMatrix AddAnotherMatrix(_nMatrix matrix)
        {
            var MatrixComponents = new List<_nVector>();
            int i = 1, j = 1;
            foreach (var vctor in rows)
            {
                var tmpVctor = new List<double>();
                foreach (var component in vctor.Value.vector)
                {
                    tmpVctor.Add(component + matrix.GetValueAt(i, j));
                    j++;
                }
                MatrixComponents.Add(new _nVector(tmpVctor));
                j = 1;
                i++;
            }
            return new _nMatrix(MatrixComponents, n);

        }

19 Source : _nMatrix.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _nMatrix SubtractAnotherMatrix(_nMatrix matrix)
        {
            var MatrixComponents = new List<_nVector>();
            int i = 1, j = 1;
            foreach (var vctor in rows)
            {
                var tmpVctor = new List<double>();
                foreach (var component in vctor.Value.vector)
                {
                    tmpVctor.Add(component - matrix.GetValueAt(i, j));
                    j++;
                }
                MatrixComponents.Add(new _nVector(tmpVctor));
                j = 1;
                i++;
            }
            return new _nMatrix(MatrixComponents, n);

        }

19 Source : _nMatrix.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _nVector MultiplyByVector(_nVector vector)
        {
            double[,] a = new double[n, n];
            for (int j = 1; j <= n; j++)
            {
                for (int i = 1; i <= n; i++)
                {
                    a[i - 1, j - 1] = GetValueAt(j, i) * vector.V(i);
                }
            }

            var vec = new List<double>();
            for (int i = 0; i < n; i++)
            {
                double temp = 0;
                for (int j = 0; j < n; j++)
                {
                    temp += a[i, j];

                }
                vec.Add(temp);
            }

            return new _nVector(vec);
        }

19 Source : _nMatrix.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _nMatrix CreateCopy(_nMatrix matrix)
        {
            var matrixRows = new List<_nVector>();
            int cntr = 0;
            foreach (var vctor in matrix.rows)
            {
                var tempVecList = new List<double>();
                for (int i = 0; i < matrix.n; i++)
                {
                    tempVecList.Add(vctor.Value.vector[i]);
                }
                matrixRows.Add(new _nVector(tempVecList));
                cntr++;
            }

            return new _nMatrix(matrixRows, matrix.n);
        }

19 Source : _nVector.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _nVector MultiplyByScalar(double scalar)
        {
            var componentList = new List<double>();
            foreach (var component in vector)
            {
                componentList.Add(component * scalar);
            }

            return new _nVector(componentList);
        }

19 Source : _nVector.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _mnMatrix mnMatrixTypeMultiplyWithAnotherVector(_nVector vec)
        {
            var componentList = new List<double>();
            var dictionary = new List<_nVector>();
            int i = 0, j = 0;
            foreach (var component in vector)
            {
                var vctor = new List<double>();
                foreach (var component2 in vec.vector)
                {
                    vctor.Add(component * component2);
                }
                dictionary.Add(new _nVector(vctor));
                i++;
            }
            return new _mnMatrix(dictionary, i, j);
        }

19 Source : _mnMatrix.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _mnMatrix MultiplyByScalar(double scalar)
        {
            var MatrixComponents = new List<_nVector>();
            int i = 1, j = 1;
            foreach (var vctor in rows)
            {
                var tmpVctor = new List<double>();
                foreach (var component in vctor.Value.vector)
                {
                    tmpVctor.Add(component * scalar);
                    j++;
                }
                MatrixComponents.Add(new _nVector(tmpVctor));
                j = 1;
                i++;
            }
            return new _mnMatrix(MatrixComponents, i, j);

        }

19 Source : _mnMatrix.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _mnMatrix ReturnTranspose(_mnMatrix matrix)
        {
            var nn = matrix.n;//rows
            var mm = matrix.m;//columns
            var tempVectors = new List<_nVector>();
            for (int i = 0; i < mm; i++)
            {
                var tempVectorList = new List<double>();
                for (int j = 0; j < nn; j++)
                {
                    tempVectorList.Add(matrix.GetValueAt(j + 1, i + 1));
                }
                tempVectors.Add(new _nVector(tempVectorList));
            }
            return new _mnMatrix(tempVectors, mm, nn);
        }

19 Source : _nVector.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _nVector Subtract(_nVector nVector)
        {
            var vec = new List<double>();
            int cntr = 0;
            foreach (var value in vector)
            {
                vec.Add(value - nVector.vector[cntr]);
                cntr++;
            }
            return new _nVector(vec);
        }

19 Source : nIdentityMatrix.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _nMatrix ReturnNIdenreplacedyMatrix(int n)
        {
            var matrixRows = new List<_nVector>();
            for (int i = 0; i < n; i++)
            {
                var row = new List<double>();
                for (int j = 0; j < n; j++)
                {
                    if (j == i)
                    {
                        row.Add(1);
                    }
                    else
                    {
                        row.Add(0);
                    }
                }
                var vectorRow = new _nVector(row);
                matrixRows.Add(vectorRow);
            }
            return new _nMatrix(matrixRows, n);
        }

19 Source : _mnMatrix.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _nVector MultiplyByVector(_nVector vector)
        {
            double[,] a = new double[m, n];
            for (int j = 1; j <= n; j++)
            {
                for (int i = 1; i <= m; i++)
                {
                    a[i - 1, j - 1] = GetValueAt(j, i) * vector.V(i);
                }
            }

            var vec = new List<double>();
            for (int i = 0; i < n; i++)
            {
                double temp = 0;
                for (int j = 0; j < m; j++)
                {
                    temp += a[j, i];

                }
                vec.Add(temp);
            }

            return new _nVector(vec);
        }

19 Source : _mnMatrix.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _mnMatrix SubtractAnotherMatrix(_mnMatrix matrix)
        {
            var MatrixComponents = new List<_nVector>();
            int i = 1, j = 1;
            foreach (var vctor in rows)
            {
                var tmpVctor = new List<double>();
                foreach (var component in vctor.Value.vector)
                {
                    tmpVctor.Add(component - matrix.GetValueAt(i, j));
                    j++;
                }
                MatrixComponents.Add(new _nVector(tmpVctor));
                j = 1;
                i++;
            }
            return new _mnMatrix(MatrixComponents, i, j);

        }

19 Source : _nVector.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _nVector MultiplyByMatrix(_nMatrix matrix)
        {
            var n = matrix.n;
            var componentList = new List<double>();
            for (int i = 0; i < n; i++)
            {
                double sum = 0;
                for (int j = 0; j < n; j++)
                {
                    sum += vector[j] * matrix.GetValueAt(j + 1, i + 1);
                }
                componentList.Add(sum);
            }
            return new _nVector(componentList);
        }

19 Source : _nVector.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _nMatrix MatrixTypeMultiplyWithAnotherVector(_nVector vec)
        {
            var componentList = new List<double>();
            int n = this.vector.Count();
            double[,] matrixComponents = new double[n, n];
            var dictionary = new List<_nVector>();
            int i = 0;
            foreach (var component in vector)
            {
                var vctor = new List<double>();
                foreach (var component2 in vec.vector)
                {
                    vctor.Add(component * component2);
                }
                dictionary.Add(new _nVector(vctor));
                i++;
            }
            return new _nMatrix(dictionary, n);
        }

19 Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

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

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

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

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

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

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

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

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

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

g = geocoder.ip('me')

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

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


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

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

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


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



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



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

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


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


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

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

                    }
                }
            }
        }

19 Source : HouseholderBase.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _nVector iComponentVector(int m)
        {
            var Components = new List<double>();
            Components.Add(1);
            for (int i = 0; i < m - 1; i++)
            {
                Components.Add(0);
            }
            return new _nVector(Components);
        }

19 Source : _mnMatrix.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _mnMatrix GetSubMatrix(int mm, int k)
        {
            var mRows = new List<_nVector>();
            int skipRows = m - mm, skipCols = m - k;
            for (int i = skipRows; i < m; i++)
            {
                var nVector = new List<double>();
                for (int j = skipCols; j < m; j++)
                {
                    nVector.Add(rows[i].vector[j]);
                }
                var tempNVector = new _nVector(nVector);
                mRows.Add(tempNVector);
            }
            return new _mnMatrix(mRows, mm, k);

        }

19 Source : _nMatrix.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _nMatrix ReturnTranspose(_nMatrix matrix)
        {
            var tempVectors = new List<_nVector>();
            for (int i = 0; i < n; i++)
            {
                var tempVectorList = new List<double>();
                for (int j = 0; j < n; j++)
                {
                    tempVectorList.Add(GetValueAt(j + 1, i + 1));
                }
                tempVectors.Add(new _nVector(tempVectorList));
            }
            return new _nMatrix(tempVectors, n);
        }

19 Source : _nVector.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _nVector Add(_nVector nVector)
        {
            var vec = new List<double>();
            int cntr = 0;
            foreach (var value in vector)
            {
                vec.Add(value + nVector.vector[cntr]);
                cntr++;
            }
            return new _nVector(vec);
        }

19 Source : _nVector.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public _nMatrix MatrixTypeMultiplyWithMe()
        {
            var componentList = new List<double>();
            int n = this.vector.Count();
            double[,] matrixComponents = new double[n, n];
            var dictionary = new List<_nVector>();
            int i = 0;
            foreach (var component in vector)
            {
                var vctor = new List<double>();
                foreach (var component2 in vector)
                {
                    vctor.Add(component * component2);
                }
                dictionary.Add(new _nVector(vctor));
                i++;
            }
            return new _nMatrix(dictionary, n);
        }

19 Source : NeuralLearner.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public static Dictionary<IObject, Func<double, double>>
            ExtrapolateAllObjectMethods(IList<IObject> objects, int testThreshold)
        {
            var rnd = new Random();
            var funcPerObjectPermiationMethodDictionary =
                    new Dictionary<IObject, Func<double, double>>();
            foreach (var obj in objects)
            {

                var allObjectPermeabilities = obj.TestAllObjectPermeabilities();
                foreach (var objectFunction in allObjectPermeabilities)
                {
                    var regressionPoints = new List<double>();
                    for (int i = 0; i < testThreshold; i++)
                    {
                        double randomValue = rnd.NextDouble();
                        regressionPoints.Add(objectFunction.Yval(randomValue));
                    }
                    funcPerObjectPermiationMethodDictionary.Add(obj,
                        UnivariateRegressionFitting.
                        ExponentialDistributionFit(regressionPoints));
                }
            }
            return funcPerObjectPermiationMethodDictionary;
        }

19 Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public static IList<double> GetColumn(IList<IList<double>> gridValues, int column)
        {
            var columnValues = new List<double>();
            foreach (var row in gridValues)
            {
                columnValues.Add(row[column]);
            }
            return columnValues;
        }

19 Source : DmnDecisionTable.cs
with MIT License
from adamecr

private static PositiveRulesCollectValues CalculatePositiveRulesCollectValues(
            IEnumerable<DmnDecisionTableRule> positiveRules,
            DmnDecisionTableRuleExecutionResults results)
        {
            double sum = 0;
            var min = double.MaxValue;
            var max = double.MinValue;

            var distinctValues = new List<double>();

            foreach (var positiveRule in positiveRules)
            {
                var valueRaw = results.GetResult(positiveRule, positiveRule.Outputs[0])?.Value;
                if (valueRaw == null) continue; //ignore null results/values

                double value;
                var isBool = positiveRule.Outputs[0].Output.Variable.Type == typeof(bool);
                if (isBool)
                {
                    value = (bool)valueRaw ? 1 : 0;
                }
                else
                {
                    value = (double)Convert.ChangeType(valueRaw, typeof(double));
                }

                sum += value;
                if (value < min) min = value;
                if (value > max) max = value;
                if (!distinctValues.Contains(value))
                {
                    distinctValues.Add(value);
                }
            }

            var count = distinctValues.Count;
            return new PositiveRulesCollectValues(sum, min, max, count);
        }

19 Source : actionChecker.cs
with MIT License
from AlbertMN

[STAThread]
        public void ProcessFile(string file, bool tryingAgain = false) {
            //Custom 'file read delay'
            float fileReadDelay = Properties.Settings.Default.FileReadDelay;
            if (fileReadDelay > 0) {
                MainProgram.DoDebug("User has set file delay to " + fileReadDelay.ToString() + "s, waiting before processing...");
                Thread.Sleep((int)fileReadDelay * 1000);
            }

            if (!File.Exists(file)) {
                MainProgram.DoDebug("File doesn't exist (anymore).");
                return;
            }

            //Make sure the file isn't in use before trying to access it
            int tries = 0;
            while (FileInUse(file) || tries >= 20) {
                tries++;
            }
            if (tries >= 20 && FileInUse(file)) {
                MainProgram.DoDebug("File in use in use and can't be read. Try again.");
                return;
            }

            //Check unique file ID (dublicate check)
            ulong theFileUid = 0;
            bool gotFileUid = false;
            tries = 0;
            while (!gotFileUid || tries >= 30) {
                try {
                    theFileUid = getFileUID(file);
                    gotFileUid = true;
                } catch {
                    Thread.Sleep(50);
                }
            }
            if (tries >= 30 && !gotFileUid) {
                MainProgram.DoDebug("File in use in use and can't be read. Try again.");
                return;
            }


            //Validate UID
            if (lastFileUid == 0) {
                lastFileUid = Properties.Settings.Default.LastActionFileUid;
            }
            if (lastFileUid == theFileUid && !tryingAgain) {
                //Often times this function is called three times per file - check if it has already been (or is being) processed
                return;
            }
            if (executedFiles.Contains(theFileUid) && !tryingAgain) {
                MainProgram.DoDebug("Tried to execute an already-executed file (UID " + theFileUid.ToString() + ")");
                return;
            }
            lastFileUid = theFileUid;
            executedFiles.Add(theFileUid);
            Properties.Settings.Default.LastActionFileUid = lastFileUid;
            Properties.Settings.Default.Save();

            MainProgram.DoDebug("Processing file...");
            string originalFileName = file, fullContent = "";

            if (!File.Exists(file)) {
                MainProgram.DoDebug("File no longer exists when trying to read file.");
                return;
            }

            //READ FILE
            if (new FileInfo(file).Length != 0) {
                try {
                    string fileContent;
                    fileContent = File.ReadAllText(file);
                    fullContent = Regex.Replace(fileContent, @"\t|\r", "");
                } catch (Exception e) {
                    if (unsuccessfulReads < 20) {
                        MainProgram.DoDebug("Failed to read file - trying again in 200ms... (trying max 20 times)");
                        unsuccessfulReads++;
                        Thread.Sleep(200);
                        ProcessFile(file, true);

                        return;
                    } else {
                        MainProgram.DoDebug("Could not read file on final try; " + e);
                        unsuccessfulReads = 0;
                        return;
                    }
                }
                MainProgram.DoDebug(" - Read complete, content: " + fullContent);
            } else {
                MainProgram.DoDebug(" - File is empty");
                ErrorMessageBox("No action was set in the action file.");
            }
            //END READ

            //DateTime lastModified = File.GetCreationTime(file);
            DateTime lastModified = File.GetLastWriteTime(file);
 
            if (lastModified.AddSeconds(Properties.Settings.Default.FileEditedMargin) < DateTime.Now) {
                //if (File.GetLastWriteTime(file).AddSeconds(Properties.Settings.Default.FileEditedMargin) < DateTime.Now) {
                //Extra security - sometimes the "creation" time is a bit behind, but the "modify" timestamp is usually right.

                MainProgram.DoDebug("File creation time: " + lastModified.ToString());
                MainProgram.DoDebug("Local time: " + DateTime.Now.ToString());

                if (GettingStarted.isConfiguringActions) {
                    //Possibly configure an offset - if this always happens

                    Console.WriteLine("File is actually too old, but configuring the software to maybe set an offset");

                    isConfiguringOffset = true;
                    if (lastModifiedOffsets == null) {
                        lastModifiedOffsets = new List<double>();
                    }

                    lastModifiedOffsets.Add((DateTime.Now - lastModified).TotalSeconds);
                    if (lastModifiedOffsets.Count >= 3) {
                        int average = (int)(lastModifiedOffsets.Average());
                        Console.WriteLine("File Margin fixed offset set to; " + average.ToString());
                        Properties.Settings.Default.AutoFileMarginFixer = average;
                        Properties.Settings.Default.Save();
                    }
                } else {
                    bool isGood = false;

                    if (Properties.Settings.Default.AutoFileMarginFixer != 0) {
                        //if (lastModified.AddSeconds(-Properties.Settings.Default.AutoFileMarginFixer) < DateTime.Now) {

                        var d1 = lastModified.AddSeconds(-Properties.Settings.Default.FileEditedMargin);
                        var d2 = DateTime.Now.AddSeconds(-Properties.Settings.Default.AutoFileMarginFixer);

                        if (d1 < d2) {
                            isGood = true;
                            MainProgram.DoDebug("File timestamp is actually more than " + Properties.Settings.Default.FileEditedMargin.ToString() + "s old, but the software is configured to have an auto-file-margin fix for " + Properties.Settings.Default.AutoFileMarginFixer.ToString() + "s");
                        } else {
                            //MainProgram.DoDebug(d1.ToString());
                            //MainProgram.DoDebug(d2.ToString());
                            MainProgram.DoDebug("The " + Properties.Settings.Default.AutoFileMarginFixer.ToString() + "s didn't fix it");
                        }
                    }

                    if (!isGood) {
                        MainProgram.DoDebug("The file is more than " + Properties.Settings.Default.FileEditedMargin.ToString() + "s old, meaning it won't be executed.");
                        new CleanupService().Start();
                        return;
                    }
                }
                //}
            }
            
            MainProgram.DoDebug("\n[ -- DOING ACTION(S) -- ]");
            MainProgram.DoDebug(" - " + file + " UID; " + theFileUid);
            MainProgram.DoDebug(" - File exists, checking the content...");

            //Process the file
            using (StringReader reader = new StringReader(fullContent)) {
                string theLine = string.Empty;
                do {
                    theLine = reader.ReadLine();
                    if (theLine != null) {
                        MainProgram.DoDebug("\n[EXECUTING ACTION]");
                        CheckAction(theLine, file);
                    }

                } while (theLine != null);
            }

            MainProgram.DoDebug("[ -- DONE -- ]");
        }

19 Source : MKMPriceAsFormula.cs
with GNU Affero General Public License v3.0
from alexander-pick

private bool parseAndAddOperand(string operand)
    {
      double number = MKMHelpers.ConvertDoubleAnySep(operand);
      if (double.IsNaN(number))
      {
        foreach (var guide in MKMHelpers.PriceGuides)
        {
          if (guide.Value.Code == operand)
          {
            guidesToResolve.Add(new KeyValuePair<int, string>(operands.Count, operand));
            operands.Add(-9999);
            return true;
          }
        }
      }
      else
      {
        operands.Add(number);
        return true;
      }
      return false;
    }

19 Source : AMD10CPU.cs
with MIT License
from AlexGyver

private double estimateTimeStampCounterMultiplier() {
      // preload the function
      estimateTimeStampCounterMultiplier(0);
      estimateTimeStampCounterMultiplier(0);

      // estimate the multiplier
      List<double> estimate = new List<double>(3);
      for (int i = 0; i < 3; i++)
        estimate.Add(estimateTimeStampCounterMultiplier(0.025));
      estimate.Sort();
      return estimate[1];
    }

19 Source : CategoryAxis.cs
with MIT License
from AlexGyver

public override void GetTickValues(
            out IList<double> majorLabelValues, out IList<double> majorTickValues, out IList<double> minorTickValues)
        {
            base.GetTickValues(out majorLabelValues, out majorTickValues, out minorTickValues);
            minorTickValues.Clear();

            if (!this.IsTickCentered)
            {
                // Subtract 0.5 from the label values to get the tick values.
                // Add one extra tick at the end.
                var mv = new List<double>(majorLabelValues.Count);
                mv.AddRange(majorLabelValues.Select(v => v - 0.5));
                if (mv.Count > 0)
                {
                    mv.Add(mv[mv.Count - 1] + 1);
                }

                majorTickValues = mv;
            }
        }

19 Source : KalmanFilter.cs
with Apache License 2.0
from AlexWan

private decimal GetValue(List<Candle> candles, int index)
        {
            //Kalman[i]=Error+Velocity[i], where
            //Error=Kalman[i-1]+Distance*ShK,
            //Velocity[i]=Velocity[i-1]+Distance*K/100,
            //Distance=Price[i]-Kalman[i-1],
            //ShK=sqrt(Sharpness*K/100).

            if (index == 0)
            {
                _velocity.Add(0);
                return 0;
            }

            double shk = Math.Sqrt(Convert.ToDouble(_sharpness.ValueDecimal * K.ValueDecimal / 100));
            double distans = Convert.ToDouble(candles[index].Close - _series.Values[index - 1]);

            if (index + 1 > _velocity.Count)
            {
                _velocity.Add(0);
            }

            _velocity[index] = _velocity[index - 1] + distans * Convert.ToDouble(K.ValueDecimal) / 100;

            double error = Convert.ToDouble(_series.Values[index - 1]) + distans * shk;

            return Convert.ToDecimal(error + _velocity[index]);
        }

19 Source : KalmanFilter.cs
with Apache License 2.0
from AlexWan

private decimal GetValue(List<Candle> candles, int index)
        {
            //Kalman[i]=Error+Velocity[i], where
            //Error=Kalman[i-1]+Distance*ShK,
            //Velocity[i]=Velocity[i-1]+Distance*K/100,
            //Distance=Price[i]-Kalman[i-1],
            //ShK=sqrt(Sharpness*K/100).

            if (index == 0)
            {
                _velocity.Add(0);
                return 0;
            }

            double shk = Math.Sqrt(Convert.ToDouble(Sharpness * K / 100));
            double distans = Convert.ToDouble(candles[index].Close - Values[index - 1]);

            if (index + 1 > _velocity.Count)
            {
                _velocity.Add(0);
            }

            _velocity[index] = _velocity[index - 1] + distans * Convert.ToDouble(K) / 100;

            double error = Convert.ToDouble(Values[index - 1]) + distans * shk;

            return Convert.ToDecimal(error + _velocity[index]);
        }

19 Source : BarChartNodeModel.cs
with MIT License
from alfarok

private void DataBridgeCallback(object data)
        {
            // Grab input data which always returned as an ArrayList
            var inputs = data as ArrayList;

            // Each of the list inputs are also returned as ArrayLists
            var labels = inputs[0] as ArrayList;
            var values = inputs[1] as ArrayList;
            var colors = inputs[2] as ArrayList;

            // Only continue if key/values match in length
            if(labels.Count != values.Count || labels.Count < 1)
            {
                throw new Exception("Label and Values do not properly align in length.");
            }

            // Update chart properties
            Labels = new List<string>();
            Values = new List<List<double>>();
            Colors = new List<SolidColorBrush>();

            if (colors.Count != labels.Count)
            {
                for (var i = 0; i < labels.Count; i++)
                {
                    Labels.Add((string)labels[i]);

                    var unpackedValues = values[i] as ArrayList;
                    var labelValues = new List<double>();

                    for (var j = 0; j < unpackedValues.Count; j++)
                    {
                        labelValues.Add(Convert.ToDouble(unpackedValues[j]));
                    }

                    Values.Add(labelValues);
                    Color randomColor = Color.FromArgb(255, (byte)rnd.Next(256), (byte)rnd.Next(256), (byte)rnd.Next(256));
                    SolidColorBrush brush = new SolidColorBrush(randomColor);
                    brush.Freeze();
                    Colors.Add(brush);
                }
            }
            else
            {
                for (var i = 0; i < labels.Count; i++)
                {
                    Labels.Add((string)labels[i]);

                    var unpackedValues = values[i] as ArrayList;
                    var labelValues = new List<double>();

                    for (var j = 0; j < unpackedValues.Count; j++)
                    {
                        labelValues.Add(Convert.ToDouble(unpackedValues[j]));
                    }

                    Values.Add(labelValues);

                    var dynColor = (DSCore.Color)colors[i];
                    var convertedColor = Color.FromArgb(dynColor.Alpha, dynColor.Red, dynColor.Green, dynColor.Blue);
                    SolidColorBrush brush = new SolidColorBrush(convertedColor);
                    brush.Freeze();
                    Colors.Add(brush);
                }
            }

            // Notify UI the data has been modified
            RaisePropertyChanged("DataUpdated");
        }

19 Source : PieChartNodeModel.cs
with MIT License
from alfarok

private void DataBridgeCallback(object data)
        {
            // Grab input data which always returned as an ArrayList
            var inputs = data as ArrayList;

            // Each of the list inputs are also returned as ArrayLists
            var keys = inputs[0] as ArrayList;
            var values = inputs[1] as ArrayList;
            var colors = inputs[2] as ArrayList;

            // Only continue if key/values match in length
            if(keys.Count != values.Count || keys.Count < 1)
            {
                throw new Exception("Label and Values do not properly align in length.");
            }

            // Update chart properties
            Labels = new List<string>();
            Values = new List<double>();
            Colors = new List<SolidColorBrush>();

            if (colors.Count != keys.Count)
            {
                for (var i = 0; i < keys.Count; i++)
                {
                    Labels.Add((string)keys[i]);
                    Values.Add(System.Convert.ToDouble(values[i]));
                    Color randomColor = Color.FromArgb(255, (byte)rnd.Next(256), (byte)rnd.Next(256), (byte)rnd.Next(256));
                    SolidColorBrush brush = new SolidColorBrush(randomColor);
                    brush.Freeze();
                    Colors.Add(brush);
                }
            }
            else
            {
                for (var i = 0; i < keys.Count; i++)
                {
                    Labels.Add((string)keys[i]);
                    Values.Add(System.Convert.ToDouble(values[i]));
                    var dynColor = (DSCore.Color)colors[i];
                    var convertedColor = Color.FromArgb(dynColor.Alpha, dynColor.Red, dynColor.Green, dynColor.Blue);
                    SolidColorBrush brush = new SolidColorBrush(convertedColor);
                    brush.Freeze();
                    Colors.Add(brush);
                }
            }

            // Notify UI the data has been modified
            RaisePropertyChanged("DataUpdated");
        }

See More Examples