#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2008 Sascha Steinbiss <steinbiss@zbh.uni-hamburg.de>
# Copyright (c) 2008 Center for Bioinformatics, University of Hamburg
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

from gt.core import *
from gt.extended import *
from gt.annotationsketch import *
import sys
import re

if __name__ == "__main__":
    if len(sys.argv) != 2:
        sys.stderr.write("Usage: " + (sys.argv)[0] + " GFF3_file\n")
        sys.stderr.write("Show sequence ids contained in GFF3 annotation file.")
        sys.exit(1)

    in_stream = GFF3InStream((sys.argv)[1])
    feature_index = FeatureIndexMemory()
    feature_stream = FeatureStream(in_stream, feature_index)
    gn = feature_stream.next_tree()

  # fill feature index

    while gn:
        gn = feature_stream.next_tree()

    seqids = feature_index.get_seqids()
    for seqid in seqids:
        print(seqid)

{'repo_name': 'genometools/genometools', 'stars': '165', 'repo_language': 'C', 'file_name': 'TransProt12', 'mime_type': 'text/plain', 'hash': -5752217517088671990, 'source_dataset': 'data'}


; Names are based on
; http://nesdevwiki.org/index.php/NES_PPU
; http://nesdevwiki.org/index.php/2A03

; PPU registers
PPUCTRL     = $2000
NT_2000     = $00
NT_2400     = $01
NT_2800     = $02
NT_2C00     = $03
MSB_XSCROLL = $01
MSB_YSCROLL = $02
VRAM_RIGHT  = $00 ; writes/reads to PPUDATA increment PPUADDR
VRAM_ACROSS = $00
VRAM_DOWN   = $04 ; writes/reads to PPUDATA add 32 to PPUADDR
OBJ_0000    = $00
OBJ_1000    = $08
OBJ_8X8     = $00
OBJ_8X16    = $20
BG_0000     = $00
BG_1000     = $10
VBLANK_NMI  = $80

PPUMASK     = $2001
LIGHTGRAY   = $01
BG_OFF      = $00
BG_CLIP     = $08
BG_ON       = $0A
OBJ_OFF     = $00
OBJ_CLIP    = $10
OBJ_ON      = $14
INT_RED     = %00100000
INT_GREEN   = %01000000
INT_BLUE    = %10000000

PPUSTATUS      = $2002
SPR_OVERFLOW   = %00100000
SPR_HIT        = %01000000
VBLANK_STARTED = %10000000

OAMADDR   = $2003
OAMDATA   = $2004
PPUSCROLL = $2005
PPUADDR   = $2006
PPUDATA   = $2007

; Pulse channel registers
SQ1_VOL   = $4000
SQ1_SWEEP = $4001
SQ1_LO    = $4002
SQ1_HI    = $4003
SQ2_VOL   = $4004
SQ2_SWEEP = $4005
SQ2_LO    = $4006
SQ2_HI    = $4007

SQ_1_8      = $00  ; 1/8 duty (sounds sharp)
SQ_1_4      = $40  ; 1/4 duty (sounds rich)
SQ_1_2      = $80  ; 1/2 duty (sounds hollow)
SQ_3_4      = $C0  ; 3/4 duty (sounds like 1/4)
SQ_HOLD     = $20  ; halt length counter
SQ_CONSTVOL = $10  ; 0: envelope decays from 15 to 0; 1: constant volume
SWEEP_OFF   = $08

; Triangle channel registers
TRI_LINEAR = $4008
TRI_LO     = $400A
TRI_HI     = $400B

TRI_HOLD = $80

; Noise channel registers
NOISE_VOL = $400C
NOISE_LO  = $400E
NOISE_HI  = $400F

NOISE_HOLD = SQ_HOLD
NOISE_CONSTVOL = SQ_CONSTVOL
NOISE_LOOP = $80

; DPCM registers
DMC_FREQ  = $4010
DMC_RAW   = $4011
DMC_START = $4012
DMC_LEN   = $4013

; OAM DMA unit register
; Writing $xx here causes 256 bytes to be copied from $xx00-$xxFF
; to OAMDATA
OAM_DMA = $4014
OAMDMA  = $4014

; Sound channel control and status register
SND_CHN       = $4015
CH_SQ1   = %00000001
CH_SQ2   = %00000010
CH_TRI   = %00000100
CH_NOISE = %00001000
CH_ALL   = %00001111  ; all tone generators, not dpcm
CH_DPCM  = %00010000

JOY1 = $4016
JOY2 = $4017
APUCTRL       = $4017
APUCTRL_5STEP = $80
APUCTRL_NOIRQ = $40

OAM_COLOR_0 =  %00000000
OAM_COLOR_1 =  %00000001
OAM_COLOR_2 =  %00000010
OAM_COLOR_3 =  %00000011
OAM_PRIORITY = %00100000
OAM_XFLIP    = %01000000
OAM_YFLIP    = %10000000

OAM_YPOS = $200
OAM_TILE = $201
OAM_ATTR = $202
OAM_XPOS = $203

KEY_RIGHT = %00000001
KEY_LEFT  = %00000010
KEY_DOWN  = %00000100
KEY_UP    = %00001000
KEY_START = %00010000
KEY_SELECT= %00100000
KEY_B     = %01000000
KEY_A     = %10000000
KEY_SNES_A = %10000000
KEY_SNES_X = %01000000
KEY_SNES_L = %00100000
KEY_SNES_R = %00010000

; and now macros ----------------------------------------------------------

.feature leading_dot_in_identifiers
.macpack generic
.macpack longbranch

; Meant to be an easy replacement for .repeat and .endrepeat
; when you're trying to save space. Uses a zeropage memory location
; instead of a register as a loop counter so as not to disturb any
; registers.
; Times - Number of times to loop ( may be a memory location )
; Free  - Free zeropage memory location to use
.macro .dj_loop Times, Free
  .scope
    DJ_Counter = Free
    lda Times
    sta Free
DJ_Label:
.endmacro
.macro .end_djl
  NextIndex:
    dec DJ_Counter
    jne DJ_Label
  .endscope
