System.Collections.Generic.List.RemoveRange(int, int)

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

1075 Examples 7

19 View Source File : ChatCommands.cs
License : MIT License
Project Creator : 0x0ade

public virtual void ParseAndRun(ChatCMDEnv env) {
            // TODO: Improve or rewrite. This comes from GhostNet, which adopted it from disbot (0x0ade's C# Discord bot).

            string raw = env.FullText;

            int index = Chat.Settings.CommandPrefix.Length + ID.Length - 1; // - 1 because next space required
            List<ChatCMDArg> args = new();
            while (
                index + 1 < raw.Length &&
                (index = raw.IndexOf(' ', index + 1)) >= 0
            ) {
                int next = index + 1 < raw.Length ? raw.IndexOf(' ', index + 1) : -2;
                if (next < 0)
                    next = raw.Length;

                int argIndex = index + 1;
                int argLength = next - index - 1;

                // + 1 because space
                args.Add(new ChatCMDArg(env).Parse(raw, argIndex, argLength));

                // Parse a split up range (with spaces) into a single range arg
                if (args.Count >= 3 &&
                    args[args.Count - 3].Type == ChatCMDArgType.Int &&
                    (args[args.Count - 2].String == "-" || args[args.Count - 2].String == "+") &&
                    args[args.Count - 1].Type == ChatCMDArgType.Int
                ) {
                    args.Add(new ChatCMDArg(env).Parse(raw, args[args.Count - 3].Index, next - args[args.Count - 3].Index));
                    args.RemoveRange(args.Count - 4, 3);
                    continue;
                }
            }

            Run(env, args);
        }

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

private void StopSentTimer(int recvTickAck, long idleTime)
    {
        if (tickBuffer.Exists(x => x.tickNum == recvTickAck))
        {
            var item = tickBuffer.Find(x => x.tickNum == recvTickAck);
            long now = m_StopWatch.ElapsedTicks;

            m_currentRtt = (int) ((now - item.sentTime - idleTime) / m_FrequencyMS);
            m_currentLag = (int) ((now - item.sentTime) / m_FrequencyMS);
            
            // Debug printing
            // Debug.Log("Pure RTT: " + m_currentRtt);
            // Debug.Log("Over all Lag: " + m_currentLag);

            // Since we got the Ack back we don't have to store the tick anymore and every tick until that tick (Because of tcp).
            // A better approach would a 4 bytes mask where every bit is whether we got the tick or not.
            tickBuffer.RemoveRange(0, tickBuffer.LastIndexOf(item));
        }
    }

19 View Source File : ListExtension.cs
License : MIT License
Project Creator : a3geek

public static void SetCount<T>(this List<T> list, int count, Func<int, T> defaultValue = null)
        {
            count = count < 0 ? 0 : count;
            defaultValue = defaultValue ?? (i => default(T));

            if(list.Count < count)
            {
                for(var i = list.Count; i < count; i++)
                {
                    list.Add(defaultValue(i));
                }
            }
            else if(list.Count > count)
            {
                list.RemoveRange(count, list.Count - count);
            }
        }

19 View Source File : WebServer.cs
License : Apache License 2.0
Project Creator : A7ocin

public string GetLog(string lineBreak = "\n")
        {
            var sb = new System.Text.StringBuilder();
            lock (_requestLog)
            {
                if (_requestLog.Count > 50)
                {
                    _requestLog.RemoveRange(0, _requestLog.Count - 50);
                }
                for (int i = 0; i < _requestLog.Count; i++)
                {
                    sb.Append(_requestLog[i]);
                    sb.Append(lineBreak);
                }
            }
            return sb.ToString();
        }

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

void UpdateOffsets(Func<int, AnchorMovementType, int> updateOffset)
		{
			int readPos = 1;
			int writePos = 1;
			while (readPos < stateChangeOffsets.Count) {
				Debug.replacedert(writePos <= readPos);
				int newOffset = updateOffset(stateChangeOffsets[readPos], AnchorMovementType.Default);
				if (newOffset == stateChangeOffsets[writePos - 1]) {
					// offset moved to same position as previous offset
					// -> previous segment has length 0 and gets overwritten with this segment
					stateChanges[writePos - 1] = stateChanges[readPos];
				} else {
					stateChangeOffsets[writePos] = newOffset;
					stateChanges[writePos] = stateChanges[readPos];
					writePos++;
				}
				readPos++;
			}
			// Delete all entries that were not written to
			stateChangeOffsets.RemoveRange(writePos, stateChangeOffsets.Count - writePos);
			stateChanges.RemoveRange(writePos, stateChanges.Count - writePos);
		}

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

public void SetHighlighting(int offset, int length, HighlightingColor color)
		{
			if (length <= 0)
				return;
			int startIndex = GetIndexForOffset(offset);
			int endIndex = GetIndexForOffset(offset + length);
			stateChanges[startIndex] = color != null ? color.Clone() : new HighlightingColor();
			stateChanges.RemoveRange(startIndex + 1, endIndex - (startIndex + 1));
			stateChangeOffsets.RemoveRange(startIndex + 1, endIndex - (startIndex + 1));
		}

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

public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
		{
			if (phase != LifetimePhase.Transforming)
				throw new InvalidOperationException("This method may only be called by line transformers.");
			int oldDoreplacedentLength = 0;
			for (int i = elementIndex; i < elementIndex + count; i++) {
				oldDoreplacedentLength += elements[i].DoreplacedentLength;
			}
			int newDoreplacedentLength = 0;
			foreach (var newElement in newElements) {
				newDoreplacedentLength += newElement.DoreplacedentLength;
			}
			if (oldDoreplacedentLength != newDoreplacedentLength)
				throw new InvalidOperationException("Old elements have doreplacedent length " + oldDoreplacedentLength + ", but new elements have length " + newDoreplacedentLength);
			elements.RemoveRange(elementIndex, count);
			elements.InsertRange(elementIndex, newElements);
			CalculateOffsets();
		}

19 View Source File : LeapMotionConfigurationChecker.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static string GetPathDifference()
        {
            // The file LeapXRServiceProvider.cs is used as a location anchor instead of the LeapMotion directory
            // to avoid a potential incorrect location return if there is a folder named LeapMotion prior to the leap 
            // core replacedets import 
            FileInfo[] leapPathLocationAnchor = FileUtilities.FindFilesInreplacedets(trackedLeapFileName);
            string leapFilePath = leapPathLocationAnchor[0].FullName;

            List<string> leapPath = leapFilePath.Split(Path.DirectorySeparatorChar).ToList();

            // Remove the last 3 elements of leap path (/Core/Scripts/LeapXRService.cs) from the list to get the root of the leap core replacedets
            leapPath.RemoveRange(leapPath.Count - 3, 3);

            List<string> unityDataPath = Application.dataPath.Split('/').ToList();
            unityDataPath.Add("LeapMotion");

            // Get the difference between the root of replacedets and the root of leap core replacedets
            IEnumerable<string> difference = leapPath.Except(unityDataPath);

            return string.Join("/", difference);
        }

19 View Source File : DamageHistory.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void Prune()
        {
            var entriesToRemove = 0;

            foreach (var entry in Log)
            {
                if (entry.Time + maximumTimeToRetain < DateTime.UtcNow)
                    entriesToRemove++;
                else
                    break;
            }

            if (entriesToRemove > 0)
            {
                Log.RemoveRange(0, entriesToRemove);
                BuildTotalDamage();
                //Console.WriteLine($"DamageHistory.Prune() - {entriesToRemove} entries removed");
            }

            LastPruneTime = DateTime.UtcNow;
        }

