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

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

1276 Examples 7

19 Source : TempTableBuilderTest.cs
with MIT License
from 0x1000000

[Test]
        public void BasicTest()
        {
            var data = new[]
            {
                new
                {
                    Bool = true,
                    Byte = byte.MaxValue,
                    Int16 = short.MaxValue,
                    Int32 = int.MaxValue,
                    Int64 = long.MaxValue,
                    Decimal = decimal.MaxValue,
                    Double = 123.456,
                    String = "ABCD",
                    DateTime = new DateTime(2099, 1, 1),
                    Guid = Guid.Parse("37197F28-AAED-480B-BA66-2C4D67A57E33")
                },
                new
                {
                    Bool = true,
                    Byte = byte.MinValue,
                    Int16 = short.MinValue,
                    Int32 = int.MinValue,
                    Int64 = long.MinValue,
                    Decimal = decimal.MinValue,
                    Double = -123.456,
                    String = "ABCDABCD",
                    DateTime = new DateTime(1900, 1, 1),
                    Guid = Guid.Parse("E8C3620B-B8CD-4574-A074-ACE09AA3DA8A")
                },
            };

            List<List<ExprValue>> dataList = new List<List<ExprValue>>(data.Length);

            foreach (var row in data)
            {
                var l = new List<ExprValue>();

                l.Add(SqQueryBuilder.Literal(row.Bool));
                l.Add(SqQueryBuilder.Literal(row.Byte));
                l.Add(SqQueryBuilder.Literal(row.Int16));
                l.Add(SqQueryBuilder.Literal(row.Int32));
                l.Add(SqQueryBuilder.Literal(row.Int64));
                l.Add(SqQueryBuilder.Literal(row.Decimal));
                l.Add(SqQueryBuilder.Literal(row.Double));
                l.Add(SqQueryBuilder.Literal(row.String));
                l.Add(SqQueryBuilder.Literal(row.DateTime));
                l.Add(SqQueryBuilder.Literal(row.Guid));

                dataList.Add(l);
            }

            var derivedTable = SqQueryBuilder.Values(dataList).AsColumns("Bool","Byte", "Int16", "Int32", "Int64", "Decimal", "Double", "String", "DateTime", "Guid");

            var q = TempTableData.FromDerivedTableValuesInsert(derivedTable, new []{ derivedTable.Columns[2], derivedTable.Columns[3] }, out var table, name: "TestTmpTable");

            var sql = q.ToMySql();
            replacedert.AreEqual(sql, "CREATE TEMPORARY TABLE `TestTmpTable`(`Bool` bit,`Byte` tinyint unsigned,`Int16` smallint,`Int32` int,`Int64` bigint,`Decimal` decimal(29,0),`Double` double,`String` varchar(8) character set utf8,`DateTime` datetime,`Guid` binary(16),CONSTRAINT PRIMARY KEY (`Int16`,`Int32`));INSERT INTO `TestTmpTable`(`Bool`,`Byte`,`Int16`,`Int32`,`Int64`,`Decimal`,`Double`,`String`,`DateTime`,`Guid`) VALUES (true,255,32767,2147483647,9223372036854775807,79228162514264337593543950335,123.456,'ABCD','2099-01-01',0x287F1937EDAA0B48BA662C4D67A57E33),(true,0,-32768,-2147483648,-9223372036854775808,-79228162514264337593543950335,-123.456,'ABCDABCD','1900-01-01',0x0B62C3E8CDB87445A074ACE09AA3DA8A)");

            sql = q.ToSql();
            replacedert.AreEqual(sql, "CREATE TABLE [#TestTmpTable]([Bool] bit,[Byte] tinyint,[Int16] smallint,[Int32] int,[Int64] bigint,[Decimal] decimal(29,0),[Double] float,[String] [nvarchar](8),[DateTime] datetime,[Guid] uniqueidentifier,CONSTRAINT [PK_TestTmpTable] PRIMARY KEY ([Int16],[Int32]));INSERT INTO [#TestTmpTable]([Bool],[Byte],[Int16],[Int32],[Int64],[Decimal],[Double],[String],[DateTime],[Guid]) VALUES (1,255,32767,2147483647,9223372036854775807,79228162514264337593543950335,123.456,'ABCD','2099-01-01','37197f28-aaed-480b-ba66-2c4d67a57e33'),(1,0,-32768,-2147483648,-9223372036854775808,-79228162514264337593543950335,-123.456,'ABCDABCD','1900-01-01','e8c3620b-b8cd-4574-a074-ace09aa3da8a')");
            
        }

19 Source : LandLord.cs
with Apache License 2.0
from 2881099

public void SearchStraight()
        {
            if (_shouPai.Count < 5) return;//不足5个牌就不处理的
            List<int> _tempone = new List<int>(_one);
            if (_tempone.Contains((int)LordPokerValueNoColorEnum.p15)) _tempone.Remove((int)LordPokerValueNoColorEnum.p15);    // ,2,小王,大王 不能组成连子
            if (_tempone.Contains((int)LordPokerValueNoColorEnum.jokers16)) _tempone.Remove((int)LordPokerValueNoColorEnum.jokers16);
            if (_tempone.Contains((int)LordPokerValueNoColorEnum.jokersb17)) _tempone.Remove((int)LordPokerValueNoColorEnum.jokersb17);
            if (_tempone.Count < 5) return;//不足5个牌就不处理的
            List<int> _minStraight = new List<int>();
            for (int i = 0; i < _tempone.Count - 1; i++)
            {
                if (_tempone[i] - 1 == _tempone[i + 1])
                {
                    _minStraight.Add(_tempone[i]);
                    if (i + 1 == _tempone.Count - 1) _minStraight.Add(_tempone[i + 1]);//最后一个要加上
                }
                else
                {//可能会出现刚才好5个,而后还有牌,搜索不到
                    _minStraight.Add(_tempone[i]);
                    if (_minStraight.Count >= 5) _straight.Add(_minStraight);
                    _minStraight = new List<int>();
                }
            }
            if (_minStraight.Count >= 5) _straight.Add(_minStraight);//最后一组必须加进去 不然一个长连子没搜索到
        }

19 Source : LandLord.cs
with Apache License 2.0
from 2881099

public void SearchLinkerPair()
        {
            if (_shouPai.Count < 6) return;//不足6个牌就不处理的
            List<int> _temptwo = new List<int>(_two);
            if (_temptwo.Contains((int)LordPokerValueNoColorEnum.p15)) _temptwo.Remove((int)LordPokerValueNoColorEnum.p15);    // ,2 不能组成连子   
            if (_temptwo.Count < 3) return;//不足6个牌就不处理的

            List<int> _minLinker = new List<int>();
            for (int i = 0; i < _temptwo.Count - 1; i++)
            {
                if (_temptwo[i] - 1 == _temptwo[i + 1])
                {
                    _minLinker.Add(_temptwo[i]);
                    if (i + 1 == _temptwo.Count - 1) _minLinker.Add(_temptwo[i + 1]);//最后一个要加上
                }
                else
                {//可能会出现刚才好3个,而后还有牌,搜索不到
                    _minLinker.Add(_temptwo[i]);
                    if (_minLinker.Count >= 3) _linkerPair.Add(_minLinker);
                    _minLinker = new List<int>();
                }
            }
            if (_minLinker.Count >= 3) _linkerPair.Add(_minLinker);
        }

19 Source : LandLord.cs
with Apache License 2.0
from 2881099

public void SearchPlaneWithone()
        {
            if (_shouPai.Count < 4) return;//不足4个牌就不处理的
            if (_three.Count < 2) return;//不足两个三带一
            List<int> _tempthree = new List<int>(_three);
            List<int> _minPlane = new List<int>();
            for (int i = 0; i < _tempthree.Count - 1; i++)
            {
                if (_tempthree[i] - 1 == _tempthree[i + 1])
                {
                    _minPlane.Add(_tempthree[i]);
                    if (i + 1 == _tempthree.Count - 1) _minPlane.Add(_tempthree[i + 1]);//最后一个要加上
                }
                else
                {//可能会出现刚才好2个,而后还有牌,搜索不到
                    _minPlane.Add(_tempthree[i]);
                    if (_minPlane.Count >= 2) _planeWith.Add(_minPlane);
                    _minPlane = new List<int>();
                }
            }
            if (_minPlane.Count >= 2) _planeWith.Add(_minPlane);
        }

19 Source : Geometry.cs
with GNU Lesser General Public License v3.0
from 9and3

public static List<List<IntPoint>> PolylineToIntPoints(List<Polyline> p, double scale = 1e10) {



            List<List<IntPoint>> polygons = new List<List<IntPoint>>();
            foreach (Polyline pp in p) {
                polygons.Add(PolylineToIntPoint(pp, scale));
            }

            return polygons;
        }

19 Source : Geometry.cs
with GNU Lesser General Public License v3.0
from 9and3

public static void Offset(IEnumerable<Polyline> polylines, List<OpenFilletType> openFilletType,
          List<ClosedFilletType> closedFilltetType, Plane plane, double tolerance, IEnumerable<double> distance,
          double miter, double arcTolerance, out List<List<Polyline>> outContour, out List<List<Polyline>> outHoles) {
            outContour = new List<List<Polyline>>();
            outHoles = new List<List<Polyline>>();
            /*
             * iEndType: How to handle open ended polygons.
             * Open				Closed
             * etOpenSquare		etClosedLine    (fill inside & outside)
             * etOpenRound			etClosedPolygon (fill outside only)
             * etOpenButt
             * 
             * See: http://www.angusj.com/delphi/clipper/doreplacedentation/Docs/Units/ClipperLib/Types/EndType.htm
             */

            /*
             * jtJoinType
             * How to fill angles of closed polygons
             * jtRound: Round
             * jtMiter: Square with variable distance
             * jtSquare: Square with fixed distance (jtMiter = 1)
             */

            ClipperOffset cOffset = new ClipperOffset(miter, arcTolerance);
            int i = 0;
            foreach (Polyline pl in polylines) {
                EndType et = EndType.etOpenButt;
                JoinType jt = JoinType.jtSquare;
                if (pl.IsClosed) {
                    et = EndType.etClosedLine;
                } else if (openFilletType.Count != 0) {
                    OpenFilletType oft = IndexOrLast(openFilletType, i);
                    switch (oft) {
                        case OpenFilletType.Butt:
                        et = EndType.etOpenButt;
                        break;
                        case OpenFilletType.Round:
                        et = EndType.etOpenRound;
                        break;
                        case OpenFilletType.Square:
                        et = EndType.etOpenSquare;
                        break;
                    }
                } else {
                    et = EndType.etOpenButt;
                }

                if (closedFilltetType.Count != 0) {
                    ClosedFilletType cft = IndexOrLast(closedFilltetType, i);
                    switch (cft) {
                        case ClosedFilletType.Miter:
                        jt = JoinType.jtMiter;
                        break;
                        case ClosedFilletType.Round:
                        jt = JoinType.jtRound;
                        break;
                        case ClosedFilletType.Square:
                        jt = JoinType.jtSquare;
                        break;
                    }
                } else {
                    jt = JoinType.jtSquare;
                }
                cOffset.AddPath(pl.ToPath2D(plane, tolerance), jt, et);
                i++;
            }

            foreach (double offsetDistance in distance) {
                PolyTree tree = new PolyTree();
                cOffset.Execute(ref tree, offsetDistance / tolerance);

                List<Polyline> holes = new List<Polyline>();
                List<Polyline> contours = new List<Polyline>();

                foreach (PolyNode path in tree.Iterate()) {
                    if (path.Contour.Count == 0) {
                        continue;
                    }
                    Polyline polyline = path.Contour.ToPolyline(plane, tolerance, !path.IsOpen);
                    if (path.IsHole) {
                        holes.Add(polyline);
                    } else {
                        contours.Add(polyline);
                    }
                }

                outContour.Add(contours);
                outHoles.Add(holes);
            }
        }