.endmacro

; These use increments (useless)
.macro .ij_loop Times, Free
  .scope
    DJ_Times = Times
    DJ_Counter = Free
    lda #0
    sta Free
DJ_Label:
.endmacro
.macro .end_ijl
  NextIndex:
    inc DJ_Counter
    lda DJ_Counter
    cmp Times
    jne DJ_Label
  .endscope
.endmacro

; swap using X
.macro swapx mema, memb
  ldx mema
  lda memb
  stx memb
  sta mema
.endmacro

; swap using Y
.macro swapy mema, memb
  ldy mema
  lda memb
  sty memb
  sta mema
.endmacro

; swap using just A + stack
.macro swapa mema, memb
  lda mema
  pha
  lda memb
  sta mema
  pla
  sta memb
.endmacro

; swap array,x and array,y
.macro swaparray list
  lda list,x
  pha
  lda list,y
  sta list,x
  pla
  sta list,y
.endmacro

; Imitation of z80's djnz opcode.
; Can be on A, X, Y, or a zeropage memory location
; Label - Label to jump to
; Reg   - Counter register to use: A,X,Y or memory location
.macro djnz Label, Reg
  .if (.match({Reg}, a))
    sub #1
  .elseif (.match({Reg}, x))
    dex
  .elseif (.match({Reg}, y))
    dey
  .else
    dec var
  .endif
  bne Label
.endmacro

; Working with X,Y is much more fun than working with PPU addresses
; give it an X and Y position, as well as a nametable number (0-3),
; and if you want to save the address to a 16-bit zeropage address
; ( big endian ) you can give an additional argument.
; NT - Nametable number (0-3)
; PX - X position in tiles
; PY - Y position in tiles
; Var - Variable to store address in (optional)
.macro PositionXY NT, PX, PY, Var
	.scope
		t0 = $2000 + (NT * 1024)	; Nametable data starts at $2000
		t1 = PX                 ; and each nametable is 1024 bytes in size
		t2 = PY * 32			; Nametable rows are 32 bytes large
		t3 = t0 + t1 + t2
        .ifblank Var        ; Are we going to be writing this directly to PPUADDR?
          lda #>t3
          sta $2006
          lda #<t3
          sta $2006
        .else               ; Are we going to be storing this to a pointer in zeropage instead?
          lda #>t3
          sta Var+0
          lda #<t3
          sta Var+1
        .endif
	.endscope
.endmacro

.macro .nyb InpA, InpB		; Makes a .byt storing two 4 bit values
	.byt ( InpA<<4 ) | InpB
.endmacro

.macro .raddr This          ; like .addr but for making "RTS trick" tables with
 .addr This-1
.endmacro

.macro neg
  eor #255
  add #1
.endmacro

.macro abs ; absolute value
.local @Skip
  bpl @Skip
  neg
@Skip:
.endmacro

.macro sex ; sign extend
.local @Skip
  ora #$7F
  bmi @Skip
  lda #0
@Skip:
.endmacro

.macro neg16 lo, hi
  sec             ;Ensure carry is set
  lda #0          ;Load constant zero
  sbc lo          ;... subtract the least significant byte
  sta lo          ;... and store the result
  lda #0          ;Load constant zero again
  sbc hi          ;... subtract the most significant byte
  sta hi          ;... and store the result
.endmacro

.macro neg16x lo, hi
  sec             ;Ensure carry is set
  lda #0          ;Load constant zero
  sbc lo,x        ;... subtract the least significant byte
  sta lo,x        ;... and store the result
  lda #0          ;Load constant zero again
  sbc hi,x        ;... subtract the most significant byte
  sta hi,x        ;... and store the result
.endmacro

.macro inc16 variable
.local @Skip
  inc variable+0
  bne @Skip
  inc variable+1
@Skip:
.endmacro

.macro dec16 variable
.local @Skip
  lda variable+0
  bne @Skip
  dec variable+1
@Skip:
  dec variable+0
.endmacro

.macro pushaxy
  pha
  txa
  pha
  tya
  pha
.endmacro

.macro pullaxy
  pla
  tay
  pla
  tax
  pla
.endmacro

.macro pushax
  pha
  txa
  pha
.endmacro

.macro pullax
  pla
  tax
  pla
.endmacro

.macro pushay
  pha
  tya
  pha
.endmacro

.macro pullay
  pla
  tay
  pla
.endmacro

.macro addcarry to
.local @Skip
  bcc @Skip
  inc to
@Skip:
.endmacro

.macro subcarry to
.local @Skip
  bcs @Skip
  dec to
@Skip:
.endmacro

.macro addcarryx to
.local @Skip
  bcc @Skip
  inc to,x
@Skip:
.endmacro

.macro subcarryx to
.local @Skip
  bcs @Skip
  dec to,x
@Skip:
.endmacro

.macro countdown counter
.local @Skip
  lda counter
  beq @Skip
    dec counter
@Skip:
.endmacro

; --- conditional return ---
.macro rtseq
.local @Skip
  bne @Skip
  rts
@Skip:
.endmacro

.macro rtsne
.local @Skip
  beq @Skip
  rts
@Skip:
.endmacro

.macro rtscc
.local @Skip
  bcs @Skip
  rts
@Skip:
.endmacro

.macro rtscs
.local @Skip
  bcc @Skip
  rts
@Skip:
.endmacro

.macro rtspl
.local @Skip
  bmi @Skip
  rts
@Skip:
.endmacro

.macro rtsmi
.local @Skip
  bpl @Skip
  rts
@Skip:
.endmacro

.macro unpack lo, hi
  pha
  and #15
  sta lo
  pla
  lsr
  lsr
  lsr
  lsr
  sta hi
.endmacro

.macro unpackx lo, hi
  pha
  and #15
  sta lo,x
  pla
  lsr
  lsr
  lsr
  lsr
  sta hi,x
.endmacro

.macro unpacky lo, hi
  pha
  and #15
  sta lo,y
  pla
  lsr
  lsr
  lsr
  lsr
  sta hi,y
.endmacro