19 View Source File : TextureMergeInfo.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void PostInit()
        {
            TerrainOverlays = TerrainOverlays.Where(t => t != null).ToList();
            TerrainAlphaOverlays = TerrainAlphaOverlays.Where(t => t != null).ToList();
            var numTerrains = TerrainOverlays.Count;
            TerrainRotations.RemoveRange(numTerrains, 3 - numTerrains);
            TerrainAlphaIndices = TerrainAlphaIndices.Where(t => t != -1).ToList();

            RoadAlphaOverlays = RoadAlphaOverlays.Where(r => r != null).ToList();
            var numRoads = RoadAlphaOverlays.Count;
            RoadRotations.RemoveRange(numRoads, 2 - numRoads);
            RoadAlphaIndices = RoadAlphaIndices.Where(r => r != -1).ToList();
        }

19 View Source File : MainWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : ACEmulator

public async void AddStatusText(string line)
        {
            statusLines.Add(line);

            var timeSinceLastUpdate = DateTime.Now - lastUpdateTime;

            if (timeSinceLastUpdate < maxUpdateInterval)
            {
                if (pendingUpdate)
                    return;

                pendingUpdate = true;
                await Task.Delay((int)maxUpdateInterval.TotalMilliseconds);
                pendingUpdate = false;
            }

            if (statusLines.Count > maxLines)
                statusLines.RemoveRange(0, statusLines.Count - maxLines);

            Status.Text = string.Join("\n", statusLines);
            Status.ScrollToEnd();

            lastUpdateTime = DateTime.Now;
        }

19 View Source File : SelectionHistory.cs
License : MIT License
Project Creator : acoppes

public void UpdateSelection(Object selection)
        {
            if (selection == null)
                return;

            var lastSelectedObject = _history.Count > 0 ? _history.Last() : null;

            var isLastSelected = lastSelectedObject != null && lastSelectedObject.reference == selection;
            var isCurrentSelection = currentSelection != null && currentSelection.reference == selection;
            
            if (!isLastSelected && !isCurrentSelection)
            {
                _history.Add(new Entry(selection));
                currentSelectionIndex = _history.Count - 1;
                
                OnNewEntryAdded?.Invoke(this);
            }

            if (_history.Count > historySize)
            {
                _history.RemoveRange(0, _history.Count - historySize);
                //			_history.RemoveAt(0);
            }
        }

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

private void UpdateSearchResults() {
			var list = new List<ProducreplacedemInfo>();

			// Score all items
			var searchParts = this.SearchText.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
			foreach (var productFamily in this.ProductData.ProductFamilies) {
				foreach (var producreplacedemInfo in productFamily.Items) {
					producreplacedemInfo.SearchScore = SampleSearchScorer.Score(producreplacedemInfo, searchParts);
					if (producreplacedemInfo.SearchScore > 0)
						list.Add(producreplacedemInfo);
				}
			}

			// Sort
			list.Sort((x, y) => y.SearchScore.CompareTo(x.SearchScore));

			// Trim to the maximum number of results
			if (list.Count > MaximumSearchResults)
				list.RemoveRange(MaximumSearchResults, list.Count - MaximumSearchResults);

			this.SearchResults = list;
		}

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

public void NavigateTo(ProducreplacedemInfo itemInfo) {
			if (this.IsNavigatingThroughHistory)
				return;

			historyIndex++;
			history.RemoveRange(historyIndex, history.Count - historyIndex);
			history.Add(itemInfo);

			if (history.Count > MaxHistoryCount) {
				historyIndex--;
				history.RemoveAt(0);
			}
		}

19 View Source File : LogCatWindow.cs
License : MIT License
Project Creator : adrenak

private void AddLog(LogCatLog log) {
            lock (logsList) {
                if (logsList.Count > memoryLimit + 1)
                    logsList.RemoveRange(0, logsList.Count - memoryLimit + 1);

                logsList.Add(log);
            }
        }

19 View Source File : BytePacker.cs
License : Apache License 2.0
Project Creator : advancer68

public void Recv(byte[] buff)
    {
        cache.AddRange(buff);
        while (true)
        {
            if (curPkgSize < 0)// if not pkg size
            {
                if (cache.Count > pkgLengthByteSize)
                {
                    //get pkg size
                    cache.CopyTo(0, pkgLengthBytes, 0, pkgLengthByteSize);
                    cache.RemoveRange(0, pkgLengthByteSize);
                    curPkgSize = BitConverter.ToInt32(pkgLengthBytes, 0);
                }
                else
                {
                    break;
                }
            }

            if (cache.Count >= curPkgSize)
            {//get pkg data
                var pkgData = new byte[curPkgSize];
                cache.CopyTo(0, pkgData, 0, pkgData.Length);
                cache.RemoveRange(0, curPkgSize);
                func.Invoke(pkgData);
                //reset pkg size
                curPkgSize = -1;
            }
            else
            {
                break;
            }
        }
    }

19 View Source File : kcp.cs
License : Apache License 2.0
Project Creator : advancer68

public int Receive(ByteBuf buffer)
    {
        if (rcv_queue.Count <= 0)
        {
            return -1;
        }
        int peekSize = PeekSize();
        if (peekSize < 0)
        {
            return -2;
        }
        bool recover = rcv_queue.Count >= rcv_wnd;
        // merge fragment.
        int c = 0;
        int len = 0;
        for (int i = 0; i < rcv_queue.Count; i++)
        {
            Segment seg = rcv_queue[i];
            len += seg.data.Size;
            buffer.WriteBytesFrom(seg.data);
            c++;
            if (seg.frg == 0)
            {
                break;
            }
        }
        if (c > 0)
        {
            for (int i = 0; i < c; i++)
            {
                SegmentDelete(rcv_queue[i]);
            }
            rcv_queue.RemoveRange(0, c);
        }
        if (len != peekSize)
        {
            throw new Exception("数据异常.");
        }
        // move available data from rcv_buf -> rcv_queue
        c = 0;
        for (int i = 0; i < rcv_buf.Count; i++)
        {
            Segment seg = rcv_buf[i];
            if (seg.sn == rcv_nxt && rcv_queue.Count < rcv_wnd)
            {
                rcv_queue.Add(seg);
                rcv_nxt++;
                c++;
            }
            else
            {
                break;
            }
        }
        if (c > 0)
            rcv_buf.RemoveRange(0, c);
        // fast recover
        if (rcv_queue.Count < rcv_wnd && recover)
        {
            // ready to send back IKCP_CMD_WINS in ikcp_flush
            // tell remote my window size
            probe |= IKCP_ASK_TELL;
        }
        return len;
    }

19 View Source File : kcp.cs
License : Apache License 2.0
Project Creator : advancer68

private void Parse_una(int una)
    {
        int c = 0;
        for (int i = 0; i < snd_buf.Count; i++)
        {
            Segment seg = snd_buf[i];
            if (_itimediff(una, seg.sn) > 0)
            {
                c++;
            }
            else
            {
                break;
            }
        }
        if (c > 0)
        {
            for (int i = 0; i < c; i++)
            {
                SegmentDelete(snd_buf[i]);
            }
            snd_buf.RemoveRange(0, c);
        }
    }