19 Source : TextFormattingConverterBase.cs
with MIT License
from ABTSoftware

public List<Tuple<int, int>> GetRanges(int[] array)
        {
            if (array.Length < 1)
                return null;

            var indexsesList = new List<List<int>>();

            var someList = new List<int>();
            for (int i = 0; i < array.Length - 1; i++)
            {
                someList.Add(array[i]);

                if (array[i + 1] - array[i] > 1)
                {
                    indexsesList.Add(someList);
                    someList = new List<int>();
                }
            }
            someList.Add(array[array.Length - 1]);
            indexsesList.Add(someList);

            return indexsesList.Select(list => new Tuple<int, int>(list[0], list.Count)).ToList();
        }

19 Source : JobServerQueue.cs
with MIT License
from actions

private async Task ProcessWebConsoleLinesQueueAsync(bool runOnce = false)
        {
            while (!_jobCompletionSource.Task.IsCompleted || runOnce)
            {
                if (_webConsoleLineAggressiveDequeue && ++_webConsoleLineAggressiveDequeueCount > _webConsoleLineAggressiveDequeueLimit)
                {
                    Trace.Info("Stop aggressive process web console line queue.");
                    _webConsoleLineAggressiveDequeue = false;
                }

                // Group consolelines by timeline record of each step
                Dictionary<Guid, List<TimelineRecordLogLine>> stepsConsoleLines = new Dictionary<Guid, List<TimelineRecordLogLine>>();
                List<Guid> stepRecordIds = new List<Guid>(); // We need to keep lines in order
                int linesCounter = 0;
                ConsoleLineInfo lineInfo;
                while (_webConsoleLineQueue.TryDequeue(out lineInfo))
                {
                    if (!stepsConsoleLines.ContainsKey(lineInfo.StepRecordId))
                    {
                        stepsConsoleLines[lineInfo.StepRecordId] = new List<TimelineRecordLogLine>();
                        stepRecordIds.Add(lineInfo.StepRecordId);
                    }

                    if (!string.IsNullOrEmpty(lineInfo.Line) && lineInfo.Line.Length > 1024)
                    {
                        Trace.Verbose("Web console line is more than 1024 chars, truncate to first 1024 chars");
                        lineInfo.Line = $"{lineInfo.Line.Substring(0, 1024)}...";
                    }

                    stepsConsoleLines[lineInfo.StepRecordId].Add(new TimelineRecordLogLine(lineInfo.Line, lineInfo.LineNumber));
                    linesCounter++;

                    // process at most about 500 lines of web console line during regular timer dequeue task.
                    if (!runOnce && linesCounter > 500)
                    {
                        break;
                    }
                }

                // Batch post consolelines for each step timeline record
                foreach (var stepRecordId in stepRecordIds)
                {
                    // Split consolelines into batch, each batch will container at most 100 lines.
                    int batchCounter = 0;
                    List<List<TimelineRecordLogLine>> batchedLines = new List<List<TimelineRecordLogLine>>();
                    foreach (var line in stepsConsoleLines[stepRecordId])
                    {
                        var currentBatch = batchedLines.ElementAtOrDefault(batchCounter);
                        if (currentBatch == null)
                        {
                            batchedLines.Add(new List<TimelineRecordLogLine>());
                            currentBatch = batchedLines.ElementAt(batchCounter);
                        }

                        currentBatch.Add(line);

                        if (currentBatch.Count >= 100)
                        {
                            batchCounter++;
                        }
                    }

                    if (batchedLines.Count > 0)
                    {
                        // When job finish, web console lines becomes less interesting to customer
                        // We batch and produce 500 lines of web console output every 500ms
                        // If customer's task produce mreplacedive of outputs, then the last queue drain run might take forever.
                        // So we will only upload the last 200 lines of each step from all buffered web console lines.
                        if (runOnce && batchedLines.Count > 2)
                        {
                            Trace.Info($"Skip {batchedLines.Count - 2} batches web console lines for last run");
                            batchedLines = batchedLines.TakeLast(2).ToList();
                        }

                        int errorCount = 0;
                        foreach (var batch in batchedLines)
                        {
                            try
                            {
                                // we will not requeue failed batch, since the web console lines are time sensitive.
                                if (batch[0].LineNumber.HasValue)
                                {
                                    await _jobServer.AppendTimelineRecordFeedAsync(_scopeIdentifier, _hubName, _planId, _jobTimelineId, _jobTimelineRecordId, stepRecordId, batch.Select(logLine => logLine.Line).ToList(), batch[0].LineNumber.Value, default(CancellationToken));
                                }
                                else
                                {
                                    await _jobServer.AppendTimelineRecordFeedAsync(_scopeIdentifier, _hubName, _planId, _jobTimelineId, _jobTimelineRecordId, stepRecordId, batch.Select(logLine => logLine.Line).ToList(), default(CancellationToken));
                                }

                                if (_firstConsoleOutputs)
                                {
                                    HostContext.WritePerfCounter($"WorkerJobServerQueueAppendFirstConsoleOutput_{_planId.ToString()}");
                                    _firstConsoleOutputs = false;
                                }
                            }
                            catch (Exception ex)
                            {
                                Trace.Info("Catch exception during append web console line, keep going since the process is best effort.");
                                Trace.Error(ex);
                                errorCount++;
                            }
                        }

                        Trace.Info("Try to append {0} batches web console lines for record '{2}', success rate: {1}/{0}.", batchedLines.Count, batchedLines.Count - errorCount, stepRecordId);
                    }
                }

                if (runOnce)
                {
                    break;
                }
                else
                {
                    await Task.Delay(_webConsoleLineAggressiveDequeue ? _aggressiveDelayForWebConsoleLineDequeue : _delayForWebConsoleLineDequeue);
                }
            }
        }

19 Source : Helpers.cs
with MIT License
from ad313

public static List<List<T>> SplitList<T>(List<T> list, int length)
        {
            if (list == null || list.Count <= 0 || length <= 0)
            {
                return new List<List<T>>();
            }

            var result = new List<List<T>>();
            var count = list.Count / length;
            count += list.Count % length > 0 ? 1 : 0;
            for (var i = 0; i < count; i++)
            {
                result.Add(list.Skip(i * length).Take(length).ToList());
            }
            return result;
        }

19 Source : MatrixSolve.cs
with GNU General Public License v3.0
from AdamWhiteHat

public static void GaussianSolve(CancellationToken cancelToken, GNFS gnfs)
		{
			Serialization.Save.Relations.Smooth.Append(gnfs); // Persist any relations not already persisted to disk

			// Because some operations clear this collection after persisting unsaved relations (to keep memory usage light)...
			// We completely reload the entire relations collection from disk.
			// This ensure that all the smooth relations are available for the matrix solving step.
			Serialization.Load.Relations.Smooth(ref gnfs);


			List<Relation> smoothRelations = gnfs.CurrentRelationsProgress.SmoothRelations.ToList();

			int smoothCount = smoothRelations.Count;

			BigInteger requiredRelationsCount = gnfs.CurrentRelationsProgress.SmoothRelationsRequiredForMatrixStep;

			gnfs.LogFunction($"Total relations count: {smoothCount}");
			gnfs.LogFunction($"Relations required to proceed: {requiredRelationsCount}");

			while (smoothRelations.Count >= requiredRelationsCount)
			{
				// Randomly select n relations from smoothRelations
				List<Relation> selectedRelations = new List<Relation>();
				while (
						selectedRelations.Count < requiredRelationsCount
						||
						selectedRelations.Count % 2 != 0 // Force number of relations to be even
					)
				{
					int randomIndex = StaticRandom.Next(0, smoothRelations.Count);
					selectedRelations.Add(smoothRelations[randomIndex]);
					smoothRelations.RemoveAt(randomIndex);
				}

				GaussianMatrix gaussianReduction = new GaussianMatrix(gnfs, selectedRelations);
				gaussianReduction.TransposeAppend();
				gaussianReduction.Elimination();

				int number = 1;
				int solutionCount = gaussianReduction.FreeVariables.Count(b => b) - 1;
				List<List<Relation>> solution = new List<List<Relation>>();
				while (number <= solutionCount)
				{
					List<Relation> relations = gaussianReduction.GetSolutionSet(number);
					number++;

					BigInteger algebraic = relations.Select(rel => rel.AlgebraicNorm).Product();
					BigInteger rational = relations.Select(rel => rel.RationalNorm).Product();

					CountDictionary algCountDict = new CountDictionary();
					foreach (var rel in relations)
					{
						algCountDict.Combine(rel.AlgebraicFactorization);
					}

					bool isAlgebraicSquare = algebraic.IsSquare();
					bool isRationalSquare = rational.IsSquare();

					gnfs.LogFunction("---");
					gnfs.LogFunction($"Relations count: {relations.Count}");
					gnfs.LogFunction($"(a,b) pairs: {string.Join(" ", relations.Select(rel => $"({rel.A},{rel.B})"))}");
					gnfs.LogFunction($"Rational  ∏(a+mb): IsSquare? {isRationalSquare} : {rational}");
					gnfs.LogFunction($"Algebraic ∏ƒ(a/b): IsSquare? {isAlgebraicSquare} : {algebraic}");
					gnfs.LogFunction($"Algebraic (factorization): {algCountDict.FormatStringAsFactorization()}");

					if (isAlgebraicSquare && isRationalSquare)
					{
						solution.Add(relations);
						gnfs.CurrentRelationsProgress.AddFreeRelationSolution(relations);
					}

					if (cancelToken.IsCancellationRequested)
					{
						break;
					}
				}

				if (cancelToken.IsCancellationRequested)
				{
					break;
				}
			}
		}