.macro skip2
  .byt $2c ; BIT absolute
.endmacro

.macro asr ; Arithmetic shift left
  cmp #$80
  ror
.endmacro

.macro notcarry ; toggles carry
 rol
 eor #1
 ror
.endmacro

{'repo_name': 'NovaSquirrel/NovaTheSquirrel', 'stars': '104', 'repo_language': 'Assembly', 'file_name': 'novapuzzle sfx.s', 'mime_type': 'text/x-asm', 'hash': -405959943486281631, 'source_dataset': 'data'}


#!/Volumes/Stuff/Dropbox/Code/Crouton_public/python_clients/venv/bin/python

# -*- coding: utf-8 -*-
import re
import sys

from setuptools.command.easy_install import main

if __name__ == '__main__':
    sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
    sys.exit(main())

{'repo_name': 'edfungus/Crouton', 'stars': '255', 'repo_language': 'Python', 'file_name': 'crouton-frame.less', 'mime_type': 'text/plain', 'hash': 1426224389208576900, 'source_dataset': 'data'}


using System;
using System.Linq;
using System.Threading.Tasks;
using Cosmos.Core;
using Cosmos.Debug.Kernel;

namespace Cosmos.Core.Memory.Old
{
    // This class must be static, as for creating objects, we need the heap
    // this heap implementation it the very most basic one: no reentrancy, etc.
    // Interrupts are disabled when trying to allocate a new block of memory.
    public static unsafe class Heap
    {
        private static Debugger mDebugger = new Debugger("Core", "Memory");

        private static uint mEndOfRam;

        private static DataLookupTable* mLastTable;

        private static uint mLastEntryIndex = 0u;

        private static bool mInitialized = false;

        private static void DoInitialize(uint aEndOfRam)
        {
            mLastTable = null;
            mLastEntryIndex = 0u;
            mEndOfRam = aEndOfRam;
            //
        }

        internal static void EnsureIsInitialized()
        {
            if (!mInitialized)
            {
                mInitialized = true;
                DoInitialize((CPU.GetAmountOfRAM() - 1) * 1024 * 1024);
            }
        }

        private static void ClearMemory(void* aStartAddress, uint aLength)
        {
            //TODO: Move to memory. Internal access only...
            CPU.ZeroFill((uint)aStartAddress, aLength);
        }

        public static uint MemAlloc(uint aLength)
        {
            if (aLength == 0)
            {
                mDebugger.Send("    Request to retrieve block with size = 0 was halted!");
                while (true)
                {
                }
            }

            bool xInterruptsWereEnabled = CPU.DisableInterrupts();
            try
            {
                EnsureIsInitialized();

                DataLookupTable* xCurrentTable = GlobalSystemInfo.GlobalInformationTable->FirstDataLookupTable;
                DataLookupTable* xPreviousTable = null;
                uint xResult;

                if (mLastTable != null)
                {
                    xCurrentTable = mLastTable;
                }

                #region Loop through existing tables and see if we find a free spot
                while (xCurrentTable != null)
                {
                    if (ScanDataLookupTable(xCurrentTable, aLength, out xResult))
                    {
                        if (xResult < CPU.GetEndOfKernel())
                        {
                            Debugger.DoSend("Wrong handle returned!");
                            while (true)
                            {
                            }
                        }

                        return xResult;
                    }
                    mLastTable = xPreviousTable;
                    xPreviousTable = xCurrentTable;
                    xCurrentTable = xCurrentTable->Next;
                    mLastEntryIndex = 0;
                }
                #endregion Loop through existing tables and see if we find a free spot

                // no tables found, lets create a new one, and use that
                if (xPreviousTable == null)
                {
                    // this check should theoretically be unnecessary, but lets keep it, to do some double-checking.
                    Debugger.DoSend("No PreviousTable found!");
                    while (true)
                    {
                    }
                }

                var xLastItem = xPreviousTable->GetEntry(DataLookupTable.EntriesPerTable - 1);
                var xNextTablePointer = (DataLookupTable*)((uint)xLastItem->DataBlock + xLastItem->Size);
                // the memory hasn't been cleared yet, so lets do that now.
                ClearMemory(xNextTablePointer, GlobalSystemInfo.TotalDataLookupTableSize);
                xPreviousTable->Next = xNextTablePointer;
                xNextTablePointer->Previous = xPreviousTable;
                if (!ScanDataLookupTable(xNextTablePointer, aLength, out xResult))
                {
                    // Something seriously weird happened: we could create a new DataLookupTable (with new entries)
                    // but couldn't allocate a new handle from it.
                    Debugger.DoSend("    Something seriously weird happened: we could create a new DataLookupTable (with new entries), but couldn't allocate a new handle from it.");
                    while (true)
                    {
                    }
                }
                mLastTable = xNextTablePointer;
                mLastEntryIndex = 0;
                return xResult;
            }
            finally
            {
                if (xInterruptsWereEnabled)
                {
                    CPU.EnableInterrupts();
                }
                else
                {
                    //Debugger.DoSend("    Not enabling interrupts, because they weren't enabled yet!");
                }
            }
        }