19 View Source File : kcp.cs
License : Apache License 2.0
Project Creator : advancer68

private void Parse_data(Segment newseg)
    {
        int sn = newseg.sn;
        if (_itimediff(sn, rcv_nxt + rcv_wnd) >= 0 || _itimediff(sn, rcv_nxt) < 0)
        {
            SegmentDelete(newseg);
            return;
        }
        int n = rcv_buf.Count - 1;
        int temp = -1;
        bool repeat = false;
        for (int i = n; i >= 0; i--)
        {
            Segment seg = rcv_buf[i];
            if (seg.sn == sn)
            {
                repeat = true;
                break;
            }
            if (_itimediff(sn, seg.sn) > 0)
            {
                temp = i;
                break;
            }
        }
        if (!repeat)
        {
            if (temp == -1)
            {
                rcv_buf.Insert(0, newseg);
            }
            else
            {
                rcv_buf.Insert(temp + 1, newseg);
            }
        }
        else
        {
            SegmentDelete(newseg);
        }
        // move available data from rcv_buf -> rcv_queue
        int c = 0;
        for (int i = 0; i < rcv_buf.Count; i++)
        {
            Segment seg = rcv_buf[i];
            if (seg.sn == rcv_nxt && rcv_queue.Count < rcv_wnd)
            {
                rcv_queue.Add(seg);
                rcv_nxt++;
                c++;
            }
            else
            {
                break;
            }
        }
        if (c > 0)
        {
            rcv_buf.RemoveRange(0, c);
        }
    }

19 View Source File : kcp.cs
License : Apache License 2.0
Project Creator : advancer68

private void Flush()
    {
        int cur = current;
        int change = 0;
        int lost = 0;
        if (updated == 0)
        {
            return;
        }
        Segment seg = new Segment(0);
        seg.conv = conv;
        seg.cmd = IKCP_CMD_ACK;
        seg.wnd = wnd_unused();
        seg.una = rcv_nxt;
        // flush acknowledges
        int c = acklist.Count / 2;
        for (int i = 0; i < c; i++)
        {
            if (buffer.Size + IKCP_OVERHEAD > mtu)
            {
                this.Output(buffer);
            }
            seg.sn = acklist[i * 2 + 0];
            seg.ts = acklist[i * 2 + 1];
            seg.Encode(buffer);
        }
        acklist.Clear();
        // probe window size (if remote window size equals zero)
        if (rmt_wnd == 0)
        {
            if (probe_wait == 0)
            {
                probe_wait = IKCP_PROBE_INIT;
                ts_probe = current + probe_wait;
            }
            else if (_itimediff(current, ts_probe) >= 0)
            {
                if (probe_wait < IKCP_PROBE_INIT)
                {
                    probe_wait = IKCP_PROBE_INIT;
                }
                probe_wait += probe_wait / 2;
                if (probe_wait > IKCP_PROBE_LIMIT)
                {
                    probe_wait = IKCP_PROBE_LIMIT;
                }
                ts_probe = current + probe_wait;
                probe |= IKCP_ASK_SEND;
            }
        }
        else
        {
            ts_probe = 0;
            probe_wait = 0;
        }
        // flush window probing commands
        if ((probe & IKCP_ASK_SEND) != 0)
        {
            seg.cmd = IKCP_CMD_WASK;
            if (buffer.Size + IKCP_OVERHEAD > mtu)
            {
                this.Output(buffer);
            }
            seg.Encode(buffer);
        }
        // flush window probing commands
        if ((probe & IKCP_ASK_TELL) != 0)
        {
            seg.cmd = IKCP_CMD_WINS;
            if (buffer.Size + IKCP_OVERHEAD > mtu)
            {
                this.Output(buffer);
            }
            seg.Encode(buffer);
        }
        probe = 0;
        // calculate window size
        int cwnd_temp = Math.Min(snd_wnd, rmt_wnd);
        if (nocwnd == 0)
        {
            cwnd_temp = Math.Min(cwnd, cwnd_temp);
        }
        // move data from snd_queue to snd_buf
        c = 0;
        for (int i = 0; i < snd_queue.Count; i++)
        {
            Segment item = snd_queue[i];
            if (_itimediff(snd_nxt, snd_una + cwnd_temp) >= 0)
            {
                break;
            }
            Segment newseg = item;
            newseg.conv = conv;
            newseg.cmd = IKCP_CMD_PUSH;
            newseg.wnd = seg.wnd;
            newseg.ts = cur;
            newseg.sn = snd_nxt++;
            newseg.una = rcv_nxt;
            newseg.resendts = cur;
            newseg.rto = rx_rto;
            newseg.fastack = 0;
            newseg.xmit = 0;
            snd_buf.Add(newseg);
            c++;
        }
        if (c > 0)
        {
            snd_queue.RemoveRange(0, c);
        }
        // calculate resent
        int resent = (fastresend > 0) ? fastresend : int.MaxValue;
        int rtomin = (nodelay == 0) ? (rx_rto >> 3) : 0;
        // flush data segments
        for (int i = 0; i < snd_buf.Count; i++)
        {
            Segment segment = snd_buf[i];
            bool needsend = false;
            if (segment.xmit == 0)
            {
                needsend = true;
                segment.xmit++;
                segment.rto = rx_rto;
                segment.resendts = cur + segment.rto + rtomin;
            }
            else if (_itimediff(cur, segment.resendts) >= 0)
            {
                needsend = true;
                segment.xmit++;
                xmit++;
                if (nodelay == 0)
                {
                    segment.rto += rx_rto;
                }
                else
                {
                    segment.rto += rx_rto / 2;
                }
                segment.resendts = cur + segment.rto;
                lost = 1;
            }
            else if (segment.fastack >= resent)
            {
                needsend = true;
                segment.xmit++;
                segment.fastack = 0;
                segment.resendts = cur + segment.rto;
                change++;
            }
            if (needsend)
            {
                segment.ts = cur;
                segment.wnd = seg.wnd;
                segment.una = rcv_nxt;
                int need = IKCP_OVERHEAD + segment.data.Size;
                if (buffer.Size + need > mtu)
                {
                    this.Output(buffer);
                }
                segment.Encode(buffer);
                if (segment.data.Size > 0)
                {
                    buffer.WriteBytesFrom(segment.data);
                }
                if (segment.xmit >= dead_link)
                {
                    state = -1;
                }
            }
        }
        // flash remain segments
        if (buffer.Size > 0)
        {
            this.Output(buffer);
        }
        // update ssthresh
        if (change != 0)
        {
            int inflight = snd_nxt - snd_una;
            ssthresh = inflight / 2;
            if (ssthresh < IKCP_THRESH_MIN)
            {
                ssthresh = IKCP_THRESH_MIN;
            }
            cwnd = ssthresh + resent;
            incr = cwnd * mss;
        }
        if (lost != 0)
        {
            ssthresh = cwnd / 2;
            if (ssthresh < IKCP_THRESH_MIN)
            {
                ssthresh = IKCP_THRESH_MIN;
            }
            cwnd = 1;
            incr = mss;
        }
        if (cwnd < 1)
        {
            cwnd = 1;
            incr = mss;
        }
    }