19 Source : ExcelReportBase.cs
with Mozilla Public License 2.0
from agebullhu

protected void ReadStyles(ISheet sheet, int sl, int el, int sc, int ec)
        {
            matrix.Clear();
            Styles.Clear();
            var l2 = new List<int>();
            matrix.Add(l2);
            for (var col = sc; col <= ec; col++)
            {
                l2.Add(sheet.GetColumnWidth(col));
            }
            l2 = new List<int>();
            matrix.Add(l2);

            for (var line = sl; line <= el; line++)
            {
                var row = sheet.GetRow(line) ?? sheet.CreateRow(line);
                l2.Add(row.Height);
                var lines = new List<ICellStyle>();
                for (var col = sc; col <= ec; col++)
                {
                    var cell = row.GetCell(col) ?? row.CreateCell(col);
                    lines.Add(cell.CellStyle);
                }
                Styles.Add(lines);
            }
        }

19 Source : CSVConvert.cs
with Mozilla Public License 2.0
from agebullhu

private static List<List<string>> Split(string values)
        {
            var result = new List<List<string>>();
            var line = new List<string>();
            var sb = new StringBuilder();
            var inQuotation = false; //在引号中
            var preQuotation = false; //前一个也是引号
            var preSeparator = true; //前面是做字段分隔符号吗
            bool isClose = false;
            foreach (var c in values)
            {
                if (c == '\"')
                {
                    if (inQuotation)
                    {
                        if (preQuotation) //连续引号当成正常的引号
                        {
                            sb.Append('\"');
                            preQuotation = false;
                        }
                        else //否则得看下一个,如果还是引号则认为正常引号,是引号当成引号来使用,其它情况不符合CVS的文件标准
                        {
                            preQuotation = true;
                        }
                    }
                    else if (preSeparator) //分隔符后的引号者才是字段内容起止
                    {
                        inQuotation = true;
                        preSeparator = false;
                    }
                    else
                    {
                        sb.Append(c);
                    }

                    continue;
                }

                if (preQuotation) //可中止
                {
                    preQuotation = false;
                    inQuotation = false;
                    isClose = true;
                    line.Add(sb.ToString());
                    sb.Clear();
                }
                else if (inQuotation) //所有都是普通内容
                {
                    sb.Append(c);
                    continue;
                }

                switch (c)
                {
                    case ',':
                        if (isClose)
                        {
                            isClose = false;
                        }
                        else
                        {
                            if (sb.Length == 0)
                            {
                                line.Add(null);
                            }
                            else
                            {
                                line.Add(sb.ToString());
                                sb.Clear();
                            }
                        }
                        preSeparator = true;
                        continue;
                    case '\r':
                    case '\n':
                        if (isClose)
                        {
                            isClose = false;
                        }
                        else
                        {
                            if (sb.Length == 0)
                            {
                                line.Add(null);
                            }
                            else
                            {
                                line.Add(sb.ToString());
                                sb.Clear();
                            }
                        }
                        if (line.Count > 0)
                        {
                            result.Add(line);
                            line = new List<string>();
                        }
                        preSeparator = true;
                        continue;
                    case ' ':
                    case '\t':
                        break;
                    default:
                        if (preSeparator)
                            preSeparator = false;
                        break;
                }

                sb.Append(c);
            }

            if (sb.Length != 0)
            {
                line.Add(sb.ToString());
                sb.Clear();
                result.Add(line);
            }
            else if (line.Count > 0)
            {
                line.Add(null);
                result.Add(line);
            }

            return result;
        }

19 Source : ExcelReportBase.cs
with Mozilla Public License 2.0
from agebullhu

protected void ReadStyles(ISheet sheet, int sl, int el, int sc, int ec)
        {
            Matrix.Clear();
            Styles.Clear();
            var l2 = new List<int>();
            Matrix.Add(l2);
            for (var col = sc; col <= ec; col++)
            {
                l2.Add(sheet.GetColumnWidth(col));
            }
            l2 = new List<int>();
            Matrix.Add(l2);

            for (var line = sl; line <= el; line++)
            {
                var row = sheet.GetRow(line) ?? sheet.CreateRow(line);
                l2.Add(row.Height);
                var lines = new List<ICellStyle>();
                for (var col = sc; col <= ec; col++)
                {
                    var cell = row.GetCell(col) ?? row.CreateCell(col);
                    lines.Add(cell.CellStyle);
                }
                Styles.Add(lines);
            }
        }

19 Source : CSVReader.cs
with Mozilla Public License 2.0
from agebullhu

private static List<List<string>> Split(string values)
        {
            var result = new List<List<string>>();
            List<string> line = null;
            var sb = new StringBuilder();
            var inQuotation = false; //在引号中
            var preQuotation = false; //前一个也是引号
            foreach (var c in values)
            {
                switch (c)
                {
                    case ',':
                        if (!inQuotation || preQuotation)
                        {
                            preQuotation = false;
                            inQuotation = false;
                            if (line == null)
                            {
                                line = new List<string>();
                                result.Add(line);
                            }
                            line.Add(sb.ToString());
                            sb.Clear();
                        }
                        else
                        {
                            sb.Append(',');
                        }
                        continue;
                    case '\"':
                        if (inQuotation)
                        {
                            if (preQuotation)
                            {
                                sb.Append('\"');
                                preQuotation = false; //连续引号当成正常的引号
                                continue;
                            }
                            //否则得看下一个,如果还是引号则认为正常引号,是引号当成引号来使用,其它情况不符合CVS的文件标准
                            preQuotation = true;
                            continue;
                        }
                        inQuotation = true;
                        continue;
                    case '\r':
                    case '\n':
                        if (!inQuotation || preQuotation)
                        {
                            if (line != null)
                            {
                                line.Add(sb.ToString());
                            }
                            sb.Clear();
                            line = null;
                            inQuotation = false;
                            preQuotation = false;
                        }
                        else
                        {
                            sb.Append(c);
                        }
                        continue;
                    default:
                        if (preQuotation)
                        {
                            sb.Append('\"');
                            preQuotation = false;
                            continue;
                        }
                        break;
                }
                sb.Append(c);
            }
            return result;
        }

19 Source : Serializer.cs
with MIT License
from agens-no

public PropertyCommentChecker NextLevel(string prop)
        {
            var newList = new List<List<string>>();
            foreach (var list in m_Props)
            {
                if (list.Count <= m_Level+1)
                    continue;
                if (list[m_Level] == "*" || list[m_Level] == prop)
                    newList.Add(list);
            }
            return new PropertyCommentChecker(m_Level + 1, newList);
        }

19 Source : HeroesResponsiveCollectionView.xaml.cs
with MIT License
from aimore

public static List<List<T>> SplitList2<T>(this List<T> me, int size = 50)
        {
            var list = new List<List<T>>();
            for (int i = 0; i < me.Count; i += size)
                list.Add(me.GetRange(i, Math.Min(size, me.Count - i)));
            return list;
        }

19 Source : DBEntryTheater.cs
with GNU General Public License v3.0
from akaAgar

protected override bool OnLoad(string iniFilePath)
        {
            int i;

            using (INIFile ini = new INIFile(iniFilePath))
            {
                // [Briefing] section
                BriefingNames = ini.GetValueArray<string>("Briefing", "Names");

                // [Theater] section
                DCSID = ini.GetValue<string>("Theater", "DCSID");
                DefaultMapCenter = ini.GetValue<Coordinates>("Theater", "DefaultMapCenter");
                MagneticDeclination = ini.GetValue<double>("Theater", "MagneticDeclination");

                // [Daytime] section
                DayTime = new MinMaxI[12];
                for (i = 0; i < 12; i++)
                {
                    MinMaxI? dayTimeValue = ParseMinMaxTime(ini.GetValueArray<string>("Daytime", ((Month)i).ToString()));

                    if (!dayTimeValue.HasValue) // Cast failed
                        BriefingRoom.PrintToLog(
                            $"Wrong format for daytime value for month {(Month)i} in theater {ID}, using default value",
                            LogMessageErrorLevel.Warning);

                    DayTime[i] = dayTimeValue ?? DEFAULT_DAYTIME;
                }



                RedCoordinates = new List<Coordinates>();
                foreach (string key in ini.GetKeysInSection("RedCoordinates"))
                    RedCoordinates.Add(ini.GetValue<Coordinates>("RedCoordinates", key));


                BlueCoordinates = new List<Coordinates>();
                foreach (string key in ini.GetKeysInSection("BlueCoordinates"))
                    BlueCoordinates.Add(ini.GetValue<Coordinates>("BlueCoordinates", key));


                // Water Coordinates
                WaterCoordinates = new List<Coordinates>();
                foreach (string key in ini.GetKeysInSection("WaterCoordinates"))
                    WaterCoordinates.Add(ini.GetValue<Coordinates>("WaterCoordinates", key));


                    List<DBEntryTheaterSpawnPoint> spawnPointsList = new List<DBEntryTheaterSpawnPoint>();
                foreach (string key in ini.GetKeysInSection("SpawnPoints"))
                {
                    DBEntryTheaterSpawnPoint sp = new DBEntryTheaterSpawnPoint();
                    if (sp.Load(ini, key))
                        spawnPointsList.Add(sp);
                }
                SpawnPoints = spawnPointsList.ToArray();

                WaterExclusionCoordinates = new List<List<Coordinates>>();
                if(ini.GetSections().Contains("waterexclusioncoordinates"))
                {
                    // Water Exclusion Coordinates
                    var tempList = new List<Coordinates>();
                    var groupID = ini.GetKeysInSection("WaterExclusionCoordinates").First().Split(".")[0];
                    foreach (string key in ini.GetKeysInSection("WaterExclusionCoordinates"))
                    {
                        var newGroupId = key.Split(".")[0];
                        if(groupID != newGroupId)
                        {
                            groupID = newGroupId;
                            WaterExclusionCoordinates.Add(tempList);
                            tempList = new List<Coordinates>();
                        }
                        tempList.Add(ini.GetValue<Coordinates>("WaterExclusionCoordinates", key));
                    }
                    WaterExclusionCoordinates.Add(tempList);
                }

                // [Temperature] section
                Temperature = new MinMaxI[12];
                for (i = 0; i < 12; i++)
                    Temperature[i] = ini.GetValue<MinMaxI>("Temperature", ((Month)i).ToString());
            }

            return true;
        }

19 Source : ConsumerSpec.cs
with Apache License 2.0
from akkadotnet

[Fact(DisplayName = "CommittableSource should emit messages received as chunked singles")]
        public async Task ShouldEmitSingles()
        {
            var splits = new List<List<CommittableMessage<string, string>>>();
            foreach (var message in Messages)
            {
                splits.Add(new List<CommittableMessage<string, string>>{message});
            }
            await CheckMessagesReceiving(splits);
        }