        private static bool ScanDataLookupTable(DataLookupTable* aTable, uint aSize, out uint aHandle)
        {
            //Debugger.DoSend("At address:");
            //Debugger.DoSendNumber((uint)aTable);

            DataLookupEntry* xPreviousEntry = null;
            for (uint i = mLastEntryIndex; i < DataLookupTable.EntriesPerTable; i++)
            {
                var xCurrentEntry = aTable->GetEntry(i);
                //Debugger.DoSend($"Item.Size", xCurrentEntry->Size);
                //Debugger.DoSend($"Item.Refcount", xCurrentEntry->Refcount);
                if (xCurrentEntry->Size == 0)
                {
                    #region Found an uninitialized entry
                    // found an entry now. Let's set it
                    if (aTable->Next != null)
                    {
                        // once a handle is used, the size should be set. But at this point, it somehow got unset again.
                        // This should never occur.
                        Debugger.DoSend("Found an entry which has no size, but there is a followup DataLookupTable");
                        while (true)
                        {
                        }
                    }

                    void* xDataBlock;
                    //Debugger.DoSend("Now calculate datablock pointer");
                    // now we found ourself a free handle
                    if (i == 0)
                    {
                        //Debugger.DoSend("Using table end");
                        // we don't have a previous handle yet, so we take the FirstByteAfterTable field of the DataLookupTable
                        // note: we're explicitly initializing all blocks, as memory hasn't been cleared yet.
                        var xTableAddr = (uint)aTable;
                        //Debugger.DoSend("xTableAddr");
                        //Debugger.DoSendNumber(xTableAddr);
                        var xTotalTableSize = GlobalSystemInfo.TotalDataLookupTableSize;
                        //Debugger.DoSend("xTotalTableSize");
                        //Debugger.DoSendNumber(xTotalTableSize);
                        xDataBlock = (void*)(xTableAddr + xTotalTableSize);
                    }
                    else
                    {
                        //Debugger.DoSend("Using previous entry");
                        // We're not the very first handle being assigned, so calculate the start address using the previous block
                        xDataBlock = (void*)((uint)xPreviousEntry->DataBlock + xPreviousEntry->Size);
                    }

                    // make sure the memory is empty
                    ClearMemory(xDataBlock, aSize);
                    //Debugger.DoSend("Cleared memory");
                    xCurrentEntry->Size = aSize;
                    xCurrentEntry->DataBlock = xDataBlock;
                    xCurrentEntry->Refcount = 1;
                    aHandle = (uint)xCurrentEntry->DataBlock;
                    //Debugger.DoSend("Returning handle");
                    //Debugger.DoSendNumber(aHandle);
                    mLastEntryIndex = i;
                    #endregion Found an uninitialized entry
                    return true;
                }

                // Refcount == UInt32.MaxValue, it means that the block has been reclaimed, and can be reused now.
                if (xCurrentEntry->Refcount == UInt32.MaxValue)
                {
                    // we can reuse this entry if its Size >= aLength
                    if (xCurrentEntry->Size >= aSize)
                    {
                        // we can reuse this entry
                        xCurrentEntry->Refcount = 1;
                        aHandle = (uint)xCurrentEntry->DataBlock;
                        mLastEntryIndex = i;
                        return true;
                    }
                }
                xPreviousEntry = xCurrentEntry;
            }
            aHandle = 0;
            return false;
        }
    }
}

{'repo_name': 'CosmosOS/Cosmos', 'stars': '1879', 'repo_language': 'C#', 'file_name': 'BeepDemo.csproj', 'mime_type': 'text/plain', 'hash': 6340113574669067746, 'source_dataset': 'data'}


{ lib, bundlerApp, bundlerUpdateScript }:

bundlerApp {
  pname = "fpm";
  gemdir = ./.;
  exes = [ "fpm" ];

  passthru.updateScript = bundlerUpdateScript "fpm";

  meta = with lib; {
    description = "Tool to build packages for multiple platforms with ease";
    homepage    = "https://github.com/jordansissel/fpm";
    license     = licenses.mit;
    maintainers = with maintainers; [ manveru nicknovitski ];
    platforms   = platforms.unix;
  };
}

{'repo_name': 'NixOS/nixpkgs-channels', 'stars': '161', 'repo_language': 'Nix', 'file_name': 'default.nix', 'mime_type': 'text/plain', 'hash': -1795636920469872499, 'source_dataset': 'data'}


using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Telegram.Td.Api;
using Unigram.Collections;
using Unigram.Common;
using Unigram.Controls;
using Unigram.Navigation.Services;
using Unigram.Services;
using Unigram.ViewModels.Delegates;
using Unigram.Views.Folders;
using Unigram.Views.Popups;
using Windows.Foundation;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;

namespace Unigram.ViewModels
{
    public class ChatsViewModel : TLViewModelBase, IDelegable<IChatsDelegate>, IChatListDelegate
    {
        private readonly INotificationsService _notificationsService;

        private readonly Dictionary<long, bool> _deletedChats = new Dictionary<long, bool>();

        public IChatsDelegate Delegate { get; set; }

        public ChatsViewModel(IProtoService protoService, ICacheService cacheService, ISettingsService settingsService, IEventAggregator aggregator, INotificationsService notificationsService, ChatList chatList)
            : base(protoService, cacheService, settingsService, aggregator)
        {
            _notificationsService = notificationsService;

            Items = new ItemsCollection(protoService, aggregator, this, chatList);

            SearchFilters = new MvxObservableCollection<ISearchChatsFilter>();

            ChatPinCommand = new RelayCommand<Chat>(ChatPinExecute);
            ChatArchiveCommand = new RelayCommand<Chat>(ChatArchiveExecute);
            ChatMarkCommand = new RelayCommand<Chat>(ChatMarkExecute);
            ChatNotifyCommand = new RelayCommand<Chat>(ChatNotifyExecute);
            ChatDeleteCommand = new RelayCommand<Chat>(ChatDeleteExecute);
            ChatClearCommand = new RelayCommand<Chat>(ChatClearExecute);
            ChatSelectCommand = new RelayCommand<Chat>(ChatSelectExecute);

            ChatsMarkCommand = new RelayCommand(ChatsMarkExecute);
            ChatsNotifyCommand = new RelayCommand(ChatsNotifyExecute);
            ChatsArchiveCommand = new RelayCommand(ChatsArchiveExecute);
            ChatsDeleteCommand = new RelayCommand(ChatsDeleteExecute);
            ChatsClearCommand = new RelayCommand(ChatsClearExecute);

            FolderAddCommand = new RelayCommand<(int, Chat)>(FolderAddExecute);
            FolderRemoveCommand = new RelayCommand<(int, Chat)>(FolderRemoveExecute);
            FolderCreateCommand = new RelayCommand<Chat>(FolderCreateExecute);

            ClearRecentChatsCommand = new RelayCommand(ClearRecentChatsExecute);

            TopChatDeleteCommand = new RelayCommand<Chat>(TopChatDeleteExecute);

#if MOCKUP
            Items.AddRange(protoService.GetChats(null));
#endif

            SelectedItems = new MvxObservableCollection<Chat>();
        }