19 View Source File : SwimPatches.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public static IEnumerable<CodeInstruction> Farmer_updateCommon_Transpiler(IEnumerable<CodeInstruction> instructions)
        {

            var codes = new List<CodeInstruction>(instructions);
            try
            {
                bool startLooking = false;
                int start = -1;
                int end = -1;
                for (int i = 0; i < codes.Count; i++)
                {
                    if (startLooking)
                    {
                        if(start == -1 && codes[i].opcode == OpCodes.Ldfld && codes[i].operand as FieldInfo == typeof(Farmer).GetField("timerSinceLastMovement"))
                        {
                            start = i - 1;
                            Monitor.Log($"start at {start}");
                        }
                        if (codes[i].opcode == OpCodes.Stfld && codes[i].operand as FieldInfo == typeof(Farmer).GetField("health"))
                        {
                            end = i + 1;
                            Monitor.Log($"end at {end}");
                        }
                    }
                    else if (codes[i].operand as string == "slosh")
                    {
                        startLooking = true;
                    }
                }
                if(start > -1 && end > start)
                {
                    codes.RemoveRange(start, end - start);
                }
            }
            catch (Exception ex)
            {
                Monitor.Log($"Failed in {nameof(Farmer_updateCommon_Transpiler)}:\n{ex}", LogLevel.Error);
            }

            return codes.AsEnumerable();
        }

19 View Source File : UndergroundPatches.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public static IEnumerable<CodeInstruction> MineShaft_populateLevel_transpiler(IEnumerable<CodeInstruction> instructions)
        {

            var codes = new List<CodeInstruction>(instructions);
            try
            {
                bool start = false;
                for (int i = 0; i < codes.Count; i++)
                {
                    if (codes[i].opcode == OpCodes.Ldarg_0)
                    {
                        if (start)
                        {
                            codes.RemoveRange(i, 3);
                            break;
                        }
                        else
                            start = true;
                    }
                }
            }
            catch (Exception ex)
            {
                monitor.Log($"Failed in {nameof(MineShaft_populateLevel_transpiler)}:\n{ex}", LogLevel.Error);
            }

            return codes.AsEnumerable();
        }

19 View Source File : PointDefinition.cs
License : MIT License
Project Creator : Aeroluna

public static PointDefinition ListToPointDefinition(List<object> list)
        {
            IEnumerable<List<object>> points;
            if (list.FirstOrDefault() is List<object>)
            {
                points = list.Cast<List<object>>();
            }
            else
            {
                points = new List<object>[] { list.Append(0).ToList() };
            }

            List<PointData> pointData = new List<PointData>();
            foreach (List<object> rawPoint in points)
            {
                int flagIndex = -1;
                int cachedCount = rawPoint.Count;
                for (int i = cachedCount - 1; i > 0; i--)
                {
                    if (rawPoint[i] is string)
                    {
                        flagIndex = i;
                    }
                    else
                    {
                        break;
                    }
                }

                Functions easing = Functions.easeLinear;
                bool spline = false;
                List<object> copiedList = rawPoint.ToList();
                if (flagIndex != -1)
                {
                    List<string> flags = rawPoint.GetRange(flagIndex, cachedCount - flagIndex).Cast<string>().ToList();
                    copiedList.RemoveRange(flagIndex, cachedCount - flagIndex);

                    string easingString = flags.Where(n => n.StartsWith("ease")).FirstOrDefault();
                    if (easingString != null)
                    {
                        easing = (Functions)Enum.Parse(typeof(Functions), easingString);
                    }

                    // TODO: add more spicy splines
                    string splineString = flags.Where(n => n.StartsWith("spline")).FirstOrDefault();
                    if (splineString == "splineCatmullRom")
                    {
                        spline = true;
                    }
                }

                if (copiedList.Count() == 2)
                {
                    Vector2 vector = new Vector2(Convert.ToSingle(copiedList[0]), Convert.ToSingle(copiedList[1]));
                    pointData.Add(new PointData(vector, easing));
                }
                else if (copiedList.Count() == 4)
                {
                    Vector4 vector = new Vector4(Convert.ToSingle(copiedList[0]), Convert.ToSingle(copiedList[1]), Convert.ToSingle(copiedList[2]), Convert.ToSingle(copiedList[3]));
                    pointData.Add(new PointData(vector, easing, spline));
                }
                else
                {
                    Vector5 vector = new Vector5(Convert.ToSingle(copiedList[0]), Convert.ToSingle(copiedList[1]), Convert.ToSingle(copiedList[2]), Convert.ToSingle(copiedList[3]), Convert.ToSingle(copiedList[4]));
                    pointData.Add(new PointData(vector, easing));
                }
            }

            return new PointDefinition(pointData);
        }

19 View Source File : Planet.PrepareSubdivision.cs
License : The Unlicense
Project Creator : aeroson

void Phase_4_Sort()
		{
			// bigger weight is first
			toRenderChunks.Sort((ToRenderChunks a, ToRenderChunks b) => b.weight.CompareTo(a.weight));

			if (toRenderChunks.Count > maxChunksToRender)
			{ 
				toRenderChunks.RemoveRange(maxChunksToRender, toRenderChunks.Count - maxChunksToRender);
			}
		}