19 Source : ConsumerSpec.cs
with Apache License 2.0
from akkadotnet

public static List<List<T>> Grouped<T>(this IEnumerable<T> messages, int size)
        {
            var groups = new List<List<T>>();
            var list = new List<T>();
            var index = 0;
            foreach (var message in messages)
            {
                list.Add(message);
                if(index != 0 && index % size == 0)
                {
                    groups.Add(list);
                    list = new List<T>();
                }

                index++;
            }
            if(list.Count > 0)
                groups.Add(list);
            return groups;
        }

19 Source : NodeDataCache.cs
with MIT License
from aksyr

public void OnBeforeSerialize() {
                keys.Clear();
                values.Clear();
                foreach (var pair in this) {
                    keys.Add(pair.Key);
                    values.Add(pair.Value);
                }
            }

19 Source : MonotoneMountain.cs
with MIT License
from Alan-FGR

private void Triangulate()
        {
            while (_convexPoints.Count != 0)
            {
                IEnumerator<Point> e = _convexPoints.GetEnumerator();
                e.MoveNext();
                Point ear = e.Current;

                _convexPoints.Remove(ear);
                Point a = ear.Prev;
                Point b = ear;
                Point c = ear.Next;
                List<Point> triangle = new List<Point>(3);
                triangle.Add(a);
                triangle.Add(b);
                triangle.Add(c);

                Triangles.Add(triangle);

                // Remove ear, update angles and convex list
                Remove(ear);
                if (Valid(a))
                    _convexPoints.Add(a);
                if (Valid(c))
                    _convexPoints.Add(c);
            }

            Debug.replacedert(_size <= 3, "Triangulation bug, please report");
        }

19 Source : Triangulator.cs
with MIT License
from Alan-FGR

private void CreateMountains()
        {
            foreach (Edge edge in _edgeList)
            {
                if (edge.MPoints.Count > 2)
                {
                    MonotoneMountain mountain = new MonotoneMountain();

                    // Sorting is a perfromance hit. Literature says this can be accomplised in
                    // linear time, although I don't see a way around using traditional methods
                    // when using a randomized incremental algorithm

                    // Insertion sort is one of the fastest algorithms for sorting arrays containing 
                    // fewer than ten elements, or for lists that are already mostly sorted.

                    List<Point> points = new List<Point>(edge.MPoints);
                    points.Sort((p1, p2) => p1.X.CompareTo(p2.X));

                    foreach (Point p in points)
                        mountain.Add(p);

                    // Triangulate monotone mountain
                    mountain.Process();

                    // Extract the triangles into a single list
                    foreach (List<Point> t in mountain.Triangles)
                    {
                        Triangles.Add(t);
                    }

                    _xMonoPoly.Add(mountain);
                }
            }
        }

19 Source : GUIScaleUtility.cs
with MIT License
from alelievr

public static void BeginNoClip () 
		{
			// Record and close all clips one by one, from bottom to top, until we hit the 'origin'
			List<Rect> rectStackGroup = new List<Rect> ();
			Rect topMostClip = getTopRect;
			while (topMostClip != new Rect (-10000, -10000, 40000, 40000)) 
			{
				rectStackGroup.Add (topMostClip);
				GUI.EndClip ();
				topMostClip = getTopRect;
			}
			// Store the clips appropriately
			rectStackGroup.Reverse ();
			rectStackGroups.Add (rectStackGroup);
			currentRectStack.AddRange (rectStackGroup);
		}

19 Source : GUIScaleUtility.cs
with MIT License
from alelievr

public static void MoveClipsUp (int count) 
		{
			// Record and close all clips one by one, from bottom to top, until reached the count or hit the 'origin'
			List<Rect> rectStackGroup = new List<Rect> ();
			Rect topMostClip = getTopRect;
			while (topMostClip != new Rect (-10000, -10000, 40000, 40000) && count > 0)
			{
				rectStackGroup.Add (topMostClip);
				GUI.EndClip ();
				topMostClip = getTopRect;
				count--;
			}
			// Store the clips appropriately
			rectStackGroup.Reverse ();
			rectStackGroups.Add (rectStackGroup);
			currentRectStack.AddRange (rectStackGroup);
		}

19 Source : SortWay.cs
with MIT License
from alen-smajic

void SortList(List<List<Vector3>> WaysToBeSorted, int index)
    {
        if(WaysToBeSorted.Count <= 0)
        {
            return;
        }

        List<List<Vector3>> Lefreplacedems = WaysToBeSorted; 
        bool found_something = false;

        for(int i = 0; i < WaysToBeSorted.Count; i++)
        {
            if(WaysToBeSorted[i][0] == SortedPathAndWays[index][SortedPathAndWays[index].Count - 1][SortedPathAndWays[index][SortedPathAndWays[index].Count - 1].Count - 1])
            {
                SortedPathAndWays[index].Add(WaysToBeSorted[i]);
                Lefreplacedems.RemoveAt(i);
                found_something = true;
            }
            else if (SortedPathAndWays[index][0][0] == WaysToBeSorted[i][WaysToBeSorted[i].Count - 1])
            {
               SortedPathAndWays[index].Insert(0, WaysToBeSorted[i]);
                Lefreplacedems.RemoveAt(i);
                found_something = true;
            }
            else if(WaysToBeSorted[i][0] == SortedPathAndWays[index][0][0])
            {
                WaysToBeSorted[i].Reverse();
                SortedPathAndWays[index].Insert(0, WaysToBeSorted[i]);
                Lefreplacedems.RemoveAt(i);
                found_something = true;
            }
            else if (WaysToBeSorted[i][WaysToBeSorted[i].Count - 1] == SortedPathAndWays[index][SortedPathAndWays[index].Count - 1][SortedPathAndWays[index][SortedPathAndWays[index].Count - 1].Count - 1])
            {
                WaysToBeSorted[i].Reverse();
                SortedPathAndWays[index].Add(WaysToBeSorted[i]);
                Lefreplacedems.RemoveAt(i);
                found_something = true;
            }
            else
            {
                continue;
            }
        }

        if(found_something == false)
        {
            List<List<Vector3>> localList = new List<List<Vector3>>();
            localList.Add(WaysToBeSorted[0]);
            SortedPathAndWays.Add(localList);
            Lefreplacedems.RemoveAt(0);
            SortList(Lefreplacedems, index + 1);
        }
        else
        {
            SortList(Lefreplacedems, index);
        }
    }

19 Source : PolygonMeshModifier.cs
with MIT License
from alen-smajic

public override void Run(VectorFeatureUnity feature, MeshData md, UnityTile tile = null)
		{
			if (Criteria != null && Criteria.Count > 0)
			{
				foreach (var criterion in Criteria)
				{
					if (criterion.ShouldReplaceFeature(feature))
					{
						return;
					}
				}
			}

			var _counter = feature.Points.Count;
			var subset = new List<List<Vector3>>(_counter);
			Data flatData = null;
			List<int> result = null;
			var currentIndex = 0;
			int vertCount = 0, polygonVertexCount = 0;
			List<int> triList = null;
			List<Vector3> sub = null;



			for (int i = 0; i < _counter; i++)
			{
				sub = feature.Points[i];
				//earcut is built to handle one polygon with multiple holes
				//point data can contain multiple polygons though, so we're handling them separately here

				vertCount = md.Vertices.Count;
				if (IsClockwise(sub) && vertCount > 0)
				{
					flatData = EarcutLibrary.Flatten(subset);
					result = EarcutLibrary.Earcut(flatData.Vertices, flatData.Holes, flatData.Dim);
					polygonVertexCount = result.Count;
					if (triList == null)
					{
						triList = new List<int>(polygonVertexCount);
					}
					else
					{
						triList.Capacity = triList.Count + polygonVertexCount;
					}

					for (int j = 0; j < polygonVertexCount; j++)
					{
						triList.Add(result[j] + currentIndex);
					}

					currentIndex = vertCount;
					subset.Clear();
				}

				subset.Add(sub);

				polygonVertexCount = sub.Count;
				md.Vertices.Capacity = md.Vertices.Count + polygonVertexCount;
				md.Normals.Capacity = md.Normals.Count + polygonVertexCount;
				md.Edges.Capacity = md.Edges.Count + polygonVertexCount * 2;
				var _size = md.TileRect.Size;

				for (int j = 0; j < polygonVertexCount; j++)
				{
					md.Edges.Add(vertCount + ((j + 1) % polygonVertexCount));
					md.Edges.Add(vertCount + j);
					md.Vertices.Add(sub[j]);
					md.Tangents.Add(Constants.Math.Vector3Forward);
					md.Normals.Add(Constants.Math.Vector3Up);

					if (_options.style == StyleTypes.Satellite)
					{
						var fromBottomLeft = new Vector2(
							(float) (((sub[j].x + md.PositionInTile.x) / tile.TileScale + _size.x / 2) / _size.x),
							(float) (((sub[j].z + md.PositionInTile.z) / tile.TileScale + _size.x / 2) / _size.x));
						md.UV[0].Add(fromBottomLeft);
					}
					else if (_options.texturingType == UvMapType.Tiled)
					{
						md.UV[0].Add(new Vector2(sub[j].x, sub[j].z));
					}
				}
			}

			flatData = EarcutLibrary.Flatten(subset);
			result = EarcutLibrary.Earcut(flatData.Vertices, flatData.Holes, flatData.Dim);
			polygonVertexCount = result.Count;

			if (_options.texturingType == UvMapType.Atlas || _options.texturingType == UvMapType.AtlasWithColorPalette)
			{
				_currentFacade = _options.atlasInfo.Roofs[UnityEngine.Random.Range(0, _options.atlasInfo.Roofs.Count)];

				minx = float.MaxValue;
				miny = float.MaxValue;
				maxx = float.MinValue;
				maxy = float.MinValue;

				_textureUvCoordinates = new Vector2[md.Vertices.Count];
				_textureDirection = Quaternion.FromToRotation((md.Vertices[0] - md.Vertices[1]), Mapbox.Unity.Constants.Math.Vector3Right);
				_textureUvCoordinates[0] = new Vector2(0, 0);
				_firstVert = md.Vertices[0];
				for (int i = 1; i < md.Vertices.Count; i++)
				{
					_vert = md.Vertices[i];
					_vertexRelativePos = _vert - _firstVert;
					_vertexRelativePos = _textureDirection * _vertexRelativePos;
					_textureUvCoordinates[i] = new Vector2(_vertexRelativePos.x, _vertexRelativePos.z);
					if (_vertexRelativePos.x < minx)
						minx = _vertexRelativePos.x;
					if (_vertexRelativePos.x > maxx)
						maxx = _vertexRelativePos.x;
					if (_vertexRelativePos.z < miny)
						miny = _vertexRelativePos.z;
					if (_vertexRelativePos.z > maxy)
						maxy = _vertexRelativePos.z;
				}

				var width = maxx - minx;
				var height = maxy - miny;

				for (int i = 0; i < md.Vertices.Count; i++)
				{
					md.UV[0].Add(new Vector2(
						(((_textureUvCoordinates[i].x - minx) / width) * _currentFacade.TextureRect.width) + _currentFacade.TextureRect.x,
						(((_textureUvCoordinates[i].y - miny) / height) * _currentFacade.TextureRect.height) + _currentFacade.TextureRect.y));
				}
			}

			if (triList == null)
			{
				triList = new List<int>(polygonVertexCount);
			}
			else
			{
				triList.Capacity = triList.Count + polygonVertexCount;
			}

			for (int i = 0; i < polygonVertexCount; i++)
			{
				triList.Add(result[i] + currentIndex);
			}

			md.Triangles.Add(triList);
		}