        #region Selection

        private long? _selectedItem;
        public long? SelectedItem
        {
            get { return _selectedItem; }
            set { Set(ref _selectedItem, value); }
        }

        private MvxObservableCollection<Chat> _selectedItems;
        public MvxObservableCollection<Chat> SelectedItems
        {
            get { return _selectedItems; }
            set { Set(ref _selectedItems, value); }
        }

        private ListViewSelectionMode _selectionMode = ListViewSelectionMode.None;
        public ListViewSelectionMode SelectionMode
        {
            get { return _selectionMode; }
            set { Set(ref _selectionMode, value); }
        }

        public int SelectedCount => _selectedItems.Count;

        public void SetSelectionMode(bool enabled)
        {
            Delegate?.SetSelectionMode(enabled);
        }

        public void SetSelectedItem(Chat chat)
        {
            if (SelectionMode != ListViewSelectionMode.Multiple)
            {
                Delegate?.Navigate(chat);
                //ChatsList.SelectedItem = chat;
            }
        }

        public void SetSelectedItems(IList<Chat> chats)
        {
            //if (ViewModel.Chats.SelectionMode == ListViewSelectionMode.Multiple)
            //{
            //    foreach (var item in chats)
            //    {
            //        if (!ChatsList.SelectedItems.Contains(item))
            //        {
            //            ChatsList.SelectedItems.Add(item);
            //        }
            //    }

            //    foreach (Chat item in ChatsList.SelectedItems)
            //    {
            //        if (!chats.Contains(item))
            //        {
            //            ChatsList.SelectedItems.Remove(item);
            //        }
            //    }
            //}
        }

        public void AddSelectedItem(Chat chat)
        {
            SelectedItems.Add(chat);
        }

        public void RemoveSelectedItem(Chat chat)
        {
            SelectedItems.Remove(chat);
        }

        public bool IsItemSelected(Chat chat)
        {
            return SelectedItems.Contains(chat);
        }

        #endregion

        public ItemsCollection Items { get; private set; }

        public bool IsLastSliceLoaded { get; set; }

        private SearchChatsCollection _search;
        public SearchChatsCollection Search
        {
            get
            {
                return _search;
            }
            set
            {
                Set(ref _search, value);
            }
        }

        public MvxObservableCollection<ISearchChatsFilter> SearchFilters { get; private set; }

        private TopChatsCollection _topChats;
        public TopChatsCollection TopChats
        {
            get
            {
                return _topChats;
            }
            set
            {
                Set(ref _topChats, value);
            }
        }

        #region Pin

        public RelayCommand<Chat> ChatPinCommand { get; }
        private void ChatPinExecute(Chat chat)
        {
            var position = chat.GetPosition(Items.ChatList);
            if (position == null)
            {
                return;
            }

            ProtoService.Send(new ToggleChatIsPinned(Items.ChatList, chat.Id, !position.IsPinned));
        }

        #endregion

        #region Archive

        public RelayCommand<Chat> ChatArchiveCommand { get; }
        private void ChatArchiveExecute(Chat chat)
        {
            var archived = chat.Positions.Any(x => x.List is ChatListArchive);
            if (archived)
            {
                ProtoService.Send(new AddChatToList(chat.Id, new ChatListMain()));
                return;
            }
            else
            {
                ProtoService.Send(new AddChatToList(chat.Id, new ChatListArchive()));
            }

            Delegate?.ShowChatsUndo(new[] { chat }, UndoType.Archive, items =>
            {
                var undo = items.FirstOrDefault();
                if (undo == null)
                {
                    return;
                }

                ProtoService.Send(new AddChatToList(chat.Id, new ChatListMain()));
            });
        }

        #endregion

        #region Multiple Archive

        public RelayCommand ChatsArchiveCommand { get; }
        private void ChatsArchiveExecute()
        {
            var chats = SelectedItems.ToList();

            foreach (var chat in chats)
            {
                ProtoService.Send(new AddChatToList(chat.Id, new ChatListArchive()));
            }

            Delegate?.ShowChatsUndo(chats, UndoType.Archive, items =>
            {
                foreach (var undo in items)
                {
                    ProtoService.Send(new AddChatToList(undo.Id, new ChatListMain()));
                }
            });

            Delegate?.SetSelectionMode(false);
            SelectedItems.Clear();
        }

        #endregion

        #region Mark

        public RelayCommand<Chat> ChatMarkCommand { get; }
        private void ChatMarkExecute(Chat chat)
        {
            if (chat.UnreadCount > 0)
            {
                ProtoService.Send(new ViewMessages(chat.Id, 0, new[] { chat.LastMessage.Id }, true));

                if (chat.UnreadMentionCount > 0)
                {
                    ProtoService.Send(new ReadAllChatMentions(chat.Id));
                }
            }
            else
            {
                ProtoService.Send(new ToggleChatIsMarkedAsUnread(chat.Id, !chat.IsMarkedAsUnread));
            }
        }

        #endregion

        #region Multiple Mark

        public RelayCommand ChatsMarkCommand { get; }
        private void ChatsMarkExecute()
        {
            var chats = SelectedItems.ToList();
            var unread = chats.Any(x => x.IsUnread());
            foreach (var chat in chats)
            {
                if (unread)
                {
                    if (chat.UnreadCount > 0)
                    {
                        ProtoService.Send(new ViewMessages(chat.Id, 0, new[] { chat.LastMessage.Id }, true));
                    }
                    else if (chat.IsMarkedAsUnread)
                    {
                        ProtoService.Send(new ToggleChatIsMarkedAsUnread(chat.Id, false));
                    }

                    if (chat.UnreadMentionCount > 0)
                    {
                        ProtoService.Send(new ReadAllChatMentions(chat.Id));
                    }
                }
                else if (chat.UnreadCount == 0 && !chat.IsMarkedAsUnread)
                {
                    ProtoService.Send(new ToggleChatIsMarkedAsUnread(chat.Id, true));
                }
            }

            Delegate?.SetSelectionMode(false);
            SelectedItems.Clear();
        }