19 View Source File : StationCounter.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static void Start()
        {
            var file = Path.Combine(ZeroApplication.Config.DataFolder, "kline_station.json");
            if (File.Exists(file))
            {
                try
                {
                    var json = File.ReadAllText(file);
                    var dir = JsonConvert.DeserializeObject<Dictionary<string, List<KLine>>>(json);
                    if (dir != null)
                        KLines = dir;
                    var now = DateTime.Now.AddMinutes(-1);//上一分钟
                    BaseLine = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0);
                    foreach (var items in KLines.Values.ToArray())
                    {
                        var array = items.ToArray();
                        var line = GetTime(BaseLine);
                        int cnt = 0;
                        for (int idx = array.Length - 1; idx >= 0; idx++)
                        {
                            ++cnt;
                            var sp = line - array[idx].Time;
                            if (sp < 0)
                                continue;
                            if (sp == 0)
                            {
                                line -= 60000;//一分钟
                                continue;
                            }
                            while (line > array[idx].Time && cnt <= 240)
                            {
                                if (idx == items.Count - 1)
                                {
                                    items.Add(new KLine
                                    {
                                        Time = line
                                    });
                                }
                                else
                                {
                                    items.Insert(idx + 1, new KLine
                                    {
                                        Time = line
                                    });
                                }
                                line -= 60000;
                                ++cnt;
                            }
                            if(cnt > 240)
                            {
                                if (items.Count > 240)
                                    items.RemoveRange(0, items.Count - 240);
                                break;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    ZeroTrace.WriteError("Restore Station KLine Data", e, file);
                }
            }
            ZeroApplication.ZeroNetEvent += new StationCounter().SystemMonitor_StationEvent;
        }

19 View Source File : DiscordEmbedBuilder.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public DiscordEmbedBuilder RemoveFieldRange(int index, int count)
        {
            this._fields.RemoveRange(index, count);
            return this;
        }

19 View Source File : Util.cs
License : MIT License
Project Creator : ajayyy

public static int RandomWithLookback( int min, int max, List<int> history, int historyCount )
		{
			int index = UnityEngine.Random.Range( min, max - history.Count );

			for ( int i = 0; i < history.Count; i++ )
			{
				if ( index >= history[i] )
				{
					index++;
				}
			}

			history.Add( index );

			if ( history.Count > historyCount )
			{
				history.RemoveRange( 0, history.Count - historyCount );
			}

			return index;
		}

19 View Source File : NSUrlSessionHandler.cs
License : MIT License
Project Creator : alexrainman

public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
        retry:
            int bytesRead = 0;
            int buffersToRemove = 0;

            if (isCompleted && position == maxLength)
            {
                return 0;
            }

            if (exception != null) throw exception;

            using (await readStreamLock.LockAsync().ConfigureAwait(false))
            {
                lock (bytes)
                {
                    foreach (var buf in bytes)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        if (exception != null) throw exception;

                        int toCopy = Math.Min(count, buf.Length - offsetInCurrentBuffer);
                        Array.ConstrainedCopy(buf, offsetInCurrentBuffer, buffer, offset, toCopy);

                        count -= toCopy;
                        offset += toCopy;
                        bytesRead += toCopy;

                        offsetInCurrentBuffer += toCopy;

                        if (offsetInCurrentBuffer >= buf.Length)
                        {
                            offsetInCurrentBuffer = 0;
                            buffersToRemove++;
                        }

                        if (count <= 0) break;
                    }

                    // Remove buffers that we read in this operation
                    bytes.RemoveRange(0, buffersToRemove);

                    position += bytesRead;
                }
            }

            // If we're at the end of the stream and it's not done, prepare
            // the next read to park itself unless AddByteArray or Complete 
            // posts
            if (position >= maxLength && !isCompleted)
            {
                lockRelease = await readStreamLock.LockAsync().ConfigureAwait(false);
            }

            if (bytesRead == 0 && !isCompleted)
            {
                // NB: There are certain race conditions where we somehow acquire
                // the lock yet are at the end of the stream, and we're not completed
                // yet. We should try again so that we can get stuck in the lock.
                goto retry;
            }

            if (cancellationToken.IsCancellationRequested)
            {
                Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose();
                cancellationToken.ThrowIfCancellationRequested();
            }

            if (exception != null)
            {
                Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose();
                throw exception;
            }

            if (isCompleted && position < maxLength)
            {
                // NB: This solves a rare deadlock 
                //
                // 1. ReadAsync called (waiting for lock release)
                // 2. AddByteArray called (release lock)
                // 3. AddByteArray called (release lock)
                // 4. Complete called (release lock the last time)
                // 5. ReadAsync called (lock released at this point, the method completed successfully) 
                // 6. ReadAsync called (deadlock on LockAsync(), because the lock is block, and there is no way to release it)
                // 
                // Current condition forces the lock to be released in the end of 5th point

                Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose();
            }

            return bytesRead;
        }

19 View Source File : NestedLists.cs
License : MIT License
Project Creator : AlFasGD

public void RemoveFirst(int count)
        {
            Count -= ElementCount(0, count);
            lists.RemoveRange(0, count);
        }

19 View Source File : User.cs
License : MIT License
Project Creator : AliakseiFutryn

public void Compute(int operand, char @operator)
		{
			CalculatorCommand command = new CalculatorCommand(operand, @operator, _calculator);
			command.Execute();

			if (_current < _commands.Count)
			{
				_commands.RemoveRange(_current, _commands.Count - _current);
			}
			_commands.Add(command);
			_current++;
		}

19 View Source File : ListExtension.cs
License : MIT License
Project Creator : allartprotocol

public static List<T> Splice<T>(this List<T> source, int index, int count)
        {
            var items = source.GetRange(index, count);
            source.RemoveRange(index, count);
            return source;
        }

19 View Source File : ArgumentHelper.cs
License : MIT License
Project Creator : amazingalek

public void RemoveArgument(string argument)
		{
			if (HasArgument(argument))
			{
				var index = _arguments.IndexOf($"-{argument}");
				_arguments.RemoveRange(index, 2);
			}
		}

19 View Source File : CardListView.xaml.cs
License : MIT License
Project Creator : Amine-Smahi

private void FillRepeater()
        {
            int numbertimes = VirtualList.Count / 10;
            if (numbertimes > 0)
            {
                try
                {
                    StackLayout stackLayout = new StackLayout();
                    for (int j = 0; j < 10; j++)
                    {
                        stackLayout.Children.Add(new Card(new CardProperties()
                        {
                            Id = VirtualList[j].Id,
                            replacedle = VirtualList[j].replacedle,
                            Description = VirtualList[j].Description,
                            ImagePath = VirtualList[j].ImagePath,
                            IsLiked = VirtualList[j].IsLiked
                        }));
                    }
                    VirtualList.RemoveRange(0, 10);
                    repeater.Children.Add(stackLayout);
                    ScrolledToBottom = 0;
                }
                catch (Exception){}
            }
        }

19 View Source File : UnifiedDiffDropDownBar.cs
License : Apache License 2.0
Project Creator : AmpScm

private bool Parse()
        {
            IVsTextLines lines = _buffer;

            int lastLine, linelen;
            Marshal.ThrowExceptionForHR(lines.GetLastLineIndex(out lastLine, out linelen));

            bool changed = false;

            int n = 0;
            for (int i = 0; i < lastLine; i++)
            {
                Marshal.ThrowExceptionForHR(lines.GetLengthOfLine(i, out linelen));
                if (linelen < 8)
                    continue; // No 'Index: ' line

                string start;
                Marshal.ThrowExceptionForHR(lines.GetLineText(i, 0, i, 7, out start));
                if (!string.Equals(start, "Index: "))
                    continue;

                Marshal.ThrowExceptionForHR(lines.GetLineText(i, 7, i, linelen, out start));

                start = start.Trim();

                if (n >= _indexes.Count || _indexes[n] != start || _lines[n] != i)
                {
                    changed = true;
                    if (n <= _indexes.Count)
                    {
                        _lines.RemoveRange(n, _indexes.Count - n);
                        _indexes.RemoveRange(n, _indexes.Count - n);
                    }

                    _indexes.Add(start);
                    _lines.Add(i);
                }                
                n++;
            }

            if (changed)
            {
                DropDownTypes.Clear();
                for (int i = 0; i < _indexes.Count; i++)
                {
                    TextSpan ts;
                    ts.iStartLine = _lines[i];
                    ts.iStartIndex = 0;
                    ts.iEndLine = (i+1 < _lines.Count) ? _lines[i+1]-1 : lastLine;                    
                    Marshal.ThrowExceptionForHR(lines.GetLengthOfLine(ts.iEndLine, out ts.iEndIndex));
                    ts.iEndIndex++;

                    DropDownTypes.Add(new ComboMember(_indexes[i], 1, DROPDOWNFONTATTR.FONTATTR_PLAIN, ts));
                }
            }

            return changed;
        }

19 View Source File : AnkhCommandService.cs
License : Apache License 2.0
Project Creator : AmpScm

public bool PostExecCommand(CommandID command, object args, CommandPrompt prompt)
        {
            if (command == null)
                throw new ArgumentNullException("command");

            lock (_delayTasks)
            {
                if (_delayed)
                {
                    _delayTasks.Add(
                        delegate
                        {
                            PerformPost(command, prompt, args);
                        });

                    return true;
                }
                else if (PerformPost(command, prompt, args))
                {
                    for (int i = 0; i < _delayedCommands.Count; i++)
                    {
                        if (!PerformPost(new CommandID(AnkhId.CommandSetGuid, _delayedCommands[i]), CommandPrompt.DoDefault, null))
                        {
                            _delayedCommands.RemoveRange(0, i);
                            return true;
                        }
                    }
                    _delayedCommands.Clear();
                    return true;
                }
                else
                    return false;
            }
        }