19 Source : ReplaceFeatureModifier.cs
with MIT License
from alen-smajic

public override void Initialize()
		{
			base.Initialize();
			//duplicate the list of lat/lons to track which coordinates have already been spawned

			_featureId = new List<List<string>>();

			for (int i = 0; i < _prefabLocations.Count; i++)
			{
				_featureId.Add(new List<string>());
			}
			if (_objects == null)
			{
				_objects = new Dictionary<ulong, GameObject>();
				_objectPosition = new Dictionary<ulong, Vector2d>();
				if(_poolGameObject == null)
				{
					_poolGameObject = new GameObject("_inactive_prefabs_pool");
				}
				if(_abstractMap == null)
				{
					_abstractMap = FindObjectOfType<AbstractMap>();
				}
				if(_abstractMap != null)
				{
					_poolGameObject.transform.SetParent(_abstractMap.transform, true);
				}
			}
			_latLonToSpawn = new List<Vector2d>();
			foreach (var loc in _prefabLocations)
			{
				_latLonToSpawn.Add(Conversions.StringToLatLon(loc));
			}
		}

19 Source : SortWay.cs
with MIT License
from alen-smajic

private void Start()
    {
        allWayCoordinates = new List<List<Vector3>>();
        SortedPathAndWays = new List<List<List<Vector3>>>();
        SplittedinPaths = new List<List<Vector3>>();
        PathsInRightOrder = new List<List<Vector3>>();

        MoveToTarget = new List<Vector3>();
        PathLastNode = new List<Vector3>();

        List<GameObject> allObjects = new List<GameObject>();
        Scene scene = SceneManager.GetActiveScene();
        scene.GetRootGameObjects(allObjects);

        // This for loop returns a list "allWayCoordinates" which contains more lists. Every list of these are way objects
        // which contain the node coordinates
        for (int i = 0; i < TranSportWayMarker.SelectedWays.Count; i++)
        {
            string ObjectName = allObjects[TranSportWayMarker.SelectedWays[i]].name;
            string ObjectID = ObjectName.Substring(15); // The ID of the way is being determined in order to search for it in the MapReader clreplaced.

            List<Vector3> WayNodes = new List<Vector3>();
            for (int j = 0; j < MapReader.ways[Convert.ToUInt64(ObjectID)].UnityCoordinates.Count; j++)
            {
                WayNodes.Add(MapReader.ways[Convert.ToUInt64(ObjectID)].UnityCoordinates[j]);
            }
            allWayCoordinates.Add(WayNodes); 
            // allWayCoordinates contains lists which represent the way objects. Every single one of these lists contains the node coordinates as values.
        }

        // Next we create a new list (SortedPathAndWays). This list merges the ways that belong to a common path.
        // E.g. if a bus line ends on one edge of the map and continues at another edge of the map, the corresponding ways will be stored in different lists.
        List<List<Vector3>> localList = new List<List<Vector3>>();
        localList.Add(allWayCoordinates[0]);
        SortedPathAndWays.Add(localList);
        allWayCoordinates.RemoveAt(0);

        // Is being called to sort the SortedPathAndWays with  respect to allWayCoordinates.
        SortList(allWayCoordinates, 0);

        // Here we transform the three-dimensional SortedPathAndWays list into a two-dimensional list. We do this by concatenating the inner lists
        // because these are already sorted.
        List<Vector3> temporaryList = new List<Vector3>();
        for(int i = 0; i < SortedPathAndWays.Count; i++) 
        {
            temporaryList = SortedPathAndWays[i].SelectMany(x => x).ToList();
            SplittedinPaths.Add(temporaryList);
        }

        for(int i = 0; i < TranSportWayMarker.StationOrder.Count; i++)
        {
            for(int j = 0; j < SplittedinPaths.Count; j++)
            {
                for(int k = 0; k < SplittedinPaths[j].Count; k++)
                {
                    if(TranSportWayMarker.StationOrder[i] == SplittedinPaths[j][k])
                    {
                        if (PathsInRightOrder.Contains(SplittedinPaths[j]))
                        {
                            break;
                        }
                        else
                        {
                            PathsInRightOrder.Add(SplittedinPaths[j]);
                        }
                    }
                }
            }
        }

        // Append paths which dont contain any station at the end.
        for(int i = 0; i < SplittedinPaths.Count; i++)
        {
            if (!PathsInRightOrder.Contains(SplittedinPaths[i]))
            {
                PathsInRightOrder.Add(SplittedinPaths[i]);
            }
        }

        // Switch the direction of the values within the paths using the stations.
        int firstIndex = -1;
        int secondIndex = -1;
        for(int i = 0; i < TranSportWayMarker.StationOrder.Count; i++)
        {
            for(int k = 0; k < PathsInRightOrder.Count; k++)
            {
                for(int j = 0; j < PathsInRightOrder[k].Count; j++)
                {
                    if(TranSportWayMarker.StationOrder[i] == PathsInRightOrder[k][j])
                    {
                        if(firstIndex == -1)
                        {
                            firstIndex = j;
                            break;
                        }
                        else
                        {
                            secondIndex = j;
                            break;
                        }
                    }
                }
                if(firstIndex != -1 && secondIndex != -1)
                {
                    if(firstIndex > secondIndex)
                    {
                        PathsInRightOrder[k].Reverse();
                        break;
                    }
                }
            }
        }

        for(int i = 0; i < PathsInRightOrder.Count; i++)
        {
            for(int j = 0; j < SortWay.PathsInRightOrder[i].Count; j++)
            {
                MoveToTarget.Add(SortWay.PathsInRightOrder[i][j]);
            }
        }

        if(SortWay.PathsInRightOrder.Count > 1)
        {
            for(int i = 0; i < PathsInRightOrder.Count; i++)
            {
                PathLastNode.Add(PathsInRightOrder[i][PathsInRightOrder[i].Count - 1]);
            }
        }

        IdentifyVehicle();
    }

19 Source : TemplateOptionsData.cs
with MIT License
from alexismorin

public static TemplateOptionsContainer GenerateOptionsContainer( bool isSubShader, string data )
		{
			TemplateOptionsContainer optionsContainer = new TemplateOptionsContainer();

			Match match = Regex.Match( data, isSubShader ? SubShaderOptionsMainPattern : PreplacedOptionsMainPattern );
			optionsContainer.Enabled = match.Success;
			if( match.Success )
			{
				try
				{
					optionsContainer.Body = match.Value;
					optionsContainer.Index = match.Index;

					List<TemplateOptionsItem> optionItemsList = new List<TemplateOptionsItem>();
					List<List<TemplateActionItem>> actionItemsList = new List<List<TemplateActionItem>>();
					Dictionary<string, int> optionItemToIndex = new Dictionary<string, int>();
					TemplateOptionsItem currentOption = null;

					//OPTIONS OVERALL SETUP
					string[] setupLines = match.Groups[ 1 ].Value.Split( ':' );
					for( int i = 0; i < setupLines.Length; i++ )
					{
						if( AseOptionsSetupDict.ContainsKey( setupLines[ i ] ) )
						{
							AseOptionsSetup setup = AseOptionsSetupDict[ setupLines[ i ] ];
							switch( setup )
							{
								case AseOptionsSetup.CopyOptionsFromMainPreplaced: optionsContainer.CopyOptionsFromMainPreplaced = true; break;
							}
						}
						else
						{
							string[] args = setupLines[ i ].Split( '=' );
							if( args.Length > 1 && AseOptionsSetupDict.ContainsKey( args[ 0 ] ) )
							{
								AseOptionsSetup setup = AseOptionsSetupDict[ args[ 0 ] ];
								switch( setup )
								{
									case AseOptionsSetup.Id: if( !int.TryParse( args[ 1 ], out optionsContainer.Id ) ) optionsContainer.Id = -1; break;
									case AseOptionsSetup.Name: optionsContainer.Name = args[ 1 ]; break;
								}
							}
						}
					}

					//AVAILABLE OPTIONS
					string body = match.Groups[ 2 ].Value.Replace( "\t", string.Empty );
					string[] optionLines = body.Split( '\n' );
					for( int oL = 0; oL < optionLines.Length; oL++ )
					{
						string[] optionItems = optionLines[ oL ].Split( ':' );
						if( optionItems.Length > 0 )
						{
							string[] itemIds = optionItems[ 0 ].Split( OptionsDataSeparator );
							switch( itemIds[ 0 ] )
							{
								case "Option":
								{
									//Fills previous option with its actions
									//actionItemsList is cleared over here
									FillOptionAction( currentOption, ref actionItemsList );

									optionItemToIndex.Clear();
									currentOption = new TemplateOptionsItem();
									currentOption.Type = AseOptionsType.Option;
									string[] optionItemSetup = optionItems[ 1 ].Split( OptionsDataSeparator );
									currentOption.Name = optionItemSetup[ 0 ];
									if( optionItemSetup.Length > 1 )
									{
										if( AseOptionItemSetupDict.ContainsKey( optionItemSetup[ 1 ] ) )
											currentOption.Setup = AseOptionItemSetupDict[ optionItemSetup[ 1 ] ];
									}

									currentOption.Id = itemIds.Length > 1 ? itemIds[ 1 ] : optionItems[ 1 ];
									currentOption.Options = optionItems[ 2 ].Split( OptionsDataSeparator );
									currentOption.Count = currentOption.Options.Length;

									for( int opIdx = 0; opIdx < currentOption.Options.Length; opIdx++ )
									{
										optionItemToIndex.Add( currentOption.Options[ opIdx ], opIdx );
										actionItemsList.Add( new List<TemplateActionItem>() );
									}

									if( optionItems.Length > 3 )
									{
										currentOption.DefaultOption = optionItems[ 3 ];
									}
									else
									{
										currentOption.DefaultOption = currentOption.Options[ 0 ];
									}

									if( currentOption.Options.Length > 2 )
									{
										currentOption.UIWidget = AseOptionsUIWidget.Dropdown;
									}
									else if( currentOption.Options.Length == 2 )
									{
										if( ( currentOption.Options[ 0 ].Equals( "true" ) && currentOption.Options[ 1 ].Equals( "false" ) ) ||
											( currentOption.Options[ 0 ].Equals( "false" ) && currentOption.Options[ 1 ].Equals( "true" ) ) )
										{
											// Toggle 0 is false and 1 is true
											currentOption.Options[ 0 ] = "false";
											currentOption.Options[ 1 ] = "true";
											currentOption.UIWidget = AseOptionsUIWidget.Toggle;
										}
									}
									else
									{
										Debug.LogWarning( "Detected an option with less than two items:" + optionItems[ 1 ] );
									}
									optionItemsList.Add( currentOption );
								}
								break;
								case "Port":
								{
									//Fills previous option with its actions
									//actionItemsList is cleared over here
									FillOptionAction( currentOption, ref actionItemsList );

									optionItemToIndex.Clear();

									currentOption = new TemplateOptionsItem();
									currentOption.Type = AseOptionsType.Port;
									if( isSubShader && optionItems.Length > 2 )
									{
										currentOption.Id = optionItems[ 1 ];
										currentOption.Name = optionItems[ 2 ];
									}
									else
									{
										currentOption.Name = optionItems[ 1 ];
									}

									currentOption.Options = new string[] { "On", "Off" };
									optionItemToIndex.Add( currentOption.Options[ 0 ], 0 );
									optionItemToIndex.Add( currentOption.Options[ 1 ], 1 );

									actionItemsList.Add( new List<TemplateActionItem>() );
									actionItemsList.Add( new List<TemplateActionItem>() );

									optionItemsList.Add( currentOption );
								}
								break;
								default:
								{
									if( optionItemToIndex.ContainsKey( optionItems[ 0 ] ) )
									{
										int idx = 0;
										if( currentOption != null && currentOption.UIWidget == AseOptionsUIWidget.Toggle )
										{
											idx = ( optionItems[ 0 ].Equals( "true" ) ) ? 1 : 0;
										}
										else
										{
											idx = optionItemToIndex[ optionItems[ 0 ] ];
										}
										actionItemsList[ idx ].Add( CreateActionItem( isSubShader, optionItems ) );
									}
									else
									{
										//string[] ids = optionItems[ 0 ].Split( ',' );
										if( itemIds.Length > 1 )
										{
											for( int i = 0; i < itemIds.Length; i++ )
											{
												if( optionItemToIndex.ContainsKey( itemIds[ i ] ) )
												{
													int idx = optionItemToIndex[ itemIds[ i ] ];
													actionItemsList[ idx ].Add( CreateActionItem( isSubShader, optionItems ) );
												}
											}
										}
									}

								}
								break;
							}
						}
					}

					//Fills last option with its actions
					FillOptionAction( currentOption, ref actionItemsList );

					actionItemsList.Clear();
					actionItemsList = null;

					optionsContainer.Options = optionItemsList.ToArray();
					optionItemsList.Clear();
					optionItemsList = null;

					optionItemToIndex.Clear();
					optionItemToIndex = null;
				}
				catch( Exception e )
				{
					Debug.LogException( e );
				}
			}
			return optionsContainer;
		}