        #endregion

        #region Notify

        public RelayCommand<Chat> ChatNotifyCommand { get; }
        private void ChatNotifyExecute(Chat chat)
        {
            _notificationsService.SetMuteFor(chat, CacheService.GetNotificationSettingsMuteFor(chat) > 0 ? 0 : 632053052);
        }

        #endregion

        #region Multiple Notify

        public RelayCommand ChatsNotifyCommand { get; }
        private void ChatsNotifyExecute()
        {
            var chats = SelectedItems.ToList();
            var muted = chats.Any(x => CacheService.GetNotificationSettingsMuteFor(x) > 0);

            foreach (var chat in chats)
            {
                if (chat.Type is ChatTypePrivate privata && privata.UserId == CacheService.Options.MyId)
                {
                    continue;
                }

                _notificationsService.SetMuteFor(chat, muted ? 0 : 632053052);
            }

            Delegate?.SetSelectionMode(false);
            SelectedItems.Clear();
        }

        #endregion

        #region Delete

        public RelayCommand<Chat> ChatDeleteCommand { get; }
        private async void ChatDeleteExecute(Chat chat)
        {
            var updated = await ProtoService.SendAsync(new GetChat(chat.Id)) as Chat ?? chat;
            var dialog = new DeleteChatPopup(ProtoService, updated, Items.ChatList, false);

            var confirm = await dialog.ShowQueuedAsync();
            if (confirm == ContentDialogResult.Primary)
            {
                var check = dialog.IsChecked == true;

                _deletedChats[chat.Id] = true;
                Items.Handle(chat.Id, 0);

                Delegate?.ShowChatsUndo(new[] { chat }, UndoType.Delete, items =>
                {
                    var undo = items.FirstOrDefault();
                    if (undo == null)
                    {
                        return;
                    }

                    _deletedChats.Remove(undo.Id);
                    Items.Handle(undo.Id, undo.Positions);
                }, async items =>
                {
                    var delete = items.FirstOrDefault();
                    if (delete == null)
                    {
                        return;
                    }

                    if (delete.Type is ChatTypeSecret secret)
                    {
                        await ProtoService.SendAsync(new CloseSecretChat(secret.SecretChatId));
                    }
                    else if (delete.Type is ChatTypeBasicGroup || delete.Type is ChatTypeSupergroup)
                    {
                        await ProtoService.SendAsync(new LeaveChat(delete.Id));
                    }

                    var user = CacheService.GetUser(delete);
                    if (user != null && user.Type is UserTypeRegular)
                    {
                        ProtoService.Send(new DeleteChatHistory(delete.Id, true, check));
                    }
                    else
                    {
                        if (delete.Type is ChatTypePrivate && check)
                        {
                            await ProtoService.SendAsync(new ToggleChatIsBlocked(delete.Id, true));
                        }

                        ProtoService.Send(new DeleteChatHistory(delete.Id, true, false));
                    }
                });
            }
        }

        #endregion

        #region Multiple Delete

        public RelayCommand ChatsDeleteCommand { get; }
        private async void ChatsDeleteExecute()
        {
            var chats = SelectedItems.ToList();

            var confirm = await MessagePopup.ShowAsync(Strings.Resources.AreYouSureDeleteFewChats, Locale.Declension("ChatsSelected", chats.Count), Strings.Resources.Delete, Strings.Resources.Cancel);
            if (confirm == ContentDialogResult.Primary)
            {
                foreach (var chat in chats)
                {
                    _deletedChats[chat.Id] = true;
                    Items.Handle(chat.Id, 0);
                }

                Delegate?.ShowChatsUndo(chats, UndoType.Delete, items =>
                {
                    foreach (var undo in items)
                    {
                        _deletedChats.Remove(undo.Id);
                        Items.Handle(undo.Id, undo.Positions);
                    }
                }, async items =>
                {
                    foreach (var delete in items)
                    {
                        if (delete.Type is ChatTypeSecret secret)
                        {
                            await ProtoService.SendAsync(new CloseSecretChat(secret.SecretChatId));
                        }
                        else if (delete.Type is ChatTypeBasicGroup || delete.Type is ChatTypeSupergroup)
                        {
                            await ProtoService.SendAsync(new LeaveChat(delete.Id));
                        }

                        ProtoService.Send(new DeleteChatHistory(delete.Id, true, false));
                    }
                });
            }

            Delegate?.SetSelectionMode(false);
            SelectedItems.Clear();
        }

        #endregion

        #region Clear

        public RelayCommand<Chat> ChatClearCommand { get; }
        private async void ChatClearExecute(Chat chat)
        {
            var updated = await ProtoService.SendAsync(new GetChat(chat.Id)) as Chat ?? chat;
            var dialog = new DeleteChatPopup(ProtoService, updated, Items.ChatList, true);

            var confirm = await dialog.ShowQueuedAsync();
            if (confirm == ContentDialogResult.Primary)
            {
                Delegate?.ShowChatsUndo(new[] { chat }, UndoType.Clear, items =>
                {
                    var undo = items.FirstOrDefault();
                    if (undo == null)
                    {
                        return;
                    }

                    _deletedChats.Remove(undo.Id);
                    Items.Handle(undo.Id, undo.Positions);
                }, items =>
                {
                    foreach (var delete in items)
                    {
                        ProtoService.Send(new DeleteChatHistory(delete.Id, false, dialog.IsChecked));
                    }
                });
            }
        }

        #endregion

        #region Multiple Clear

        public RelayCommand ChatsClearCommand { get; }
        private async void ChatsClearExecute()
        {
            var chats = SelectedItems.ToList();

            var confirm = await MessagePopup.ShowAsync(Strings.Resources.AreYouSureClearHistoryFewChats, Locale.Declension("ChatsSelected", chats.Count), Strings.Resources.ClearHistory, Strings.Resources.Cancel);
            if (confirm == ContentDialogResult.Primary)
            {
                Delegate?.ShowChatsUndo(chats, UndoType.Clear, items =>
                {
                    foreach (var undo in items)
                    {
                        _deletedChats.Remove(undo.Id);
                        Items.Handle(undo.Id, undo.Positions);
                    }
                }, items =>
                {
                    var clear = items.FirstOrDefault();
                    if (clear == null)
                    {
                        return;
                    }

                    ProtoService.Send(new DeleteChatHistory(clear.Id, false, false));
                });
            }

            Delegate?.SetSelectionMode(false);
            SelectedItems.Clear();
        }