19 View Source File : ConsoleScript.cs
License : GNU General Public License v3.0
Project Creator : AndrasMumm

void TrimExcessLogs()
        {
            if (!restrictLogCount)
            {
                return;
            }

            var amountToRemove = logs.Count - maxLogCount;

            if (amountToRemove <= 0)
            {
                return;
            }

            logs.RemoveRange(0, amountToRemove);
        }

19 View Source File : SpectatingController.cs
License : MIT License
Project Creator : andruzzzhka

private void PacketReceived(NetIncomingMessage msg)
        {
            if (Config.Instance.SpectatorMode && !Client.Instance.inRadioMode && _currentScene == 1)
            {
                msg.Position = 0;
                CommandType commandType = (CommandType)msg.ReadByte();
                if (commandType == CommandType.GetPlayerUpdates)
                {
                    int playersCount = msg.ReadInt32();

                    for (int j = 0; j < playersCount; j++)
                    {
                        try
                        {
                            ulong playerId = msg.ReadUInt64();
                            byte packetsCount = msg.ReadByte();

                            ReplayData replay;

                            if(playerUpdates.TryGetValue(playerId, out replay))
                            {
                                if(replay.playerInfo == null)
                                {
                                    if (InGameOnlineController.Instance.players.TryGetValue(playerId, out OnlinePlayerController playerController))
                                    {
                                        replay.playerInfo = playerController.playerInfo;
                                    }
                                }

                                for (int k = 0; k < packetsCount; k++)
                                {
                                    PlayerUpdate player = new PlayerUpdate(msg);

                                    replay.updates.Add(player);
                                }

                                byte hitCount = msg.ReadByte();

                                for (int i = 0; i < hitCount; i++)
                                {
                                    HitData hit = new HitData(msg);
                                    if (!replay.hits.ContainsKey(hit.objectId))
                                        replay.hits.Add(hit.objectId, hit);
                                }

                                if (replay.updates.Count > 450)
                                {
                                    replay.updates.RemoveRange(0, replay.updates.Count - 450);
                                }
                            }
                            else
                            {
                                replay = new ReplayData();

                                if(InGameOnlineController.Instance.players.TryGetValue(playerId, out OnlinePlayerController playerController))
                                {
                                    replay.playerInfo = playerController.playerInfo;
                                }

                                if(replay.playerInfo == null)
                                {
                                    InGameOnlineController.Instance.sendFullUpdate = true;
                                    continue;
                                }

                                for (int k = 0; k < packetsCount; k++)
                                {
                                    PlayerUpdate player = new PlayerUpdate(msg);

                                    replay.updates.Add(player);
                                }

                                byte hitCount = msg.ReadByte();

                                for (int i = 0; i < hitCount; i++)
                                {
                                    HitData hit = new HitData(msg);
                                    if(!replay.hits.ContainsKey(hit.objectId))
                                        replay.hits.Add(hit.objectId, hit);
                                }

                                playerUpdates.Add(playerId, replay);
                            }                            
                        }
                        catch (Exception e)
                        {
#if DEBUG
                            Plugin.log.Critical($"Unable to parse PlayerInfo! Excpetion: {e}");
#endif
                        }
                    }
                }
            }
        }

19 View Source File : MultiplayerResultsViewController.cs
License : MIT License
Project Creator : andruzzzhka

public void UpdateLeaderboard()
        {
            var scores = InGameOnlineController.Instance.playerScores;

            if (scores == null)
                return;

            scores.Sort();

            if (scores.Count < _scoreData.Count)
            {
                _scoreData.RemoveRange(scores.Count, _scoreData.Count - scores.Count);
            }

            for (int i = 0; i < scores.Count; i++)
            {
                if (_scoreData.Count <= i)
                {
                    _scoreData.Add(new LeaderboardTableView.ScoreData((int)scores[i].score, scores[i].name, i + 1, false));
                    Plugin.log.Debug("Added new ScoreData!");
                }
                else
                {
                    _scoreData[i].SetProperty("playerName", scores[i].name);
                    _scoreData[i].SetProperty("score", (int)scores[i].score);
                    _scoreData[i].SetProperty("rank", i + 1);
                }
            }

            leaderboardTableView.SetScores(_scoreData, -1);

        }

19 View Source File : PlayerManagementViewController.cs
License : MIT License
Project Creator : andruzzzhka

public void UpdatePlayerList(RoomState state)
        {
            
            var playersDict = InGameOnlineController.Instance.players;
                
            if (playersDict.Count != players.Count)
            {
                while(playersDict.Count > players.Count)
                {
                    players.Add(new PlayerListObject(null, this));
                }
                if (playersDict.Count < players.Count)
                    players.RemoveRange(playersDict.Count, players.Count - playersDict.Count);

                playersList.tableView.ReloadData();
            }

            int index = 0;
            foreach(var playerPair in playersDict)
            {
                (players[index] as PlayerListObject).Update(playerPair.Value.playerInfo, state);
                index++;
            }            
        }

19 View Source File : PlayingNowViewController.cs
License : MIT License
Project Creator : andruzzzhka

public void UpdateLeaderboard()
        {
            var scores = InGameOnlineController.Instance.playerScores;

            if (scores == null)
                return;

            if (scores.Count < _scoreData.Count)
            {
                _scoreData.RemoveRange(scores.Count, _scoreData.Count - scores.Count);
            }

            scores.Sort();

            for (int i = 0; i < scores.Count; i++)
            {
                if (_scoreData.Count <= i)
                {
                    _scoreData.Add(new LeaderboardTableView.ScoreData((int)scores[i].score, scores[i].name, i + 1, false));
                }
                else
                {
                    _scoreData[i].SetProperty("playerName", scores[i].name);
                    _scoreData[i].SetProperty("score", (int)scores[i].score);
                    _scoreData[i].SetProperty("rank", i + 1);
                }
            }

            leaderboardTableView.SetScores(_scoreData, -1);

        }

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

public void UpdatePlayerInfo(NetIncomingMessage msg)
        {
            if(msg.ReadByte() == 0)
            {
                playerInfo.updateInfo = new PlayerUpdate(msg);
                byte hitCount = msg.ReadByte();

                for(int i = 0; i < hitCount; i++)
                {
                    playerInfo.hitsLastUpdate.Add(new HitData(msg));
                }
                
                lastUpdateIsFull = false;
            }
            else
            {
                playerInfo = new PlayerInfo(msg);
                lastUpdateIsFull = true;
            }

            if (_joinedRoom != null && _joinedRoom.spectatorInRoom)
            {
                playerUpdateHistory.Enqueue(playerInfo.updateInfo);

                while (playerUpdateHistory.Count >= 16)
                {
                    playerUpdateHistory.Dequeue();
                }

                playerHitsHistory.AddRange(playerInfo.hitsLastUpdate);

                if (playerHitsHistory.Count >= 32)
                {
                    playerHitsHistory.RemoveRange(0, playerHitsHistory.Count - 32);
                }
            }
        }

19 View Source File : LavalinkQueue.cs
License : MIT License
Project Creator : angelobreuer

public void RemoveRange(int index, int count)
    {
        lock (_syncRoot)
        {
            _list.RemoveRange(index, count);
        }
    }

19 View Source File : TimelineTesterView.xaml.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