19 Source : ASETextureArrayCreator.cs
with MIT License
from alexismorin

private void BuildTexture3D()
		{
			int sizeX = m_sizes[ m_selectedSizeX ];
			int sizeY = m_sizes[ m_selectedSizeY ];
			int mipCount = m_mipMaps ? MipCount[ Mathf.Max( sizeX, sizeY ) ] : 1;

			Texture3D texture3D = new Texture3D( sizeX, sizeY, m_allTextures.Count, m_selectedFormatEnum, m_mipMaps );
			texture3D.wrapMode = m_wrapMode;
			texture3D.filterMode = m_filterMode;
			texture3D.anisoLevel = m_anisoLevel;
			texture3D.Apply( false );
			RenderTexture cache = RenderTexture.active;
			RenderTexture rt = new RenderTexture( sizeX, sizeY, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default );
			rt.Create();
			List<List<Color>> mipColor = new List<List<Color>>();
			if( m_mipMaps )
			{
				for( int i = 0; i < mipCount; i++ )
				{
					mipColor.Add( new List<Color>() );
				}
			}
			else
			{
				mipColor.Add( new List<Color>() );
			}

			for( int i = 0; i < m_allTextures.Count; i++ )
			{
				// build report
				int widthChanges = m_allTextures[ i ].width < sizeX ? -1 : m_allTextures[ i ].width > sizeX ? 1 : 0;
				int heightChanges = m_allTextures[ i ].height < sizeY ? -1 : m_allTextures[ i ].height > sizeY ? 1 : 0;
				if( ( widthChanges < 0 && heightChanges <= 0 ) || ( widthChanges <= 0 && heightChanges < 0 ) )
					m_message += m_allTextures[ i ].name + " was upscaled\n";
				else if( ( widthChanges > 0 && heightChanges >= 0 ) || ( widthChanges >= 0 && heightChanges > 0 ) )
					m_message += m_allTextures[ i ].name + " was downscaled\n";
				else if( ( widthChanges > 0 && heightChanges < 0 ) || ( widthChanges < 0 && heightChanges > 0 ) )
					m_message += m_allTextures[ i ].name + " changed dimensions\n";

				// blit image to upscale or downscale the image to any size
				RenderTexture.active = rt;

				bool cachedsrgb = GL.sRGBWrite;
				GL.sRGBWrite = !m_linearMode;
				Graphics.Blit( m_allTextures[ i ], rt );
				GL.sRGBWrite = cachedsrgb;

				Texture2D t2d = new Texture2D( sizeX, sizeY, TextureFormat.ARGB32, m_mipMaps, m_linearMode );
				t2d.ReadPixels( new Rect( 0, 0, sizeX, sizeY ), 0, 0, m_mipMaps );
				RenderTexture.active = null;

				bool isCompressed = UncompressedFormats.FindIndex( x => x.Equals( m_selectedFormatEnum ) ) < 0;
				if( isCompressed )
				{
					EditorUtility.CompressTexture( t2d, m_selectedFormatEnum, m_quality );
					//	t2d.Apply( false );
				}
				t2d.Apply( false );

				if( m_mipMaps )
				{
					for( int mip = 0; mip < mipCount; mip++ )
					{
						mipColor[ mip ].AddRange( t2d.GetPixels( mip ) );
					}
				}
				else
				{
					mipColor[ 0 ].AddRange( t2d.GetPixels( 0 ) );
				}
			}

			rt.Release();
			RenderTexture.active = cache;

			if( m_message.Length > 0 )
				m_message = m_message.Substring( 0, m_message.Length - 1 );

			for( int i = 0; i < mipCount; i++ )
			{
				texture3D.SetPixels( mipColor[ i ].ToArray(), i );
			}

			texture3D.Apply( false );

			string path = m_folderPath + m_fileName + ".replacedet";
			Texture3D outfile = replacedetDatabase.LoadMainreplacedetAtPath( path ) as Texture3D;
			if( outfile != null )
			{
				EditorUtility.CopySerialized( texture3D, outfile );
				replacedetDatabase.Savereplacedets();
				EditorGUIUtility.PingObject( outfile );
				m_lastSaved = outfile;
			}
			else
			{
				replacedetDatabase.Createreplacedet( texture3D, path );
				EditorGUIUtility.PingObject( texture3D );
				m_lastSaved = texture3D;
			}
		}

19 Source : ASETextureArrayCreator.cs
with GNU General Public License v3.0
from alexismorin

private void BuildTexture3D()
		{
			int sizeX = m_sizes[ m_selectedSizeX ];
			int sizeY = m_sizes[ m_selectedSizeY ];
			int mipCount = m_mipMaps ? MipCount[ Mathf.Max( sizeX, sizeY ) ] : 1;

			Texture3D texture3D = new Texture3D( sizeX, sizeY, m_allTextures.Count, m_selectedFormatEnum, m_mipMaps );
			texture3D.wrapMode = m_wrapMode;
			texture3D.filterMode = m_filterMode;
			texture3D.anisoLevel = m_anisoLevel;
			texture3D.Apply( false );
			RenderTexture cache = RenderTexture.active;
			RenderTexture rt = new RenderTexture( sizeX, sizeY, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default );
			rt.Create();
			List<List<Color>> mipColor = new List<List<Color>>();
			if( m_mipMaps )
			{
				for( int i = 0; i < mipCount; i++ )
				{
					mipColor.Add( new List<Color>() );
				}
			}
			else
			{
				mipColor.Add( new List<Color>() );
			}

			for( int i = 0; i < m_allTextures.Count; i++ )
			{
				// build report
				int widthChanges = m_allTextures[ i ].width < sizeX ? -1 : m_allTextures[ i ].width > sizeX ? 1 : 0;
				int heightChanges = m_allTextures[ i ].height < sizeY ? -1 : m_allTextures[ i ].height > sizeY ? 1 : 0;
				if( ( widthChanges < 0 && heightChanges <= 0 ) || ( widthChanges <= 0 && heightChanges < 0 ) )
					m_message += m_allTextures[ i ].name + " was upscaled\n";
				else if( ( widthChanges > 0 && heightChanges >= 0 ) || ( widthChanges >= 0 && heightChanges > 0 ) )
					m_message += m_allTextures[ i ].name + " was downscaled\n";
				else if( ( widthChanges > 0 && heightChanges < 0 ) || ( widthChanges < 0 && heightChanges > 0 ) )
					m_message += m_allTextures[ i ].name + " changed dimensions\n";

				// blit image to upscale or downscale the image to any size
				RenderTexture.active = rt;

				bool cachedsrgb = GL.sRGBWrite;
				GL.sRGBWrite = !m_linearMode;
				Graphics.Blit( m_allTextures[ i ], rt );
				GL.sRGBWrite = cachedsrgb;

				Texture2D t2d = new Texture2D( sizeX, sizeY, TextureFormat.ARGB32, m_mipMaps, m_linearMode );
				t2d.ReadPixels( new Rect( 0, 0, sizeX, sizeY ), 0, 0, m_mipMaps );
				RenderTexture.active = null;

				bool isCompressed = UncompressedFormats.FindIndex( x => x.Equals( m_selectedFormatEnum ) ) < 0;
				if( isCompressed )
				{
					EditorUtility.CompressTexture( t2d, m_selectedFormatEnum, m_quality );
					t2d.Apply( false );
				}

				if( m_mipMaps )
				{
					for( int mip = 0; mip < mipCount; mip++ )
					{
						mipColor[ mip ].AddRange( t2d.GetPixels( mip) );
					}
				}
				else
				{
					mipColor[ 0 ].AddRange( t2d.GetPixels( 0 ) );
				}
			}
			
			rt.Release();
			RenderTexture.active = cache;
			if( m_message.Length > 0 )
				m_message = m_message.Substring( 0, m_message.Length - 1 );

			for( int i = 0; i < mipCount; i++ )
			{
				texture3D.SetPixels( mipColor[ i ].ToArray(), i );
			}

			texture3D.Apply();

			string path = m_folderPath + m_fileName + ".replacedet";
			Texture3D outfile = replacedetDatabase.LoadMainreplacedetAtPath( path ) as Texture3D;
			if( outfile != null )
			{
				EditorUtility.CopySerialized( texture3D, outfile );
				replacedetDatabase.Savereplacedets();
				EditorGUIUtility.PingObject( outfile );
				m_lastSaved = outfile;
			}
			else
			{
				replacedetDatabase.Createreplacedet( texture3D, path );
				EditorGUIUtility.PingObject( texture3D );
				m_lastSaved = texture3D;
			}
		}

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