        #endregion

        #region Select

        public RelayCommand<Chat> ChatSelectCommand { get; }
        private void ChatSelectExecute(Chat chat)
        {
            SelectedItems.ReplaceWith(new[] { chat });
            SelectionMode = ListViewSelectionMode.Multiple;

            //Delegate?.SetSelectedItems(_selectedItems);
        }

        #endregion

        #region Commands

        public RelayCommand ClearRecentChatsCommand { get; }
        private async void ClearRecentChatsExecute()
        {
            var confirm = await MessagePopup.ShowAsync(Strings.Resources.ClearSearch, Strings.Resources.AppName, Strings.Resources.OK, Strings.Resources.Cancel);
            if (confirm != ContentDialogResult.Primary)
            {
                return;
            }

            ProtoService.Send(new ClearRecentlyFoundChats());

            var items = Search;
            if (items != null && string.IsNullOrEmpty(items.Query))
            {
                items.Clear();
            }
        }

        public RelayCommand<Chat> TopChatDeleteCommand { get; }
        private async void TopChatDeleteExecute(Chat chat)
        {
            if (chat == null)
            {
                return;
            }

            var confirm = await MessagePopup.ShowAsync(string.Format(Strings.Resources.ChatHintsDelete, CacheService.GetTitle(chat)), Strings.Resources.AppName, Strings.Resources.OK, Strings.Resources.Cancel);
            if (confirm != ContentDialogResult.Primary)
            {
                return;
            }

            ProtoService.Send(new RemoveTopChat(new TopChatCategoryUsers(), chat.Id));
            TopChats.Remove(chat);
        }

        #endregion

        #region Folder add

        public RelayCommand<(int, Chat)> FolderAddCommand { get; }
        private async void FolderAddExecute((int ChatFilterId, Chat Chat) data)
        {
            var filter = await ProtoService.SendAsync(new GetChatFilter(data.ChatFilterId)) as ChatFilter;
            if (filter == null)
            {
                return;
            }

            var total = filter.IncludedChatIds.Count + filter.PinnedChatIds.Count + 1;
            if (total > 99)
            {
                await MessagePopup.ShowAsync(Strings.Resources.FilterAddToAlertFullText, Strings.Resources.FilterAddToAlertFullTitle, Strings.Resources.OK);
                return;
            }

            if (filter.IncludedChatIds.Contains(data.Chat.Id))
            {
                // Warn user about chat being already in the folder?
                return;
            }

            filter.ExcludedChatIds.Remove(data.Chat.Id);
            filter.IncludedChatIds.Add(data.Chat.Id);

            ProtoService.Send(new EditChatFilter(data.ChatFilterId, filter));
        }

        #endregion

        #region Folder remove

        public RelayCommand<(int, Chat)> FolderRemoveCommand { get; }
        private async void FolderRemoveExecute((int ChatFilterId, Chat Chat) data)
        {
            var filter = await ProtoService.SendAsync(new GetChatFilter(data.ChatFilterId)) as ChatFilter;
            if (filter == null)
            {
                return;
            }

            var total = filter.ExcludedChatIds.Count + 1;
            if (total > 99)
            {
                await MessagePopup.ShowAsync(Strings.Resources.FilterRemoveFromAlertFullText, Strings.Resources.AppName, Strings.Resources.OK);
                return;
            }

            if (filter.ExcludedChatIds.Contains(data.Chat.Id))
            {
                // Warn user about chat being already in the folder?
                return;
            }

            filter.IncludedChatIds.Remove(data.Chat.Id);
            filter.ExcludedChatIds.Add(data.Chat.Id);

            ProtoService.Send(new EditChatFilter(data.ChatFilterId, filter));
        }

        #endregion

        #region Folder create

        public RelayCommand<Chat> FolderCreateCommand { get; }
        private void FolderCreateExecute(Chat chat)
        {
            NavigationService.Navigate(typeof(FolderPage), state: new NavigationState { { "included_chat_id", chat.Id } });
        }

        #endregion

        public void SetFilter(ChatList chatList)
        {
            Aggregator.Unsubscribe(Items);
            Items = new ItemsCollection(ProtoService, Aggregator, this, chatList);
            RaisePropertyChanged(() => Items);
        }