private async void TimelineTesterView_Loaded(
            object sender,
            RoutedEventArgs e)
        {
            if (!File.Exists(this.LogFile))
            {
                return;
            }

            var list = new List<TestLog>();

            await Task.Run(() =>
            {
                var seq = 1L;
                using (var sr = new StreamReader(this.LogFile, new UTF8Encoding(false)))
                {
                    while (!sr.EndOfStream)
                    {
                        var logline = sr.ReadLine();

                        if (string.IsNullOrEmpty(logline) ||
                            logline.StartsWith("#") ||
                            logline.StartsWith("//"))
                        {
                            continue;
                        }

                        var log = new TestLog(logline)
                        {
                            Seq = seq++
                        };

                        list.Add(log);
                    }
                }

                if (!list.Any())
                {
                    return;
                }

                // 頭出しをする
                var combatStart = list.FirstOrDefault(x => x.Log.Contains("戦闘開始"));
                if (combatStart != null)
                {
                    list.RemoveRange(0, list.IndexOf(combatStart));
                }
                else
                {
                    // ダミー戦闘開始5秒前を挿入する
                    var head = list.First();
                    list.Insert(0, new TestLog(
                        $"[{head.Timestamp.AddSeconds(-5):HH:mm:ss.fff}] 00:0039:戦闘開始まで5秒! [DUMMY]"));

                    // xivlog flush を挿入する
                    var last = list.Last();
                    list.Add(new TestLog(
                        $"[{last.Timestamp.AddSeconds(1):HH:mm:ss.fff}] /xivlog flush"));
                }

                var first = list.First();

                foreach (var log in list)
                {
                    if (log.Timestamp >= first.Timestamp)
                    {
                        log.Time = log.Timestamp - first.Timestamp;
                    }
                    else
                    {
                        log.Time = log.Timestamp.AddDays(1) - first.Timestamp;
                    }
                }
            });

            this.Logs.Clear();
            this.Logs.AddRange(list);
        }

19 View Source File : TriggerTesterView.xaml.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

private async void LoadLog()
        {
            if (!File.Exists(this.LogFile))
            {
                return;
            }

            var list = new List<TestLog>();

            await Task.Run(() =>
            {
                var ignores = XIVPluginHelper.IgnoreLogKeywords;

                var seq = 1L;
                using (var sr = new StreamReader(this.LogFile, new UTF8Encoding(false)))
                {
                    while (!sr.EndOfStream)
                    {
                        var logline = sr.ReadLine();

                        if (string.IsNullOrEmpty(logline) ||
                            logline.StartsWith("#") ||
                            logline.StartsWith("//"))
                        {
                            continue;
                        }

                        if (ignores.Any(x => logline.Contains(x)))
                        {
                            continue;
                        }

                        var log = new TestLog(logline)
                        {
                            Seq = seq++
                        };

                        list.Add(log);
                    }
                }

                if (!list.Any())
                {
                    return;
                }

                // 頭出しをする
                var combatStart = list.FirstOrDefault(x => x.Log.Contains("戦闘開始"));
                if (combatStart != null)
                {
                    list.RemoveRange(0, list.IndexOf(combatStart));
                }

                var first = list.First();

                foreach (var log in list)
                {
                    if (log.Timestamp >= first.Timestamp)
                    {
                        log.Time = log.Timestamp - first.Timestamp;
                    }
                    else
                    {
                        log.Time = log.Timestamp.AddDays(1) - first.Timestamp;
                    }
                }
            });

            this.Logs.Clear();
            this.Logs.AddRange(list);
        }

19 View Source File : AppLog.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public static void AppendLog(
            string dateTime,
            string level,
            string callsite,
            string message)
        {
            DateTime d;
            DateTime.TryParse(dateTime, out d);

            var entry = new AppLogEntry()
            {
                DateTime = d,
                Level = level,
                CallSite = callsite,
                Message = message,
            };

            lock (AppLog.locker)
            {
                if (AppLog.logBuffer.Count > LogBufferSize)
                {
                    AppLog.logBuffer.RemoveRange(0, LogBufferMargin);
                }

                AppLog.logBuffer.Add(entry);
            }

            WPFHelper.BeginInvoke(() =>
                AppLog.OnAppendedLog(new AppendedLogEventArgs(entry)));
        }

19 View Source File : BinaryMappingHelpers.cs
License : Apache License 2.0
Project Creator : AntonioDePau