private void ResetValues()
        {
            _timeStart = new DateTime(DatePickerStart.Year, DatePickerStart.Month, DatePickerStart.Day,
                                      TimePickerStart.Hour, 0, 0);
            _timeEnd = ToEndTicks ? DateTime.MaxValue : new DateTime(DatePickerEnd.Year, DatePickerEnd.Month, DatePickerEnd.Day,
                                                                TimePickerEnd.Hour, 0, 0);


            _allTicksVolume = 0;
            _lastVwapValue = 0;
            _currentVwapValue = 0;

            _moveX = 0;
            _valCount = 0;
            _lastMedian = 0;
            _lastPow = 0;

            _allTicksVolumeD = 0;
            _lastVwapValueD = 0;
            _currentVwapValueD = 0;
            _needZeroD = false;
            _lastDayD = 0;

            _moveXd = 0;
            _valCountD = 0;
            _lastMedianD = 0;
            _lastPowD = 0;

            _allTicksVolumeW = 0;
            _lastVwapValueW = 0;
            _currentVwapValueW = 0;
            _needZeroW = true;
            _started = false;
            _lastDayW = 0;

            _moveXw = 0;
            _valCountW = 0;
            _lastMedianW = 0;
            _lastPowW = 0;

            VwapDate = new List<decimal>();
            VwapDay = new List<decimal>();
            VwapWeekly = new List<decimal>();

            DateDeviationsValues = new List<List<decimal>>();
            DayDeviationsValues = new List<List<decimal>>();
            WeeklyDeviationsValues = new List<List<decimal>>();

            for (int i = 0; i < 6; i++)
            {
                DateDeviationsValues.Add(new List<decimal>());
                DayDeviationsValues.Add(new List<decimal>());
                WeeklyDeviationsValues.Add(new List<decimal>());
            }
        }

19 Source : StrategyParemetrsUi.xaml.cs
with Apache License 2.0
from AlexWan

List<List<IIStrategyParameter>> GetParamSortedByTabName()
        {
            List<List<IIStrategyParameter>> sorted = new List<List<IIStrategyParameter>>();

            for(int i = 0;i < _parameters.Count;i++)
            {
                List<IIStrategyParameter> myList = sorted.Find(s => s[0].TabName == _parameters[i].TabName);

                if(myList != null)
                {
                    myList.Add(_parameters[i]);
                }
                else
                {
                    List<IIStrategyParameter> newItem = new List<IIStrategyParameter>();
                    newItem.Add(_parameters[i]);
                    sorted.Add(newItem);
                }
            }

            for(int i = 0;i < sorted.Count;i++)
            {// переставляем принудительно параметры без имени вкладки в первый слот вкладок
                if(sorted[i][0].TabName == null && i != 0)
                {
                    List<IIStrategyParameter> par = sorted[i];
                    sorted.RemoveAt(i);
                    sorted.Insert(0, par);
                    break;
                }
            }

            return sorted;
        }

19 Source : Extensions.cs
with MIT License
from AlFasGD