        public class ItemsCollection : ObservableCollection<Chat>, ISupportIncrementalLoading,
            IHandle<UpdateChatDraftMessage>,
            IHandle<UpdateChatLastMessage>,
            IHandle<UpdateChatPosition>
        {
            private readonly IProtoService _protoService;
            private readonly IEventAggregator _aggregator;

            private readonly DisposableMutex _loadMoreLock = new DisposableMutex();

            private readonly ChatsViewModel _viewModel;

            private readonly ChatList _chatList;

            private bool _hasMoreItems = true;

            private long _internalChatId = 0;
            private long _internalOrder = long.MaxValue;

            private long _lastChatId;
            private long _lastOrder;

            public ChatList ChatList => _chatList;

            public ItemsCollection(IProtoService protoService, IEventAggregator aggregator, ChatsViewModel viewModel, ChatList chatList)
            {
                _protoService = protoService;
                _aggregator = aggregator;

                _viewModel = viewModel;

                _chatList = chatList;

#if MOCKUP
                _hasMoreItems = false;
#endif

                _ = LoadMoreItemsAsync(0);
            }

            public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
            {
                return AsyncInfo.Run(token => LoadMoreItemsAsync());
            }

            private async Task<LoadMoreItemsResult> LoadMoreItemsAsync()
            {
                using (await _loadMoreLock.WaitAsync())
                {
                    //var response = await _protoService.SendAsync(new GetChats(_chatList, _internalOrder, _internalChatId, 20));
                    var response = await _protoService.GetChatListAsync(_chatList, Count, 20);
                    if (response is Telegram.Td.Api.Chats chats)
                    {
                        foreach (var id in chats.ChatIds)
                        {
                            var chat = _protoService.GetChat(id);
                            var order = chat.GetOrder(_chatList);

                            if (chat != null && order != 0)
                            {
                                _internalChatId = chat.Id;
                                _internalOrder = order;

                                var next = NextIndexOf(chat, order);
                                if (next >= 0)
                                {
                                    Insert(next, chat);
                                }

                                _lastChatId = chat.Id;
                                _lastOrder = order;
                            }
                        }

                        _hasMoreItems = chats.ChatIds.Count > 0;
                        _aggregator.Subscribe(this);

                        _viewModel.Delegate?.SetSelectedItems(_viewModel.SelectedItems);

                        return new LoadMoreItemsResult { Count = (uint)chats.ChatIds.Count };
                    }

                    return new LoadMoreItemsResult { Count = 0 };
                }
            }

            public bool HasMoreItems => _hasMoreItems;

            #region Handle

            public void Handle(UpdateChatPosition update)
            {
                if (update.Position.List.ListEquals(_chatList))
                {
                    Handle(update.ChatId, update.Position.Order);
                }
            }

            public void Handle(UpdateChatLastMessage update)
            {
                Handle(update.ChatId, update.Positions, true);
            }

            public void Handle(UpdateChatDraftMessage update)
            {
                Handle(update.ChatId, update.Positions, true);
            }

            public void Handle(long chatId, IList<ChatPosition> positions, bool lastMessage = false)
            {
                var chat = GetChat(chatId);
                var order = chat.GetOrder(_chatList);

                Handle(chat, order, lastMessage);
            }

            public void Handle(long chatId, long order)
            {
                var chat = GetChat(chatId);
                if (chat != null)
                {
                    Handle(chat, order, false);
                }
            }

            private void Handle(Chat chat, long order, bool lastMessage)
            {
                if (_viewModel._deletedChats.ContainsKey(chat.Id))
                {
                    if (order == 0)
                    {
                        _viewModel._deletedChats.Remove(chat.Id);
                    }
                    else
                    {
                        return;
                    }
                }

                //var chat = GetChat(chatId);
                if (chat != null /*&& _chatList.ListEquals(chat.ChatList)*/)
                {
                    _viewModel.BeginOnUIThread(() => UpdateChatOrder(chat, order, lastMessage));
                }
            }

            private async void UpdateChatOrder(Chat chat, long order, bool lastMessage)
            {
                if (order > _lastOrder || (order == _lastOrder && chat.Id >= _lastChatId))
                {
                    using (await _loadMoreLock.WaitAsync())
                    {
                        var next = NextIndexOf(chat, order);
                        if (next >= 0)
                        {
                            Remove(chat);
                            Insert(Math.Min(Count, next), chat);

                            if (chat.Id == _viewModel._selectedItem)
                            {
                                _viewModel.Delegate?.SetSelectedItem(chat);
                            }
                            if (_viewModel.SelectedItems.Contains(chat))
                            {
                                _viewModel.Delegate?.SetSelectedItems(_viewModel._selectedItems);
                            }
                        }
                        else if (lastMessage)
                        {
                            _viewModel.Delegate?.UpdateChatLastMessage(chat);
                        }
                    }
                }
                else
                {
                    using (await _loadMoreLock.WaitAsync())
                    {
                        Remove(chat);
                    }

                    if (chat.Id == _viewModel._selectedItem)
                    {
                        _viewModel.Delegate?.SetSelectedItem(chat);
                    }
                    if (_viewModel.SelectedItems.Contains(chat))
                    {
                        _viewModel.SelectedItems.Remove(chat);
                        _viewModel.Delegate?.SetSelectedItems(_viewModel._selectedItems);
                    }

                    if (!_hasMoreItems)
                    {
                        await LoadMoreItemsAsync(0);
                    }
                }
            }

            private int NextIndexOf(Chat chat, long order)
            {
                var prev = -1;
                var next = 0;

                for (int i = 0; i < Count; i++)
                {
                    var item = this[i];
                    if (item.Id == chat.Id)
                    {
                        prev = i;
                        continue;
                    }

                    var itemOrder = item.GetOrder(_chatList);

                    if (order > itemOrder || order == itemOrder && chat.Id >= item.Id)
                    {
                        return next == prev ? -1 : next;
                    }

                    next++;
                }

                return Count;
            }

            private Chat GetChat(long chatId)
            {
                //if (_viewModels.ContainsKey(chatId))
                //{
                //    return _viewModels[chatId];
                //}
                //else
                //{
                //    var chat = ProtoService.GetChat(chatId);
                //    var item = _viewModels[chatId] = new ChatViewModel(ProtoService, chat);

                //    return item;
                //}

                return _protoService.GetChat(chatId);
            }

            #endregion
        }
    }

    public class SearchResult
    {
        public Chat Chat { get; set; }
        public User User { get; set; }

        public string Query { get; set; }

        public bool IsPublic { get; set; }

        public SearchResult(Chat chat, string query, bool pub)
        {
            Chat = chat;
            Query = query;
            IsPublic = pub;
        }

        public SearchResult(User user, string query, bool pub)
        {
            User = user;
            Query = query;
            IsPublic = pub;
        }
    }
}

namespace Telegram.Td.Api
{
    [Flags]
    public enum ChatListFilterFlags
    {
        IncludeContacts,
        IncludeNonContacts,
        IncludeGroups,
        IncludeChannels,
        IncludeBots,
        ExcludeMuted,
        ExcludeRead,
        ExcludeArchived
    }
}

{'repo_name': 'UnigramDev/Unigram', 'stars': '1077', 'repo_language': 'C#', 'file_name': 'TDLib-logs.md', 'mime_type': 'text/plain', 'hash': 1910934609073818348, 'source_dataset': 'data'}