public static List<replacedem> CreateOrResize<replacedem>(this List<replacedem> list, int count)
            where replacedem : new()
        {
            list = list ?? new List<replacedem>();
            var difference = list.Count - count;
            if (difference < 0)
            {
                list.AddRange(Enumerable.Range(0, -difference).Select(x => new replacedem()));
            }
            else if (difference > 0)
            {
                list.RemoveRange(count, difference);
            }

            return list;
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : anydream

private static List<string> ParseDependFiles(string input)
		{
			input = input.Replace("\r", null);

			List<string> output = new List<string>();
			StringBuilder sb = new StringBuilder();

			void AddOutput(string s)
			{
				if (s.Length > 0)
					output.Add(s);
			}

			for (int i = 0, sz = input.Length; i < sz; ++i)
			{
				char ch = input[i];
				if (ch == '\\' && i + 1 < sz)
				{
					char chNext = input[i + 1];
					if (chNext == '\\' ||
						chNext == ' ')
					{
						sb.Append(chNext);
						++i;
						continue;
					}
					else if (chNext == '\n')
					{
						AddOutput(sb.ToString());
						sb.Clear();
						++i;
						continue;
					}
				}
				else if (ch == '\n' || ch == ' ')
				{
					AddOutput(sb.ToString());
					sb.Clear();
					continue;
				}
				sb.Append(ch);
			}

			if (sb.Length > 0)
				AddOutput(sb.ToString());

			output.RemoveRange(0, 2);
			return output;
		}

19 View Source File : ChatChannel.cs
License : MIT License
Project Creator : ArcturusZhang

public void TruncateMessages()
        {
            if (this.MessageLimit <= 0 || this.Messages.Count <= this.MessageLimit)
            {
                return;
            }

            int excessCount = this.Messages.Count - this.MessageLimit;
            this.Senders.RemoveRange(0, excessCount);
            this.Messages.RemoveRange(0, excessCount);
        }

19 View Source File : StructureLog.cs
License : MIT License
Project Creator : ark-mod

[System.Diagnostics.Conditional("STRUCTURELOG")]
        public void Add<TValueType>(long start, int length, string name)
        {
            _offsetIdLast++;
            if (_offsets.Count > _maxHistory)
            {
                _offsets.RemoveRange(0, _offsets.Count - _maxHistory + 1);
                var of = _offsets.FirstOrDefault();
                if (of != default)
                {
                    var i = 0;
                    while (_stackLog.Count >= i + 1)
                    {
                        var sl = _stackLog[i];
                        if (!sl.ToId.HasValue)
                        {
                            i++;
                            continue;
                        }
                        if (sl.ToId.Value < of.id) _stackLog.Remove(sl);
                        else break;
                    }
                }
            }
            _offsets.Add((start, length, typeof(TValueType), name, _offsetIdLast));
        }

19 View Source File : HomePage.axaml.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

public void UpdateRecentFiles()
        {
            RecentFiles = RecentFile.GetRecentFiles().ToList();

            if (RecentFilesGrids == null)
            {
                RecentFilesGrids = new List<Grid>(RecentFiles.Count);
                UpdateGrid = new List<Action<string, RecentFile>>();
            }

            if (RecentFilesGrids.Count > RecentFiles.Count)
            {
                this.FindControl<UniformGrid>("RecentFilesGrid").Children.RemoveRange(RecentFiles.Count, RecentFilesGrids.Count - RecentFiles.Count);
                RecentFilesGrids.RemoveRange(RecentFiles.Count, RecentFilesGrids.Count - RecentFiles.Count);
                UpdateGrid.RemoveRange(RecentFiles.Count, UpdateGrid.Count - RecentFiles.Count);
            }

            for (int i = 0; i < RecentFiles.Count; i++)
            {
                if (i > RecentFilesGrids.Count - 1)
                {

                    Grid itemGrid = new Grid() { Height = 102, Margin = new Thickness(0, 0, 5, 5), Background = Brushes.Transparent };
                    itemGrid.ColumnDefinitions.Add(new ColumnDefinition(97, GridUnitType.Pixel));
                    itemGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                    itemGrid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));

                    StackPanel namePanel = new StackPanel() { Margin = new Thickness(5, 0, 5, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                    Grid.SetColumn(namePanel, 1);
                    itemGrid.Children.Add(namePanel);

                    TrimmedTextBox2 nameBlock;
                    TrimmedTextBox2 pathBlock;
                    TrimmedTextBox2 dateBlock;

                    {
                        nameBlock = new TrimmedTextBox2() { Text = Path.GetFileName(RecentFiles[i].Item2.FilePath), FontSize = 16, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                        AvaloniaBugFixes.SetToolTip(nameBlock, new TextBlock() { Text = RecentFiles[i].Item2.FilePath, TextWrapping = TextWrapping.NoWrap });
                        namePanel.Children.Add(nameBlock);
                    }

                    {
                        pathBlock = new TrimmedTextBox2() { Text = Path.GetDirectoryName(RecentFiles[i].Item2.FilePath), Foreground = new SolidColorBrush(Color.FromRgb(102, 102, 102)), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, FontSize = 14, Margin = new Thickness(0, 0, 0, 5) };
                        AvaloniaBugFixes.SetToolTip(pathBlock, new TextBlock() { Text = RecentFiles[i].Item2.FilePath, TextWrapping = TextWrapping.NoWrap });
                        namePanel.Children.Add(pathBlock);
                    }

                    string lastModified = new DateTime(RecentFiles[i].Item2.ModifiedDate).ToString("f");

                    {
                        dateBlock = new TrimmedTextBox2() { Text = lastModified, Foreground = new SolidColorBrush(Color.FromRgb(102, 102, 102)), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, FontSize = 12 };
                        AvaloniaBugFixes.SetToolTip(dateBlock, new TextBlock() { Text = lastModified, TextWrapping = TextWrapping.NoWrap });
                        namePanel.Children.Add(dateBlock);
                    }

                    Image img = new Image() { };

                    using (MemoryStream ms = new MemoryStream(RecentFiles[i].Item2.Preview))
                    {
                        img.Source = new Bitmap(ms);
                    }

                    itemGrid.Children.Add(new Border() { BorderBrush = Brushes.Black, BorderThickness = new Thickness(1), MaxWidth = 92, MaxHeight = 92, Margin = new Thickness(5, 0, 0, 0), HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, Child = new Viewbox { Child = img } });

                    StackPanel buttonsPanel = new StackPanel() { VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                    Grid.SetColumn(buttonsPanel, 2);
                    itemGrid.Children.Add(buttonsPanel);

                    Button deleteButton = new Button() { Foreground = Brushes.Black, Content = new DPIAwareBox(Icons.GetIcon16("TreeViewer.replacedets.Trash")) { Width = 16, Height = 16 }, Background = Brushes.Transparent, Padding = new Thickness(0), Width = 24, Height = 24, Margin = new Thickness(0, 0, 0, 2), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, IsVisible = false };
                    buttonsPanel.Children.Add(deleteButton);
                    AvaloniaBugFixes.SetToolTip(deleteButton, new TextBlock() { Text = "Delete", Foreground = Brushes.Black });
                    deleteButton.Clreplacedes.Add("SideBarButton");

                    itemGrid.PointerEnter += (s, e) =>
                    {
                        deleteButton.IsVisible = true;
                        itemGrid.Background = new SolidColorBrush(Color.FromRgb(210, 210, 210));
                    };

                    itemGrid.PointerLeave += (s, e) =>
                    {
                        deleteButton.IsVisible = false;
                        itemGrid.Background = Brushes.Transparent;
                    };

                    itemGrid.PointerPressed += (s, e) =>
                    {
                        itemGrid.Background = new SolidColorBrush(Color.FromRgb(177, 177, 177));
                    };

                    string treeFile = RecentFiles[i].Item2.FilePath;

                    itemGrid.PointerReleased += async (s, e) =>
                    {
                        itemGrid.Background = new SolidColorBrush(Color.FromRgb(210, 210, 210));

                        Point pos = e.GetCurrentPoint(itemGrid).Position;

                        if (pos.X >= 0 && pos.Y >= 0 && pos.X <= itemGrid.Bounds.Width && pos.Y <= itemGrid.Bounds.Height)
                        {
                            await this.FindAncestorOfType<MainWindow>().LoadFile(treeFile, false);
                        }
                    };

                    string fileToDelete = RecentFiles[i].Item1;

                    deleteButton.Click += async (s, e) =>
                    {
                        try
                        {
                            File.Delete(fileToDelete);

                            int index = RecentFilesGrids.IndexOf(itemGrid);

                            RecentFilesGrids.RemoveAt(index);
                            UpdateGrid.RemoveAt(index);
                            this.FindControl<UniformGrid>("RecentFilesGrid").Children.RemoveAt(index);
                        }
                        catch (Exception ex)
                        {
                            await new MessageBox("Attention!", "An error occurred while deleting the files!\n" + ex.Message).ShowDialog2(this.FindAncestorOfType<Window>());
                        }
                    }; ;

                    RecentFilesGrids.Add(itemGrid);

                    UpdateGrid.Add((item1, item2) =>
                    {

                        nameBlock.Text = Path.GetFileName(item2.FilePath);
                        AvaloniaBugFixes.SetToolTip(nameBlock, new TextBlock() { Text = item2.FilePath, TextWrapping = TextWrapping.NoWrap });

                        pathBlock.Text = Path.GetDirectoryName(item2.FilePath);
                        AvaloniaBugFixes.SetToolTip(pathBlock, new TextBlock() { Text = item2.FilePath, TextWrapping = TextWrapping.NoWrap });

                        string lastModified = new DateTime(item2.ModifiedDate).ToString("f");
                        dateBlock.Text = lastModified;
                        AvaloniaBugFixes.SetToolTip(dateBlock, new TextBlock() { Text = lastModified, TextWrapping = TextWrapping.NoWrap });

                        using (MemoryStream ms = new MemoryStream(item2.Preview))
                        {
                            img.Source = new Bitmap(ms);
                        }

                        fileToDelete = item1;
                        treeFile = item2.FilePath;
                    });

                    this.FindControl<UniformGrid>("RecentFilesGrid").Children.Add(itemGrid);
                }
                else
                {
                    UpdateGrid[i](RecentFiles[i].Item1, RecentFiles[i].Item2);
                }
            }
        }

See More Examples