public static List<List<T>> ToList<T>(this T[,] ar)
        {
            var l = new List<List<T>>();
            for (int i = 0; i < ar.GetLength(0); i++)
            {
                var temp = new List<T>();
                for (int j = 0; j < ar.GetLength(1); j++)
                    temp.Add(ar[i, j]);
                l.Add(temp);
            }
            return l;
        }

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 : BasicLineChartNodeModel.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.");
            }

            // Clear current chart values
            Labels = new List<string>();
            Values = new List<List<double>>();
            Colors = new List<SolidColorBrush>();

            // If color count doesn't match replacedle count use random colors
            if (colors.Count != labels.Count)
            {
                for (var i = 0; i < labels.Count; i++)
                {
                    var outputValues = new List<double>();

                    foreach (var plotVal in values[i] as ArrayList)
                    {
                        outputValues.Add(System.Convert.ToDouble(plotVal));
                    }

                    Labels.Add((string)labels[i]);
                    Values.Add(outputValues);

                    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++)
                {
                    var outputValues = new List<double>();

                    foreach (var plotVal in values[i] as ArrayList)
                    {
                        outputValues.Add(System.Convert.ToDouble(plotVal));
                    }

                    Labels.Add((string)labels[i]);
                    Values.Add(outputValues);

                    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 : HeatSeriesNodeModel.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 xLabels = inputs[0] as ArrayList;
            var yLabels = inputs[1] as ArrayList;
            var values = inputs[2] as ArrayList;
            var colors = inputs[3] as ArrayList;

            // TODO - is it worth/possible to display jagged data
            // If data is jagged throw warning
            if (xLabels.Count != values.Count || xLabels.Count == 0)
            {
                throw new Exception("Label and Values do not properly align in length.");
            }

            // Clear current chart values
            XLabels = new List<string>();
            YLabels = new List<string>();
            Values = new List<List<double>>();
            Colors = new List<Color>();

            // Iterate the x and y values separately as they may be different lengths
            for (var i = 0; i < xLabels.Count; i++)
            {
                XLabels.Add((string)xLabels[i]);
            }

            for (var i = 0; i < yLabels.Count; i++)
            {
                YLabels.Add((string)yLabels[i]);
            }

            // Iterate values (count should be x-labels length * y-lables length)
            for (var i = 0; i < values.Count; i++)
            {
                var unpackedValues = values[i] as ArrayList;
                var outputValues = new List<double>();

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

                Values.Add(outputValues);
            }

            // If colors is empty add 1 random color
            if (colors == null || colors.Count == 0)
            {
                Color randomColor = Color.FromArgb(255, (byte)rnd.Next(256), (byte)rnd.Next(256), (byte)rnd.Next(256));
                Colors.Add(randomColor);
            }

            // If provided with 1 color blend white to color
            // Else create color range from provided color
            else
            {
                for(var i = 0; i < colors.Count; i++)
                {
                    var dynColor = (DSCore.Color)colors[i];
                    var convertedColor = Color.FromArgb(dynColor.Alpha, dynColor.Red, dynColor.Green, dynColor.Blue);
                    Colors.Add(convertedColor);
                }
            }

            // TODO - Should this use Dynamo Scheduler to prevent timing issues with redundant calls?
            // Notify UI the data has been modified
            RaisePropertyChanged("DataUpdated");
        }

19 Source : ScatterPlotNodeModel.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 xValues = inputs[1] as ArrayList;
            var yValues = inputs[2] as ArrayList;
            var colors = inputs[3] as ArrayList;

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

            // Clear current chart values
            Labels = new List<string>();
            XValues = new List<List<double>>();
            YValues = new List<List<double>>();
            Colors = new List<SolidColorBrush>();

            // If color count doesn't match replacedle count use random colors
            if (colors.Count != labels.Count)
            {
                for (var i = 0; i < labels.Count; i++)
                {
                    var outputXValues = new List<double>();
                    var outputYValues = new List<double>();

                    var unpackedXValues = xValues[i] as ArrayList;
                    var unpackedYValues = yValues[i] as ArrayList;

                    for (var j = 0; j < unpackedXValues.Count; j++)
                    {
                        outputXValues.Add(Convert.ToDouble(unpackedXValues[j]));
                        outputYValues.Add(Convert.ToDouble(unpackedYValues[j]));
                    }

                    Labels.Add((string)labels[i]);
                    XValues.Add(outputXValues);
                    YValues.Add(outputYValues);

                    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 all inputs should be consistent in length
            else
            {
                for (var i = 0; i < labels.Count; i++)
                {
                    var outputXValues = new List<double>();
                    var outputYValues = new List<double>();

                    var unpackedXValues = xValues[i] as ArrayList;
                    var unpackedYValues = yValues[i] as ArrayList;

                    for (var j = 0; j < unpackedXValues.Count; j++)
                    {
                        outputXValues.Add(Convert.ToDouble(unpackedXValues[j]));
                        outputYValues.Add(Convert.ToDouble(unpackedYValues[j]));
                    }

                    Labels.Add((string)labels[i]);
                    XValues.Add(outputXValues);
                    YValues.Add(outputYValues);

                    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 : Extensions.cs
with MIT License
from AlFasGD

public static List<List<decimal>> Copy(this List<List<decimal>> l)
        {
            var result = new List<List<decimal>>();
            for (int i = 0; i < l.Count; i++)
            {
                var newItem = new List<decimal>();
                for (int j = 0; j < l[i].Count; j++)
                    newItem.Add(l[i][j]);
                result.Add(newItem);
            }
            return result;
        }

19 Source : GenericListExtensions.cs
with MIT License
from AlFasGD

public static List<List<T>> Clone<T>(this List<List<T>> l)
        {
            var result = new List<List<T>>();
            for (int i = 0; i < l.Count; i++)
                result.Add(new List<T>(l[i]));
            return result;
        }

19 Source : NestedLists.cs
with MIT License
from AlFasGD

public void Add(T item)
        {
            lists.Add(new List<T> { item });
            Count++;
        }

19 Source : NestedLists.cs
with MIT License
from AlFasGD

public void Add(List<T> items)
        {
            lists.Add(new List<T>(items));
            Count += items.Count;
        }

19 Source : PbfTileSource.cs
with MIT License
from AliFlux

private static async Task<VectorTile> baseTileToVector(object baseTile)
        {
            var tile = baseTile as Mapbox.VectorTile.VectorTile;
            var result = new VectorTile();

            foreach (var lyrName in tile.LayerNames())
            {
                Mapbox.VectorTile.VectorTileLayer lyr = tile.GetLayer(lyrName);

                var vectorLayer = new VectorTileLayer();
                vectorLayer.Name = lyrName;

                for (int i = 0; i < lyr.FeatureCount(); i++)
                {
                    Mapbox.VectorTile.VectorTileFeature feat = lyr.GetFeature(i);

                    var vectorFeature = new VectorTileFeature();
                    vectorFeature.Extent = 1;
                    vectorFeature.GeometryType = convertGeometryType(feat.GeometryType);
                    vectorFeature.Attributes = feat.GetProperties();

                    var vectorGeometry = new List<List<Point>>();

                    foreach (var points in feat.Geometry<int>())
                    {
                        var vectorPoints = new List<Point>();

                        foreach (var coordinate in points)
                        {
                            var dX = (double)coordinate.X / (double)lyr.Extent;
                            var dY = (double)coordinate.Y / (double)lyr.Extent;

                            vectorPoints.Add(new Point(dX, dY));

                            //var newX = Utils.ConvertRange(dX, extent.Left, extent.Right, 0, vectorFeature.Extent);
                            //var newY = Utils.ConvertRange(dY, extent.Top, extent.Bottom, 0, vectorFeature.Extent);

                            //vectorPoints.Add(new Point(newX, newY));
                        }

                        vectorGeometry.Add(vectorPoints);
                    }

                    vectorFeature.Geometry = vectorGeometry;
                    vectorLayer.Features.Add(vectorFeature);
                }

                result.Layers.Add(vectorLayer);
            }

            return result;
        }

19 Source : VectorTile.cs
with MIT License
from AliFlux

public VectorTile ApplyExtent(Rect extent)
        {
            VectorTile newTile = new VectorTile();
            newTile.IsOverZoomed = this.IsOverZoomed;
            
            foreach(var layer in Layers)
            {
                var vectorLayer = new VectorTileLayer();
                vectorLayer.Name = layer.Name;

                foreach (var feature in layer.Features)
                {
                    var vectorFeature = new VectorTileFeature();
                    vectorFeature.Attributes = new Dictionary<string, object>(feature.Attributes);
                    vectorFeature.Extent = feature.Extent;
                    vectorFeature.GeometryType = feature.GeometryType;

                    var vectorGeometry = new List<List<Point>>();
                    foreach (var geometry in feature.Geometry)
                    {
                        var vectorPoints = new List<Point>();

                        foreach (var point in geometry)
                        {

                            var newX = Utils.ConvertRange(point.X, extent.Left, extent.Right, 0, vectorFeature.Extent);
                            var newY = Utils.ConvertRange(point.Y, extent.Top, extent.Bottom, 0, vectorFeature.Extent);

                            vectorPoints.Add(new Point(newX, newY));
                        }

                        vectorGeometry.Add(vectorPoints);
                    }

                    vectorFeature.Geometry = vectorGeometry;
                    vectorLayer.Features.Add(vectorFeature);
                }

                newTile.Layers.Add(vectorLayer);
            }

            return newTile;
        }

19 Source : Program.cs
with MIT License
from alkampfergit

private static void AddTableContent(
            WordManipulator manipulator,
            List<WorkItem> workItems,
            WordTemplateFolderManager template)
        {
            string tableFileName = template.GetTable("A", true);
            using (var tableManipulator = new WordManipulator(tableFileName, false))
            {
                List<List<String>> table = new List<List<string>>();
                foreach (WorkItem workItem in workItems)
                {
                    List<String> row = new List<string>();
                    row.Add(workItem.Id.ToString());
                    row.Add(workItem.GetFieldValuereplacedtring("System.replacedignedTo"));
                    row.Add(workItem.AttachedFileCount.ToString());
                    table.Add(row);
                }
                tableManipulator.FillTable(true, table);
            }
            manipulator.AppendOtherWordFile(tableFileName);
            File.Delete(tableFileName);
        }

19 Source : WordManipulator.cs
with MIT License
from alkampfergit

public WordManipulator FillTableWithSingleFieldWorkItems(
            Boolean skipHeader,
            IEnumerable<WorkItem> workItems)
        {
            var table = _doreplacedent.MainDoreplacedentPart.Doreplacedent.Body
                .Descendants<Table>()
                .FirstOrDefault();
            if (table != null)
            {
                //remove every rows but first save the first two rows for the formatting.
                var rows = table.Elements<TableRow>().ToList();
                Int32 skip = skipHeader ? 1 : 0;
                var rowWithField = rows.Skip(skip).First();
                List<List<String>> workItemCellsData = new List<List<string>>();
                List<String> cellFields = new List<string>();
                var cells = rowWithField.Descendants<TableCell>().ToList();
                foreach (var dataCell in cells)
                {
                    //ok for each cell we need to grab the field name
                    //in this first version we support only a field for each column
                    var dataCellText = dataCell.InnerText;
                    var match = Regex.Match(dataCellText, @"\{\{(?<name>.*?)\}\}");
                    if (match.Success)
                    {
                        cellFields.Add(match.Groups["name"].Value);
                    }
                    else
                    {
                        cellFields.Add("");
                    }
                }
                foreach (var workItem in workItems)
                {
                    List<String> row = new List<string>();
                    var properties = workItem.CreateDictionaryFromWorkItem();
                    foreach (var field in cellFields)
                    {
                        if (properties.TryGetValue(field, out var value))
                        {
                            row.Add(value as String);
                        }
                        else
                        {
                            row.Add(String.Empty);
                        }
                    }
                    workItemCellsData.Add(row);
                }

                FillTable(true, workItemCellsData);
            }
            return this;
        }

19 Source : SeaOfWavesSystem.cs
with MIT License
from allenwp

public static List<List<WaveTile>> CreateSea()
        {
            var rowCount = 30;
            var tileCount = 20;

            var result = new List<List<WaveTile>>(rowCount);
            for (int row = 0; row < rowCount; row++)
            {
                var list = new List<WaveTile>(tileCount);
                for (int tileIndex = 0; tileIndex < tileCount; tileIndex++)
                {
                    var enreplacedy = EnreplacedyAdmin.Instance.CreateEnreplacedy("WaveTile");
                    var tile = EnreplacedyAdmin.Instance.AddComponent<WaveTile>(enreplacedy);
                    tile.DrawLength = 0.5f;
                    var transform = EnreplacedyAdmin.Instance.AddComponent<Transform>(enreplacedy);
                    transform.LocalScale = new Vector3(5f, 1f, 1f);
                    transform.LocalPosition = new Vector3(tileIndex * transform.LocalScale.X - ((tileCount * transform.LocalScale.X) / 2f), 0, row * -3f);
                    list.Add(tile);
                }
                result.Add(list);
            }
            return result;
        }

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

public static bool PolicyContainsMatchingRule(XacmlPolicy policy, Rule rule)
        {
            string ruleResourceKey = GetAttributeMatchKey(rule.Resource);
            
            foreach (XacmlRule policyRule in policy.Rules)
            {
                if (!policyRule.Effect.Equals(XacmlEffectType.Permit) || policyRule.Target == null)
                {
                    continue;
                }

                List<List<AttributeMatch>> policyResourceMatches = new List<List<AttributeMatch>>();
                bool matchingActionFound = false;
                foreach (XacmlAnyOf anyOf in policyRule.Target.AnyOf)
                {
                    foreach (XacmlAllOf allOf in anyOf.AllOf)
                    {
                        List<AttributeMatch> resourceMatch = new List<AttributeMatch>();
                        foreach (XacmlMatch xacmlMatch in allOf.Matches)
                        {
                            if (xacmlMatch.AttributeDesignator.Category.Equals(XacmlConstants.MatchAttributeCategory.Resource))
                            {
                                resourceMatch.Add(new AttributeMatch { Id = xacmlMatch.AttributeDesignator.AttributeId.OriginalString, Value = xacmlMatch.AttributeValue.Value });
                            }
                            else if (xacmlMatch.AttributeDesignator.Category.Equals(XacmlConstants.MatchAttributeCategory.Action) &&
                                xacmlMatch.AttributeDesignator.AttributeId.OriginalString == rule.Action.Id &&
                                xacmlMatch.AttributeValue.Value == rule.Action.Value)
                            {
                                matchingActionFound = true;
                            }
                        }

                        if (resourceMatch.Any())
                        {
                            policyResourceMatches.Add(resourceMatch);
                        }
                    }
                }

                if (policyResourceMatches.Any(resourceMatch => GetAttributeMatchKey(resourceMatch) == ruleResourceKey) && matchingActionFound)
                {
                    int guidIndex = policyRule.RuleId.IndexOf(AltinnXacmlConstants.Prefixes.RuleId);
                    rule.RuleId = policyRule.RuleId.Substring(guidIndex + AltinnXacmlConstants.Prefixes.RuleId.Length);
                    return true;
                }
            }

            return false;
        }

19 Source : Helper.cs
with MIT License
from amidos2006

public static List<List<int>> getPermutations(List<int> values, int size){
            List<List<int>> result = new List<List<int>>();
            if(size == 0){
                return result;
            }
            
            for(int i=0; i < values.Count; i++){
                List<int> clone = copyList<int>(values);
                clone.RemoveAt(i);
                List<List<int>> tempResult = getPermutations(clone, size - 1);
                if(tempResult.Count == 0){
                    result.Add(new List<int>());
                    result[result.Count - 1].Add(values[i]);
                }
                foreach(List<int> list in tempResult){
                    list.Insert(0, values[i]);
                    result.Add(list);
                }
            }
            
            return result;
        }

19 Source : PendingChangeHandler.cs
with Apache License 2.0
from AmpScm

public IEnumerable<PendingCommitState> GetCommitRoots(IEnumerable<PendingChange> changes)
        {
            List<SvnWorkingCopy> wcs = new List<SvnWorkingCopy>();
            List<List<PendingChange>> pcs = new List<List<PendingChange>>();

            foreach (PendingChange pc in changes)
            {
                SvnItem item = pc.SvnItem;
                SvnWorkingCopy wc = item.WorkingCopy;

                if (wc != null)
                {
                    int n = wcs.IndexOf(wc);

                    List<PendingChange> wcChanges;
                    if (n < 0)
                    {
                        wcs.Add(wc);
                        pcs.Add(wcChanges = new List<PendingChange>());
                    }
                    else
                        wcChanges = pcs[n];

                    wcChanges.Add(pc);
                }
            }

            if (wcs.Count <= 1)
            {
                yield return new PendingCommitState(Context, changes);
                yield break;
            }

            using (MultiWorkingCopyCommit dlg = new MultiWorkingCopyCommit())
            {
                dlg.SetInfo(wcs, pcs);

                if (dlg.ShowDialog(Context) != DialogResult.OK || dlg.ChangeGroups.Count == 0)
                {
                    yield return null;
                    yield break;
                }

                foreach (List<PendingChange> chg in dlg.ChangeGroups)
                {
                    yield return new PendingCommitState(Context, chg);
                }
            }
        }

See More Examples