text:
using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.IO;
using System.Diagnostics;
using System.Threading;

// This code is currently not used, but is useful if we want to compress other stream-based
// formats (basically this allows you to add compression onto any stream-based protocol.
// I have #ifdefed it out for now, since it is unused, but want to check it in so that we
// don't lose it.
#if false

#if !NETSTANDARD1_3

namespace Utilities
{
    /// This is basically a DeflateStream that supports seaking ON READ and does good buffering. To do this
    /// we compress in independent chunks of blockSize code:CompressedWriteStream.blockSize. The output stream
    /// looks like the following
    ///
    /// * DWORD Block Size (units that uncompressed data is compressed), Valid for the whole file
    /// * Block 1
    ///   * DWORD compressed blockSize (in bytes) of first Chunk
    ///   * compressed Data for first chunk
    /// * Block 2
    ///   * DWORD compressed blockSize (in bytes) of first Chunk
    ///   * compressed Data for first chunk
    /// * ...
    /// * Block LAST
    ///   * Negative DWORD compressed blockSize (in bytes) of first Chunk (indicates last chunk
    ///   * DWORD blockSize of uncompressed data;
    ///   * compressed Data for last chunk
    /// * BlockTable (array of QWORDS of file offsets to the begining of block 0 through N)
    /// * DWORD number of QWORDS entries in BlockTable.
    /// * DWORD number of uncompressed bytes in the last block
    ///
    /// This layout allows the reader to efficiently present an uncompressed view of the stream.
    ///
    class CompressedWriteStream : Stream, IDisposable
    {
#if false
        public static void CompressFile(string inputFilePath, string compressedFilePath)
        {
            using (Stream compressor = new CompressedWriteStream(compressedFilePath))
                Utilities.StreamUtilities.CopyFromFile(inputFilePath, compressor);
        }
#endif
        public CompressedWriteStream(string filePath) : this(File.Create(filePath)) { }
        public CompressedWriteStream(Stream outputStream) : this(outputStream, DefaultBlockSize, false) { }
        /// <summary>
        ///  Create a compressed stream. If blocksize is less than 1K you are likely to NOT achieve
        ///  good compression. Generally a block size of 8K - 256K is a good range (64K is the default and
        ///  generally there is less than .5% to be gained by making it bigger).
        /// </summary>
        public CompressedWriteStream(Stream outputStream, int blockSize, bool leaveOpen)
        {
            Debug.Assert(64 <= blockSize && blockSize <= 1024 * 1024 * 4);     // sane values.
            this.outputStream = outputStream;
            this.blockSize = blockSize;
            this.leaveOpen = leaveOpen;
            outputBuffer = new MemoryStream();
            compressor = new DeflateStream(outputBuffer, CompressionMode.Compress, true);
            compressedBlockSizes = new List<int>();
            WriteSignature(outputStream, Signature);
            WriteInt(outputStream, 1);                                // Version number;
            WriteInt(outputStream, blockSize);
            positionOfFirstBlock = outputStream.Position;
            spaceLeftInBlock = blockSize;
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            while (count > spaceLeftInBlock)
            {
                if (spaceLeftInBlock > 0)
                {
                    compressor.Write(buffer, offset, spaceLeftInBlock);
                    offset += spaceLeftInBlock;
                    count -= spaceLeftInBlock;
                    spaceLeftInBlock = 0;
                }
                FlushBlock(false);

                // Set up for the next block, create a new
                outputBuffer.SetLength(0);
                compressor = new DeflateStream(outputBuffer, CompressionMode.Compress, true);
                spaceLeftInBlock = blockSize;
            }
            compressor.Write(buffer, offset, count);
            spaceLeftInBlock -= count;
        }
        protected override void Dispose(bool disposing)
        {
            if (!disposing)
            {

                int lastBlockByteCount = blockSize - spaceLeftInBlock;
                // Write out the last block
                FlushBlock(true);

                // Write out the table of block sizes (to allow for efficient arbitrary seeking).
                CompressedWriteStream.LogLine("Writing offset table starting at 0x" + outputStream.Position.ToString("x"));
                long blockOffset = positionOfFirstBlock;
                foreach (int compressedBlockSize in compressedBlockSizes)
                {
                    WriteLong(outputStream, blockOffset);
                    blockOffset += (compressedBlockSize + 4);       // Add the total blockSize (with header) of the previous block
                }
                WriteLong(outputStream, blockOffset);

                CompressedWriteStream.LogLine("Writing offset table count " + (compressedBlockSizes.Count + 1) +
                    " uncompressed Left = 0x" + lastBlockByteCount.ToString("x"));
                // remember the count of the table.
                WriteInt(outputStream, compressedBlockSizes.Count + 1);
                // and the number of uncompressed bytes in the last block
                WriteInt(outputStream, lastBlockByteCount);
                if (!leaveOpen)
                    outputStream.Dispose();
            }
            base.Dispose(disposing);
        }

        public override bool CanRead { get { return false; } }
        public override bool CanSeek { get { return false; } }
        public override bool CanWrite { get { return true; } }

        // This is stored at the begining as ASCII to mark this stream
        public static readonly string Signature = "!BlockDeflateStream";

        // methods that are purposely not implemented
        public override long Length { get { throw new NotSupportedException(); } }
        public override long Position
        {
            get
            {
                throw new NotSupportedException();
            }
            set
            {
                throw new NotSupportedException();
            }
        }
        public override int Read(byte[] buffer, int offset, int count)
        {
            throw new NotSupportedException();
        }
        public override long Seek(long offset, SeekOrigin origin)
        {
            throw new NotSupportedException();
        }
        public override void SetLength(long value)
        {
            throw new NotSupportedException();
        }
        public override void Flush()
        {
            throw new NotSupportedException();
        }

#region private
        private void FlushBlock(bool lastBlock)
        {
            compressor.Dispose();
            int compressedBlockSize = (int)outputBuffer.Length;
            Debug.Assert(spaceLeftInBlock == 0 || lastBlock);
            CompressedWriteStream.LogLine("FlushBlock: lastBlock " + lastBlock + " compressedBlockSize = 0x" + compressedBlockSize.ToString("x") +
                " uncompresseSize=0x" + (blockSize - spaceLeftInBlock).ToString("x"));
            CompressedWriteStream.LogLine("Block header placed at filePosition=0x" + outputStream.Position.ToString("x"));
            // Write the block out prepended with its blockSize
            if (lastBlock)
            {
                WriteInt(outputStream, -compressedBlockSize);
                WriteInt(outputStream, blockSize - spaceLeftInBlock);   // write the uncompressed blockSize too.
            }
            else
            {
                compressedBlockSizes.Add(compressedBlockSize);
                WriteInt(outputStream, compressedBlockSize);
            }

            outputStream.Write(outputBuffer.GetBuffer(), 0, compressedBlockSize);
            // TODO remove outputStream.Write(new byte[compressedBlockSize], 0, compressedBlockSize);
            CompressedWriteStream.LogLine("After write, filePosition=0x" + outputStream.Position.ToString("x"));
        }
        static void WriteInt(Stream stream, int number)
        {
            for (int i = 0; i < 4; i++)
            {
                stream.WriteByte((byte)number);
                number >>= 8;
            }
        }
        static void WriteLong(Stream stream, long number)
        {
            for (int i = 0; i < 8; i++)
            {
                stream.WriteByte((byte)number);
                number >>= 8;
            }
        }
        private static void WriteSignature(Stream outputStream, string sig)
        {
            int i = 0;
            while (i < sig.Length)
            {
                outputStream.WriteByte((byte)sig[i]);
                i++;
            }
            // DWORD align it.
            while (i % 4 != 0)
            {
                outputStream.WriteByte(0);
                i++;
            }
        }
        [Conditional("DEBUG")]
        internal static void LogLine(string line)
        {
            // Debugger.Log(1, "Compressor", line + "\r\n");
        }

        const int DefaultBlockSize = 64 * 1024;

        Stream outputStream;            // Where the compressed bytes end up.
        int blockSize;
        bool leaveOpen;                 // do not close the underlying stream on close.
        long positionOfFirstBlock;
        List<int> compressedBlockSizes;

        // represents the current position in the file.
        DeflateStream compressor;       // Feed writes to this.
        MemoryStream outputBuffer;      // We need to buffer output to determine its blockSize
        int spaceLeftInBlock;

#endregion
    }

    class CompressedReadStream : Stream, IDisposable
    {
        public CompressedReadStream(string filePath) : this(File.OpenRead(filePath), false) { }
        /// <summary>
        /// Reads the stream of bytes written by code:CompressedWriteStream
        /// </summary>
        CompressedReadStream(Stream compressedData, bool leaveOpen)
        {
            if (!compressedData.CanRead || !compressedData.CanSeek)
                throw new ArgumentException("Stream must be readable and seekable", "compressedData");
            this.compressedData = compressedData;
            this.leaveOpen = leaveOpen;
            ReadSignature(compressedData, CompressedWriteStream.Signature);
            int versionNumber = ReadInt(compressedData);
            if (versionNumber != 1)
                throw new NotSupportedException("Version number Mismatch");
            maxUncompressedBlockSize = ReadInt(compressedData);
            Debug.Assert(64 <= maxUncompressedBlockSize && maxUncompressedBlockSize <= 1024 * 1024 * 4);      // check for sane values.
            nextCompressedBlockStartPosition = compressedData.Position;
            // uncompressedBlockStartPosition = 0;
            // uncompressedBlockSize = 0;
        }

#if false
        public static void DecompressFile(string compressedFilePath, string outputFilePath)
        {
            using (Stream decompressor = new CompressedWriteStream(compressedFilePath))
                Utilities.StreamUtilities.CopyToFile(decompressor, outputFilePath);
        }
#endif

        public override int Read(byte[] buffer, int offset, int count)
        {
            int totalBytesRead = 0;
            int bytesRead;
            while (count > (uncompressedDataLeft + totalBytesRead))
            {
                bytesRead = 0;
                if (uncompressedDataLeft > 0)
                    bytesRead += decompressor.Read(buffer, offset + totalBytesRead, uncompressedDataLeft);
                totalBytesRead += bytesRead;
                uncompressedDataLeft -= bytesRead;
                if (uncompressedDataLeft == 0)
                {
                    if (lastBlock)
                        return totalBytesRead;

                    FillBlock(uncompressedBlockStartPosition + uncompressedBlockSize, nextCompressedBlockStartPosition);
                }
            }
            bytesRead = decompressor.Read(buffer, offset + totalBytesRead, count - totalBytesRead);
            totalBytesRead += bytesRead;
            uncompressedDataLeft -= bytesRead;
            Debug.Assert(totalBytesRead <= count);
            return totalBytesRead;
        }
        public override long Seek(long offset, SeekOrigin origin)
        {
            if (origin == SeekOrigin.End)
                offset = offset + Length;
            else if (origin == SeekOrigin.Current)
                offset += Position;

            Position = offset;
            return offset;
        }
        public override long Length
        {
            get
            {
                InitBlockStarts();
                return uncompressedStreamLength;
            }
        }
        public override long Position
        {
            get
            {
                return uncompressedBlockStartPosition + (uncompressedBlockSize - uncompressedDataLeft);
            }
            set
            {
                long relativeOffset = value - Position;
                // Optimization: are we seeking a small forward offset
                if (0 <= relativeOffset && relativeOffset < uncompressedBlockStartPosition + uncompressedDataLeft)
                {
                    Skip((int)relativeOffset);
                    return;
                }

                int blockNumber = (int)(value / maxUncompressedBlockSize);
                long newUncompressedBlockStartPosition = blockNumber * maxUncompressedBlockSize;
                int remainder = (int)(value - newUncompressedBlockStartPosition);

                FillBlock(newUncompressedBlockStartPosition, GetCompressedPositionForBlock(blockNumber));
                Skip(remainder);
            }
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (!leaveOpen)
                    compressedData.Dispose();
                if (decompressor != null)
                    decompressor.Dispose();
            }
            base.Dispose(disposing);
        }

        public override bool CanRead { get { return true; } }
        public override bool CanSeek { get { return true; } }
        public override bool CanWrite { get { return false; } }

        // Methods purposefully left unimplemented since they apply to writable streams
        public override void SetLength(long value) { throw new NotSupportedException(); }
        public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); }
        public override void Flush() { throw new NotSupportedException(); }

#region private

        private void ReadSignature(Stream inputStream, string sig)
        {
            int i = 0;
            bool badSig = false;
            while (i < sig.Length)
            {
                if (inputStream.ReadByte() != sig[i])
                    badSig = true;
                i++;
            }
            // DWORD align it.
            while (i % 4 != 0)
            {
                if (inputStream.ReadByte() != 0)
                    badSig = true;
                i++;
            }
            if (badSig)
                throw new Exception("Stream signature mismatch.  Bad data format.");
        }
        /// <summary>
        /// Initializes the current block to point at the begining of the block (a block is the length as
        /// well as the data) that starts at the uncompressed location 'uncompressedBlockStart' which as the
        /// cooresponding compressed location 'compressedBlockStart'.
        /// </summary>
        private void FillBlock(long uncompressedBlockStart, long compressedBlockStart)
        {
            CompressedWriteStream.LogLine("FillBlock: uncompressedBlockStart 0x" + uncompressedBlockStart.ToString("x") +
                " compressedBlockStart 0x" + compressedBlockStart.ToString("x"));
            // Advance the uncompressed position
            uncompressedBlockStartPosition = uncompressedBlockStart;
            // and set the compressed stream to just past this block's data
            compressedData.Position = compressedBlockStart;

            // Read in the next block' blockSize (both compressed and uncompressed)
            uncompressedBlockSize = maxUncompressedBlockSize;
            int compressedBlockSize = ReadInt(compressedData);
            lastBlock = false;
            if (compressedBlockSize < 0)
            {
                compressedBlockSize = -compressedBlockSize;
                uncompressedBlockSize = ReadInt(compressedData);
                lastBlock = true;
            }
            Debug.Assert(compressedBlockSize <= maxUncompressedBlockSize * 3);       // I have never seen expansion more than 2X
            Debug.Assert(uncompressedBlockSize <= maxUncompressedBlockSize);
            if (decompressor != null)
                decompressor.Dispose();
            // Get next clump of data.
            decompressor = new DeflateStream(compressedData, CompressionMode.Decompress, true);

            // Set the uncompressed and compressed data pointers.
            uncompressedDataLeft = uncompressedBlockSize;
            nextCompressedBlockStartPosition = compressedData.Position + compressedBlockSize;

            CompressedWriteStream.LogLine("FillBlock compressedBlockSize = 0x" + compressedBlockSize.ToString("x") + " lastblock = " + lastBlock);
            CompressedWriteStream.LogLine("FillBlock: DONE: uncompressedDataLeft 0x" + uncompressedDataLeft.ToString("x") +
                " nextCompressedBlockStartPosition 0x" + nextCompressedBlockStartPosition.ToString("x"));
        }

        private long GetCompressedPositionForBlock(int blockNumber)
        {
            InitBlockStarts();

            int blockStartPos = blockNumber * sizeof(long);

            int low =
                 blockStarts[blockStartPos] +
                (blockStarts[blockStartPos + 1] << 8) +
                (blockStarts[blockStartPos + 2] << 16) +
                (blockStarts[blockStartPos + 3] << 24);
            int high =
                 blockStarts[blockStartPos + 4] +
                (blockStarts[blockStartPos + 5] << 8) +
                (blockStarts[blockStartPos + 6] << 16) +
                (blockStarts[blockStartPos + 7] << 24);

            return (long)(uint)low + (((long)high) << 32);
        }
        private bool Skip(int bytesToSkip)
        {
            int readSize = bytesToSkip;
            if (readSize > 1024)
                readSize = 1024;

            byte[] buffer = new byte[readSize];
            do
            {
                int count = Read(buffer, 0, readSize);
                if (count == 0)
                    return false;
                bytesToSkip -= count;

            } while (bytesToSkip > 0);
            return true;
        }
        private static int ReadInt(Stream compressedData)
        {
            int ret = compressedData.ReadByte() +
                (compressedData.ReadByte() << 8) +
                (compressedData.ReadByte() << 16) +
                (compressedData.ReadByte() << 24);
            return ret;
        }
        private void InitBlockStarts()
        {
            if (blockStarts != null)
                return;

            long origPosition = compressedData.Position;
            compressedData.Seek(-8, SeekOrigin.End);
            int numberOfBlocks = ReadInt(compressedData);
            int lastBlockLength = ReadInt(compressedData);
            Debug.Assert(lastBlockLength <= maxUncompressedBlockSize);
            Debug.Assert(numberOfBlocks <= compressedData.Length * 50 / maxUncompressedBlockSize);

            int blockStartLength = numberOfBlocks * sizeof(long);
            blockStarts = new byte[blockStartLength];
            compressedData.Seek(-blockStartLength - 8, SeekOrigin.End);
            compressedData.Read(blockStarts, 0, blockStartLength);
            compressedData.Position = origPosition;

            uncompressedStreamLength = (numberOfBlocks - 1) * (long)maxUncompressedBlockSize + lastBlockLength;
            Debug.Assert(GetCompressedPositionForBlock(0) == 0x1C);         // First block position is just skips past the header.
        }

        // fields associated with the stream as a whole.
        Stream compressedData;              // The original stream (assumed to be compressed data)
        int maxUncompressedBlockSize;       // The uncompressed blockSize of all blocks except the last (which might be shorter)
        byte[] blockStarts;                 // The blockStarts table, which allows random seeking (lazily inited)
        long uncompressedStreamLength;      // total blockSize of the uncompressed stream
        bool leaveOpen;

        // fields associated with the current position
        long uncompressedBlockStartPosition;    // uncompressed stream position begining of the current block
        long nextCompressedBlockStartPosition;  // compresed stream position for the NEXT block
        DeflateStream decompressor;         // The real stream2, we create a new one on each block.
        int uncompressedBlockSize;          // The logical blockSize of the current uncompressed block.
        int uncompressedDataLeft;           // The number of bytes left in the current uncompressed block.
        bool lastBlock;                     // True if this is the last block in the compressed stream.

        class StreamCacheBuffer : StreamCache
        {
            public StreamCacheBuffer(Stream baseStream)
                : base(1024 * 16)
            {
                m_baseStream = baseStream;
            }
            public override void Fill(StreamCache.DataBlock block)
            {
                lock (this)
                {
                    if (m_curPostion != block.m_position)
                        m_baseStream.Position = block.m_position;
                    block.m_len = m_baseStream.Read(block.m_data, 0, block.m_data.Length);
                    m_curPostion = block.m_position + block.m_len;
                }
            }
            public override long Length { get { return m_baseStream.Length; } }

#region private
            long m_curPostion;
            Stream m_baseStream;
#endregion
        }

        class StreamCacheDecompressor : StreamCache
        {
            public StreamCacheDecompressor(StreamCache input, int blockSize)
                : base(blockSize)
            {
                m_input = input;
                m_maxWorkers = 1;       // TODO
            }
            public override void Fill(StreamCache.DataBlock uncompressedBlockToReturn)
            {
                long compressedDataPos;
                int compressedDataSize;

                GetCompressedBlockInfo(uncompressedBlockToReturn.m_position, out compressedDataPos, out compressedDataSize);
                using (var compressedData = new StreamCacheStream(m_input, compressedDataPos, compressedDataSize))
                using (var uncompressedData = new DeflateStream(compressedData, CompressionMode.Decompress))
                    uncompressedBlockToReturn.m_len = uncompressedData.Read(uncompressedBlockToReturn.m_data, 0, uncompressedBlockToReturn.m_data.Length);

                uncompressedBlockToReturn.m_filled = true;
            }
            public override long Length { get { return m_input.Length; } }

            /// <summary>
            /// Given the desired uncompressed data position, return the file offset of the compressed data
            /// for that location, as well as the size of the compressed data.
            /// </summary>
            private void GetCompressedBlockInfo(long uncompressedPosition, out long compressedDataPos, out int compressedDataSize)
            {
                long compressedBlockPosition = 0;       // TODO FIX NOW

                compressedDataSize = ReadInt(compressedBlockPosition);
                compressedDataPos = compressedBlockPosition + 4;
            }
            /// <summary>
            /// Read in a single integer from the stream at 'position'. Because it might span blocks, this
            /// routine is not trivial.
            /// </summary>
            private int ReadInt(long position)
            {
                int ret = 0;
                DataBlock block = null;
                int positionInBlock = 0;
                for (int byteNum = 0; byteNum < 4; byteNum++)
                {
                    if (block == null)
                    {
                        block = m_input.GetBlock(position + byteNum);
                        if (block == null)
                            return 0;           // TODO throw exception instead?
                        positionInBlock = (int)(position - block.m_position);
                    }
                    ret = ret + (block.m_data[positionInBlock] << (byteNum * 8));
                    positionInBlock++;
                    if (positionInBlock >= block.m_len)
                        block = null;
                }
                return ret;
            }

            private StreamCache m_input;
        }

        abstract class StreamCache
        {
            protected StreamCache(int blockSize)
            {
                m_blocks = new DataBlock(blockSize, this, m_blocks);
                for (int i = 0; i < 3; i++)
                    m_blocks = new DataBlock(blockSize, this, m_blocks.m_next);
            }

            public abstract long Length { get; }
            public abstract void Fill(DataBlock block);
            public DataBlock GetBlock(long position)
            {
                DataBlock block;
                lock (this)
                {
                    block = FindBlockForPosition(position);
                    m_blocks = block;
                    block.m_refCount++; // TODO deal with overflow.
                    if (m_curWorkers == 0 && m_maxWorkers > 0)
                    {
                        m_curWorkers++;
                        ThreadPool.QueueUserWorkItem(new WaitCallback(this.DoAyncWork));
                    }
                }
                if (block.m_beingFilled)
                    block.Wait();
                else
                {
                    Fill(block);
                    block.m_filled = true;
                }
                return block;
            }

            /// <summary>
            /// This is what a worker thread does.  Basically it tries to decompress more data
            /// </summary>
            private void DoAyncWork(object state)
            {
                DataBlock block = null;
                for (; ; )
                {
                    lock (this)
                    {
                        block = GetDataBlockToFetch();
                        if (block == null)
                        {
                            --m_curWorkers;
                            return;
                        }
                        block.m_beingFilled = true;     // we are now filling the block, we own it now.
                    }
                    Fill(block);                        // Do the main work outside the lock.

                    block.m_beingFilled = false;        // we relinquish 'ownership' of the block
                    block.m_filled = true;              // and publish it as being filled.
                }
            }

            /// <summary>
            /// Find the data block for stream position 'position'.  If it is already been fetched great!
            /// If not return a block that can be filled in (but has NOT been).  You can tell because
            /// block.m_filled == false in that case.  It is also possible that the block is being filled
            /// so you have to wait on it (outside the StreamCache lock), before returning it.
            /// </summary>
            private DataBlock FindBlockForPosition(long position)
            {
                // We assume the StreamCache lock is held!
                DataBlock block = m_blocks;
                DataBlock freeBlock = null;
                for (; ; )
                {
                    if (block.m_position <= position && position < block.m_position + block.m_len)
                        return block;

                    if (freeBlock == null && block.m_refCount == 0 && !block.m_beingFilled)
                        freeBlock = block;

                    if (block == m_blocks)
                    {
                        // TODO, if we have not hit our concurrency limit, and it looks like we are streaming,
                        // add more workers, as the workers can't seem to keep up.
                        if (freeBlock == null)
                            freeBlock = m_blocks.m_next = new DataBlock(m_blocks.m_data.Length, this, m_blocks.m_next);

                        Debug.Assert(!block.m_beingFilled && block.m_refCount == 0);
                        block = freeBlock;
                        block.Clear(position);
                        break;
                    }
                }
                return block;
            }

            /// <summary>
            /// This routine returns a block that we have determined is useful to prefetch.   If we can't
            /// find a good block to prefetch, we return null.
            /// </summary>
            private DataBlock GetDataBlockToFetch()
            {
                // We assume the StreamCache lock is held!

                // Our heuristic is simple:  Just read ahead from the block at m_block
                DataBlock block = m_blocks.m_next;
                long positionToPrefetch = m_blocks.m_position + m_blocks.m_len;
                long length = Length;
                for (; ; )
                {
                    // If we have not already done the readahead
                    if (block.m_position != positionToPrefetch)
                    {
                        if (positionToPrefetch >= length)       // past end of stream
                            return null;

                        // It is not in use one way or the other
                        if (block.m_refCount == 0 && !block.m_beingFilled)
                        {
                            // Then go ahead and use it to prefetch.
                            block.Clear(positionToPrefetch);
                            return block;
                        }
                    }
                    else
                        positionToPrefetch = block.m_position + block.m_len;

                    if (block == m_blocks)
                        return null;
                }
            }

            public class DataBlock : IDisposable
            {
                internal DataBlock(int blockSize, StreamCache cache, DataBlock next)
                {
                    m_data = new byte[blockSize];
                    m_next = next;
                    m_cache = cache;

                }
                public void Dispose()
                {
                    lock (m_cache)
                    {
                        --m_refCount;
                    }
                }
                internal void Wait()
                {
                    while (!m_filled)
                        Thread.Sleep(1);
                }
                internal void Clear(long position)
                {
                    m_position = position;
                    m_filled = false;
                    m_len = m_data.Length;
                }

                internal byte[] m_data;                // data itself
                internal long m_position;              // position of data in the stream
                internal int m_len;                    // logical length of the data.

                internal DataBlock m_next;             // blocks are in a linked list in StreamCache
                internal volatile bool m_filled;       // set when finished filling.
                internal volatile bool m_beingFilled;  // set async thread claims block to fill.
                internal byte m_refCount;              // Incremented when GetBlock() is called, decremented on Dispose()
                internal StreamCache m_cache;          // cache that manages this block
            }

            DataBlock m_blocks;
            int m_curWorkers;
            protected int m_maxWorkers;
        }

        class StreamCacheStream : Stream
        {
            public StreamCacheStream(StreamCache cache, long start, long length)
            {
                m_start = start;
                m_length = length;
                m_cache = cache;
                Position = m_start;
            }
            public override bool CanRead { get { return true; } }
            public override bool CanSeek { get { return true; } }
            public override long Seek(long offset, SeekOrigin origin)
            {
                if (origin == SeekOrigin.Begin)
                    Position = offset;
                else if (origin == SeekOrigin.Current)
                    Position = Position + offset;
                else if (origin == SeekOrigin.End)
                    Position = Length + offset;
                return Position;
            }
            public override long Length
            {
                get { return m_length; }
            }
            public override long Position
            {
                get
                {
                    return m_curBlock.m_position + m_positionInBlock;
                }
                set
                {
                    long newPos = value;
                    if (newPos < m_start)
                        newPos = m_start;
                    else if (newPos >= m_start + m_length)
                    {
                        newPos = m_start + m_length;
                        m_curBlock = null;
                        return;
                    }
                    if (m_curBlock != null)
                        m_curBlock.Dispose();
                    m_curBlock = m_cache.GetBlock(newPos);
                    if (m_curBlock != null)
                    {
                        m_positionInBlock = (int)(newPos - m_curBlock.m_position);
                        m_blockLength = m_curBlock.m_len;
                        long lengthLeft = m_length - newPos;
                        if (lengthLeft < m_blockLength)
                            m_blockLength = (int)lengthLeft;
                    }
                    else
                    {
                        m_positionInBlock = 0;
                        m_blockLength = 0;
                    }
                }
            }
            public override int Read(byte[] buffer, int offset, int count)
            {
                if (m_curBlock == null)
                    return 0;
                int curOffset = offset;
                int countLeft = count;
                for (; ; )
                {
                    int bytesLeft = m_blockLength - m_positionInBlock;
                    if (bytesLeft == 0)
                    {
                        // Setting the position updates m_curBlock, m_PositionInBlock and m_blockLength
                        Position = m_curBlock.m_position + m_positionInBlock;
                        if (m_curBlock == null)     // end of stream?
                            break;
                    }
                    int copySize = Math.Min(bytesLeft, countLeft);
                    Array.Copy(m_curBlock.m_data, m_positionInBlock, buffer, curOffset, copySize);
                    m_positionInBlock += copySize;
                    curOffset += copySize;
                    countLeft -= copySize;
                    if (countLeft == 0)
                        break;
                }
                return count - countLeft;
            }
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    if (m_curBlock != null)
                    {
                        m_curBlock.Dispose();
                        m_curBlock = null;
                    }
                }
                base.Dispose(disposing);
            }

#region write methods (Not Implemented)
            public override bool CanWrite { get { return false; } }
            public override void SetLength(long value) { throw new NotImplementedException(); }
            public override void Write(byte[] buffer, int offset, int count) { throw new NotImplementedException(); }
            public override void Flush() { }
#endregion
#region private
            StreamCache.DataBlock m_curBlock;   // Current chunk of data
            int m_positionInBlock;
            int m_blockLength;                  // Logical end of the block
            long m_start;                       // logical start position of the stream in m_cache
            long m_length;                      // logical length of the stream in the m_cache
            StreamCache m_cache;                // represents all the data
#endregion
        }

#endregion
    }

#if UNIT_TESTS
    public static class CompressedStreamTests
    {
        public static void SizeTest(string inputFilePath)
        {
            Console.WriteLine("In size tests");
            for (int blockSize = 1024; blockSize <= 256 * 1024; blockSize *= 2)
            {
                string compressedFilePath = Path.ChangeExtension(inputFilePath, "." + blockSize.ToString() + ".compressed");
                using (Stream compressor = new CompressedWriteStream(File.Create(compressedFilePath), blockSize, false))
                    StreamUtilities.CopyFromFile(inputFilePath, compressor);

                double percent = 100.0 * (new FileInfo(compressedFilePath).Length) / (new FileInfo(inputFilePath).Length);
                Console.WriteLine("Blocksize " + blockSize.ToString().PadLeft(7) +
                    " compression " + percent.ToString("f2") + "%. Placed in file " + compressedFilePath);
            }
        }
        public static void Tests()
        {
            string testOrig = "text.orig";
            string testCompressed = "text.compressed";

            for (int fileSize = 1023; fileSize <= 1025; fileSize++)
            {
                CreateDataFile(testOrig, fileSize);
                FileStream origData = File.OpenRead(testOrig);

                // Try writing in various block sizes
                // TODO more sizes?
                for (int i = 1; i < 256; i += 37)
                {
                    CompressedWriteStream compressor = new CompressedWriteStream(File.Create(testCompressed), 64, false);
                    origData.Position = 0;
                    CopyInChunks(origData, compressor, i);
                    compressor.Close();

                    CompressedReadStream decompressor = new CompressedReadStream(testCompressed);
                    origData.Position = 0;
                    Debug.Assert(CompareStreams(origData, decompressor, 1024 * 16));
                    decompressor.Close();
                }

                CompressedReadStream lengthTest = new CompressedReadStream(testCompressed);
                Debug.Assert(lengthTest.Length == origData.Length);
                lengthTest.Close();

                // Try reading back in various seek positions.
                for (int blockSize = 20; blockSize < 300; blockSize += 47)
                {
                    CompressedReadStream decompressor = new CompressedReadStream(testCompressed);
                    for (int seekPosition = 0; seekPosition <= 1024; seekPosition += 16 * 3)
                        CompareStreams(origData, decompressor, blockSize, seekPosition);
                    decompressor.Close();
                }

                origData.Close();
            }
        }

        private static void CreateDataFile(string name, int length)
        {
            StreamWriter writer = File.CreateText(name);
            Random r = new Random(3454);

            string textLine = "The quick brown fox jumped over the lazy dog";
            int writtenBytes = 0;
            for (; ; )
            {
                if (writtenBytes + textLine.Length + 2 >= length)
                {
                    writer.WriteLine(textLine.Substring(0, length - writtenBytes - 2));
                    break;
                }
                int start = r.Next(textLine.Length - 3);
                int end = r.Next(start + 3, textLine.Length);
                writer.WriteLine(textLine.Substring(start, end - start));
                writtenBytes += (end - start + 2);
            }
            writer.Close();
        }
        private static bool FileCompare(string fileName1, string fileName2)
        {
            using (FileStream stream1 = File.OpenRead(fileName1))
            using (FileStream stream2 = File.OpenRead(fileName2))
                return CompareStreams(stream1, stream2, 1024);
        }
        private static void CompareStreams(Stream stream1, Stream stream2, int blockSize, int startPos)
        {
            stream1.Position = startPos;
            stream2.Position = startPos;
            CompareStreams(stream1, stream2, blockSize);
        }
        private static bool CompareStreams(Stream stream1, Stream stream2, int blockSize)
        {
            byte[] block1 = new byte[blockSize];
            byte[] block2 = new byte[blockSize];
            for (; ; )
            {
                Debug.Assert(stream1.Position == stream2.Position);
                int stream1Count = stream1.Read(block1, 0, blockSize);
                int stream2Count = stream2.Read(block2, 0, blockSize);
                if (stream1Count != stream2Count)
                {
                    Debug.Assert(false);
                    return false;
                }
                if (stream1Count == 0)
                    break;
                if (!ByteCompare(block1, 0, block2, 0, blockSize))
                    return false;
            }
            return true;
        }
        private static bool ByteCompare(byte[] buffer1, int offset1, byte[] buffer2, int offset2, int blockSize)
        {
            for (int i = 0; i < blockSize; i++)
                if (buffer1[i + offset1] != buffer2[i + offset2])
                {
                    Debug.Assert(false);
                    return false;
                }
            return true;
        }
        private static void CopyInChunks(Stream fromStream, Stream toStream, int blockSize)
        {
            byte[] block = new byte[blockSize];

            for (; ; )
            {
                int count = fromStream.Read(block, 0, blockSize);
                if (count == 0)
                    break;
                toStream.Write(block, 0, count);
            }
        }
    }
#endif
}

#endif // !NETSTANDARD1_3

#endif // false


text: export default from './create-playlist';

redpajama_set_name: RedPajamaGithub


text:
<?php

use yii\helpers\Inflector;
use yii\helpers\StringHelper;

/* @var $this yii\web\View */
/* @var $generator yii\gii\generators\crud\Generator */

/* @var $model \yii\db\ActiveRecord */
$model = new $generator->modelClass();
$safeAttributes = $model->safeAttributes();
if (empty($safeAttributes)) {
    $safeAttributes = $model->attributes();
}

$totalColumns = count($generator->getColumnNames());
//Deduct the columns that we don't display on form.
// Status, created_by, updated_by, created_at, updated_at, id
$hiddenColumns = 6;
$visibleColumns = $totalColumns - $hiddenColumns;

echo "<?php\n";
?>

use yii\widgets\ActiveForm;
use common\helpers\Html;

/* @var $this yii\web\View */
/* @var $model <?= ltrim($generator->modelClass, '\\') ?> */
/* @var $form yii\widgets\ActiveForm */
?>
<?= "<?php " ?>//echo Html::errorSummary($model); ?>

        <?= "<?php " ?>$form = ActiveForm::begin(); ?>
<?php if ($visibleColumns <= 3) : ?>

<?php else : ?>

<?php endif; ?>
<?php
$i = 0;
$half = ceil($visibleColumns / 2);
foreach ($generator->getColumnNames() as $attribute) {
    if($i == $half) {
echo '
'."\n";
echo '
'."\n";
    }
    if (in_array($attribute, $safeAttributes)) {
        if ($attribute == 'id' || $attribute == 'status' || $attribute == 'created_by' || $attribute == 'updated_by' || $attribute == 'created_at' || $attribute == 'updated_at') {
echo '';
        } else {
echo "                    <?= " . $generator->generateActiveField($attribute) . " ?>\n";
$i++;
        }
    }
}
?>

                    <div class="box-footer <?php echo $visibleColumns <= 3 ? 'text-center' : '' ?>">
                        <?= "<?= " ?>Html::submitButton($model->isNewRecord ? <?= $generator->generateString('Create') ?> : <?= $generator->generateString('Update') ?>, ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

        <?= "<?php " ?>ActiveForm::end(); ?>


text:
/**
 * @author Michael Danilov
 */
package com.google.code.appengine.awt.event;

import com.google.code.appengine.awt.AWTEvent;
import com.google.code.appengine.awt.Component;
import com.google.code.appengine.awt.Container;

public class HierarchyEvent extends AWTEvent {

    private static final long serialVersionUID = -5337576970038043990L;

    public static final int HIERARCHY_FIRST = 1400;

    public static final int HIERARCHY_CHANGED = 1400;

    public static final int ANCESTOR_MOVED = 1401;

    public static final int ANCESTOR_RESIZED = 1402;

    public static final int HIERARCHY_LAST = 1402;

    public static final int PARENT_CHANGED = 1;

    public static final int DISPLAYABILITY_CHANGED = 2;

    public static final int SHOWING_CHANGED = 4;

    private Container changedParent;
    private Component changed;
    private long changeFlag;

    public HierarchyEvent(Component source, int id, Component changed,
                          Container changedParent) {
        this(source, id, changed, changedParent, 0l);
    }

    public HierarchyEvent(Component source, int id, Component changed,
                          Container changedParent, long changeFlags) {
        super(source, id);

        this.changed = changed;
        this.changedParent = changedParent;
        this.changeFlag = changeFlags;
    }

    public Component getComponent() {
        return (Component) source;
    }

    public long getChangeFlags() {
        return changeFlag;
    }

    public Component getChanged() {
        return changed;
    }

    public Container getChangedParent() {
        return changedParent;
    }

    @Override
    public String paramString() {
        /* The format is based on 1.5 release behavior
         * which can be revealed by the following code:
         *
         * HierarchyEvent e = new HierarchyEvent(new Button("Button"),
         *          HierarchyEvent.HIERARCHY_CHANGED,
         *          new Panel(), new Container());
         * System.out.println(e);
         */
        String paramString = null;

        switch (id) {
        case HIERARCHY_CHANGED:
            paramString = "HIERARCHY_CHANGED"; //$NON-NLS-1$
            break;
        case ANCESTOR_MOVED:
            paramString = "ANCESTOR_MOVED"; //$NON-NLS-1$
            break;
        case ANCESTOR_RESIZED:
            paramString = "ANCESTOR_RESIZED"; //$NON-NLS-1$
            break;
        default:
            paramString = "unknown type"; //$NON-NLS-1$
        }

        paramString += " ("; //$NON-NLS-1$

        if (id == HIERARCHY_CHANGED) {
            if ((changeFlag & PARENT_CHANGED) > 0) {
                paramString += "PARENT_CHANGED,"; //$NON-NLS-1$
            }
            if ((changeFlag & DISPLAYABILITY_CHANGED) > 0) {
                paramString += "DISPLAYABILITY_CHANGED,"; //$NON-NLS-1$
            }
            if ((changeFlag & SHOWING_CHANGED) > 0) {
                paramString += "SHOWING_CHANGED,"; //$NON-NLS-1$
            }
        }

        return paramString + "changed=" + changed +  //$NON-NLS-1$
                ",changedParent=" + changedParent + ")"; //$NON-NLS-1$ //$NON-NLS-2$
    }

}


text:
title: "Cloud and moutain pr0n"
excerpt: "PaperFaces portrait of @d0ugal drawn with Paper by 53 on an iPad."
image:
  feature: paperfaces-d0ugal-twitter-lg.jpg
  thumb: paperfaces-d0ugal-twitter-150.jpg
tags: [portrait, illustration, Paper by 53, beard]
---

PaperFaces portrait of [@d0ugal](http://twitter.com/d0ugal).

{% include boilerplate/paperfaces-2.html %}

Work in progress screen captures Made with Paper.


text:
package me.lake.ffmpeg;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * Created by lake on 22/11/16.
 * Decoder_mp42YUV project.
 */
public class NativeMediaData {
    public long nativePointer;
    public int width;
    public int height;
    public long duration;
    public float frameRate;

    public NativeMediaData() {

    }

    public void setNativePointer(long nativePointer) {
        this.nativePointer = nativePointer;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public void setDuration(long duration) {
        this.duration = duration;
    }

    public void setFrameRate(float frameRate) {
        this.frameRate = frameRate;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("ResParameter:");
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (Modifier.isStatic(field.getModifiers())) {
                continue;
            }
            field.setAccessible(true);
            try {
                sb.append(field.getName());
                sb.append('=');
                sb.append(field.get(this));
                sb.append(';');
            } catch (IllegalAccessException e) {
            }
        }
        return super.toString()+";"+sb.toString();
    }
}


text:
using AH.DUtility;
using AH.ModuleController.IPDSR;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Linq;
using AH.Shared.UI;

namespace AH.ModuleController.UI.IPD.Forms
{
    public partial class frmAdmissionCancel : AH.Shared.UI.frmSmartFormStandard
    {
        IPDSR.IPDWSClient ipdSc = new IPDSR.IPDWSClient();
        List<InPatient> oPats = new List<InPatient>();
        string purposeID = Utility.GetPurposeCode(Utility.PurposeCode.AdvanceCollection);
        string revenueHeadGroupAdvance = Utility.GetMasterChargeCode(Utility.ChargesCode.AdvanceCharges);
        string revenueHead = Utility.GetHeadChargeCode(Utility.HeadChargeCode.Advance);

        public frmAdmissionCancel()
        {
            InitializeComponent();
        }

        private void cboPatientSearch_Click(object sender, EventArgs e)
        {
            try
            {
                string vrfy = ipdSc.VerifyInPatient(txtRegistrationId.Text);
                if (vrfy.Length > 0)
                {
                    MessageBox.Show(vrfy, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtRegistrationId.Focus();
                    btnNew.PerformClick();
                    return;
                }

                string vrfySatyingTime = ipdSc.CheckPatStayingTime(txtRegistrationId.Text);
                if (vrfySatyingTime.Length > 0)
                {
                    MessageBox.Show(vrfySatyingTime, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtRegistrationId.Focus();
                    btnNew.PerformClick();
                    return;
                }

                InPatient pat = ipdSc.GetAdmittedPatient(txtRegistrationId.Text);
                LoadPatient(pat);
                rdPreviousAmount.Text = ipdSc.GetTotalAmount(txtRegistrationId.Text).ToString();
                LoadListViewReport(txtRegistrationId.Text);
            }
            catch (System.ServiceModel.CommunicationException commp)
            {
                MessageBox.Show(Utility.CommunicationErrorMsg, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

        }

        private void LoadPatient(InPatient pat)
        {
            txtPatientName.Text = pat.Name;
            txthcn.Text = pat.HCN;
            txtStaffId.Text = pat.StaffID;
            AH.DUtility.Age age = Utility.CalculateAge(pat.DOB);
            txtAgeYears.Text = age.Year.ToString();
            txtAgeMonths.Text = age.Month.ToString();
            txtAgeDays.Text = age.Day.ToString();
            txtAgeHours.Text = "0";
            txtSex.Text = pat.Sex;

            txtBedNo.Text = pat.Bed.BedNo;
            txtReffDocName.Text = pat.Doctor.Name;
            txtDeptId.Text = pat.Department.DepartmentID;
            txtDept.Text = pat.Department.DepartmentTitle;

            txtUnitId.Text = pat.DepartmentUnit.UnitId;
            txtRoomNo.Text = pat.Room.RoomNo.ToString();

            if ((txtDeptId.Text != null) && txtUnitId.Text != null)
            {
                oPats = ipdSc.GetDepartmentHead(txtDeptId.Text, txtUnitId.Text).ToList();
            }

            foreach (InPatient oPat in oPats)
            {
                txtRdDepartmentHead.Text = oPat.Department.DepartmentUnitHeadID;
                txtDepartmentHead.Text = oPat.Department.DepartmentUnitHead;
            }

        }

        private void btnDepositHistory_Click(object sender, EventArgs e)
        {
            try
            {
                string vrfy = ipdSc.VerifyInPatient(txtRegistrationId.Text);
                if (vrfy.Length > 0)
                {
                    MessageBox.Show(vrfy, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtRegistrationId.Focus();
                    btnNew.PerformClick();
                    return;
                }

                frmAdvancePaymentHistory payHist = new frmAdvancePaymentHistory(txtRegistrationId.Text, txtPatientName.Text);
                payHist.ShowDialog();
            }
            catch (System.ServiceModel.CommunicationException commp)
            {
                MessageBox.Show(Utility.CommunicationErrorMsg, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
             List<string> vf = new List<string>() {"txtRegistrationId", "txtPatientName","txtAmount" };
            Control control = Utility.ReqFieldValidator(this, vf);
            if (control != null)
            {
                MessageBox.Show(Utility.getFMS(control.Name) + Utility.Req, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                control.Focus();
                return;
            }

            string label = "Advance Deposit Payment";
            string patNo = txthcn.Text;
            string patName = txtPatientName.Text;
            string department = txtDeptId.Text;
            string departmentUnit = txtUnitId.Text;
            string purposeID = Utility.GetPurposeCode(Utility.PurposeCode.PrescriptionFee);
            string reffDepartment = "N/A";
            string departmentReffUnit = "N/A";
            decimal departmentAmount = 0;
            decimal reffDepartmentAmount = 0;
            string amount = txtTotalAmount.Text;// "0";// txtAmount.Text;
            string advance = rdPreviousAmount.Text;//"0";
            string vat = "0";
            string discount = "0";
            string discountBy = "";
            string paymentType = "0";
            DateTime updateDate = DateTime.ParseExact(DateTime.Now.ToString("dd/MM/yyyy"), "dd/MM/yyyy", new System.Globalization.CultureInfo("en-GB"));

            try
            {
                AH.Shared.UI.frmPayment frm = new frmPayment(1, label, patNo, patName, purposeID, amount, advance, vat, discount, discountBy, department, reffDepartment, departmentUnit, departmentReffUnit, departmentAmount, reffDepartmentAmount, updateDate, paymentType,0,false);
                frm.onSaveButtonClicked = new frmPayment.SaveButtonClick(PaymentData);
                frm.Show();
            }
            catch (System.ServiceModel.CommunicationException commp)
            {
                MessageBox.Show(Utility.CommunicationErrorMsg, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

        }
        private OPDPayment PaymentObject(AH.Shared.MODEL.OPDPayment payment)
        {
            OPDPayment paymentObject = new OPDPayment();
            paymentObject.Advance = payment.Advance;
            paymentObject.Amount = payment.Amount;
            paymentObject.CompanyID = payment.CompanyID;
            paymentObject.ConsultantFee = payment.ConsultantFee;
            paymentObject.Department = payment.Department;
            paymentObject.DepartmentUnit = payment.DepartmentUnit;
            paymentObject.DeptAmount = payment.DeptAmount;
            paymentObject.Discount = payment.Discount;
            paymentObject.EntryBy = payment.EntryBy;
            paymentObject.EntryDate = payment.EntryDate;
            paymentObject.EntryName = payment.EntryName;
            paymentObject.HCN = payment.HCN;
            paymentObject.LocationID = payment.LocationID;
            paymentObject.MachineID = payment.LocationID;
            paymentObject.NetAmount = payment.NetAmount;
            paymentObject.PaymentDate = payment.PaymentDate;
            paymentObject.PaymentType = payment.PaymentType;
            paymentObject.PreviousDue = payment.PreviousDue;
            paymentObject.PurposeID = payment.PurposeID;
            paymentObject.PurposeTitle = payment.PurposeTitle;
            paymentObject.ReffDept = payment.ReffDept;
            paymentObject.ReffDeptAmount = payment.ReffDeptAmount;
            paymentObject.ReffDeptUnit = payment.ReffDeptUnit;
            paymentObject.RefferedFee = payment.RefferedFee;
            paymentObject.RegistrationNo = payment.RegistrationNo;
            paymentObject.Staff = payment.Staff;
            paymentObject.TransactionNo = payment.TransactionNo;
            paymentObject.VAT = payment.VAT;
            return paymentObject;
        }

        private void PaymentData(AH.Shared.MODEL.OPDPayment payment)
        {
            try
            {
                InPatient pat = this.PopulatePatAdmissionCancel((OPDPayment)PaymentObject(payment));
                short i = ipdSc.SavePatientAdmissionCancel(pat);
                if (i == 0)
                {
                    MessageBox.Show(Utility.MistakeMsg, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    MessageBox.Show(Utility.InsertMsg, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    btnNew.PerformClick();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

        }

        private void FormatGridReport()
        {
            lstRevenueDetails.CheckBoxes = false;
            lstRevenueDetails.Columns.Add("Service Name", 200, HorizontalAlignment.Left);
            lstRevenueDetails.Columns.Add("Amount", 150, HorizontalAlignment.Left);
        }

        private void LoadListViewReport(string regno)
        {
            lstRevenueDetails.Items.Clear();

            List<RevenueHead> rvhds = ipdSc.GetDepartmentRevenue(regno).ToList();

            foreach (RevenueHead rv in rvhds)
            {
                ListViewItem itm = new ListViewItem(rv.Title);
                itm.SubItems.Add(rv.Amount.ToString());
                lstRevenueDetails.Items.Add(itm);
                txtTotalAmount.Text = (+Convert.ToInt32(rv.Amount)).ToString();
                // = rv.ID + ',' + rv.RevenueHeadGroup.ID + ',' + rv.Amount.ToString() + ';';
                rdTxtNetPayment.Text = ((Convert.ToInt32(txtTotalAmount.Text) - Convert.ToInt32(rdPreviousAmount.Text)).ToString());
            }
        }

        private void frmAdmissionCancel_Load(object sender, EventArgs e)
        {
            FormatGridReport();
            txtRegistrationId.Select();

            cboCancelReason.DisplayMember = "Value";
            cboCancelReason.ValueMember = "Key";
            cboCancelReason.DataSource = new BindingSource((ipdSc.GetAdmCancelReasonDic("E")), null);
        }

        private InPatient PopulatePatAdmissionCancel(OPDPayment payment)
        {
            InPatient patObj = new InPatient();
            patObj.RegistrationNo = txtRegistrationId.Text;
            patObj.Remarks = txtRemarks.Text;

            patObj.StaffID =txtStaffId.Text;

            patObj.CancellationReason = cboCancelReason.SelectedValue.ToString();

            Department odept = new Department();
            odept.DepartmentID = txtDeptId.Text;
            patObj.Department = odept;

            DepartmentUnit oUnit = new DepartmentUnit();
            oUnit.UnitId = txtUnitId.Text;
            patObj.DepartmentUnit = oUnit;

            OPDPayment opdObj = payment;
            patObj.Payment = opdObj;

            RevenueHead rvnHd = new RevenueHead();
            rvnHd.ID = revenueHead;

            RevenueHeadGroup rvnHdGroup = new RevenueHeadGroup();
            rvnHdGroup.ID = revenueHeadGroupAdvance;
            rvnHd.RevenueHeadGroup = rvnHdGroup;

            patObj.RevenueHead = rvnHd;

            EntryParameter ep = new EntryParameter();
            ep.EntryBy = Utility.UserId;
            ep.CompanyID = Utility.CompanyID;
            ep.LocationID = Utility.LocationID;
            ep.MachineID = Utility.MachineID;
            patObj.EntryParameter = ep;

            return patObj;
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {

        }

    }
}


text:
<?php

namespace App\Security;

use App\Repositories;
use Nette;
use Nette\Localization\ITranslator;
use Nette\Security\Passwords;

class Authenticator extends Nette\Object implements Nette\Security\IAuthenticator
{
    /** @var int Account activation limit set to one hour */
    const ACTIVATION_LIMIT_TIMESTAMP = 3600000;

    /** @var IdentityFactory */
    private $identityFactory;

    /** @var ITranslator */
    private $translator;

    /** @var Repositories\UserRepository */
    private $userRepository;

    /**
     * @param IdentityFactory             $identityFactory
     * @param ITranslator                 $translator
     * @param Repositories\UserRepository $userRepository
     */
    public function __construct(IdentityFactory $identityFactory, ITranslator $translator, Repositories\UserRepository $userRepository)
    {
        $this->identityFactory = $identityFactory;
        $this->translator      = $translator;
        $this->userRepository  = $userRepository;
    }

    /**
     * @param  string[]                               $credentials
     * @throws Nette\Security\AuthenticationException
     * @return Nette\Security\Identity
     */
    public function authenticate(array $credentials)
    {
        list($email, $password) = $credentials;

        $user = $this->userRepository->getByEmail($email);

        if (!$user) {
            throw new Nette\Security\AuthenticationException($this->translator->translate('locale.sign.authentication_issues'), self::IDENTITY_NOT_FOUND);
        } elseif (!$user->isAuthenticated) {
            throw new Nette\Security\AuthenticationException($this->translator->translate('locale.sign.authentication_issues'), self::NOT_APPROVED);
        } elseif (!Passwords::verify($password . $user->salt, $user->password)) {
            throw new Nette\Security\AuthenticationException($this->translator->translate('locale.sign.authentication_issues'), self::INVALID_CREDENTIAL);
        } elseif (Passwords::needsRehash($user->password)) {
            $this->userRepository->updatePassword($user, $user->password);
        }

        return $this->identityFactory->createIdentity($user);
    }
}


text:
#include <grpc/support/port_platform.h>

#ifdef GPR_WINDOWS

#include "src/core/lib/security/credentials/alts/check_gcp_environment.h"

#include <shellapi.h>
#include <stdio.h>
#include <tchar.h>
#include <windows.h>

#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/sync.h>

namespace grpc_core {
namespace internal {

bool check_bios_data(const char*) { return false; }

bool check_windows_registry_product_name(HKEY root_key,
                                         const char* reg_key_path,
                                         const char* reg_key_name) {
  const size_t kProductNameBufferSize = 256;
  char const expected_substr[] = "Google";

  // Get the size of the string first to allocate our buffer. This includes
  // enough space for the trailing NUL character that will be included.
  DWORD buffer_size{};
  auto rc = ::RegGetValueA(
      root_key, reg_key_path, reg_key_name, RRF_RT_REG_SZ,
      nullptr,        // We know the type will be REG_SZ.
      nullptr,        // We're only fetching the size; no buffer given yet.
      &buffer_size);  // Fetch the size in bytes of the value, if it exists.
  if (rc != 0) {
    return false;
  }

  if (buffer_size > kProductNameBufferSize) {
    return false;
  }

  // Retrieve the product name string.
  char buffer[kProductNameBufferSize];
  buffer_size = kProductNameBufferSize;
  rc = ::RegGetValueA(
      root_key, reg_key_path, reg_key_name, RRF_RT_REG_SZ,
      nullptr,                     // We know the type will be REG_SZ.
      static_cast<void*>(buffer),  // Fetch the string value this time.
      &buffer_size);  // The string size in bytes, not including trailing NUL.
  if (rc != 0) {
    return false;
  }

  return strstr(buffer, expected_substr) != nullptr;
}

}  // namespace internal
}  // namespace grpc_core

static bool g_compute_engine_detection_done = false;
static bool g_is_on_compute_engine = false;
static gpr_mu g_mu;
static gpr_once g_once = GPR_ONCE_INIT;

static void init_mu(void) { gpr_mu_init(&g_mu); }

bool grpc_alts_is_running_on_gcp() {
  char const reg_key_path[] = "SYSTEM\\HardwareConfig\\Current\\";
  char const reg_key_name[] = "SystemProductName";

  gpr_once_init(&g_once, init_mu);
  gpr_mu_lock(&g_mu);
  if (!g_compute_engine_detection_done) {
    g_is_on_compute_engine =
        grpc_core::internal::check_windows_registry_product_name(
            HKEY_LOCAL_MACHINE, reg_key_path, reg_key_name);
    g_compute_engine_detection_done = true;
  }
  gpr_mu_unlock(&g_mu);
  return g_is_on_compute_engine;
}

#endif  // GPR_WINDOWS


text:
set -e

cd ~

if [[ "$OSTYPE" == darwin* ]]; then
    ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

    brew install caskroom/cask/brew-cask
    brew update

    brew install git curl tree htop ctags tmux tig the_silver_searcher

    brew cask install seil
    # https://pqrs.org/osx/karabiner/seil.html#usage

    brew cask install iterm2 vagrant virtualbox

    brew install zsh

    brew install macvim --override-system-vim

    brew tap thoughtbot/formulae
    brew install rcm

    # currently only support for Debian-based OSes

else
    # get env variables about OS
    . /etc/lsb-release
    os=$(lsb_release -si)
    ver=$(lsb_release -sr)

    # install packages
    sudo apt-get -y update
    sudo apt-get -y install git curl tree htop ctags tmux tig silversearcher-ag ethtool xclip zsh vim-gnome gnome-tweak-tool

    # install rcm
    pushd /tmp
    wget -N https://thoughtbot.github.io/rcm/debs/rcm_1.2.3-1_all.deb
    sha=$(sha256sum rcm_1.2.3-1_all.deb | cut -f1 -d' ')
    [ "$sha" = "fb8ec2611cd4d519965b66fcf950bd93d7593773659f83a8612053217daa38b4" ] && \
        sudo dpkg -i rcm_1.2.3-1_all.deb
    popd

    # install chromium and make default
    sudo apt-get -y install chromium-browser
    sudo ln -sf /etc/alternatives/x-www-browser /usr/bin/google-chrome
fi

# dotfiles
if [ $(hostname) = "dotfiles-test" ]; then
    rm -Rf ~/.dotfiles
    cp -R /vagrant ~/.dotfiles
else
    if cd ~/.dotfiles; then
        git pull
    else
        git clone git://github.com/christophermanning/dotfiles.git ~/.dotfiles
    fi
fi
env RCRC=$HOME/.dotfiles/rcrc rcup

# vim-plug install plugins
vim +PlugInstall +qa

# zsh
if cd "${ZDOTDIR:-$HOME}/.zprezto"; then
    git pull
else
    git clone --recursive https://github.com/sorin-ionescu/prezto.git "${ZDOTDIR:-$HOME}/.zprezto"
fi

sudo chsh -s /bin/zsh $USER

# setup local files
if [ -t 1 ]; then
    echo "Please enter git name: "
    read git_name
    echo "export GIT_AUTHOR_NAME=\"$git_name\" && export GIT_COMMITTER_NAME=\$GIT_AUTHOR_NAME" >> ~/.zshrc.local

    echo "Please enter git email: "
    read git_email
    echo "export GIT_AUTHOR_EMAIL=\"$git_email\" && export GIT_COMMITTER_EMAIL=\$GIT_AUTHOR_EMAIL" >> ~/.zshrc.local
fi


text:
package org.gradle.api.reporting.dependencies;

import groovy.lang.Closure;
import org.gradle.api.Action;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.internal.CollectionCallbackActionDecorator;
import org.gradle.api.internal.ConventionTask;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.strategy.VersionComparator;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.strategy.VersionParser;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.strategy.VersionSelectorScheme;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.reporting.Reporting;
import org.gradle.api.reporting.dependencies.internal.DefaultDependencyReportContainer;
import org.gradle.api.reporting.dependencies.internal.HtmlDependencyReporter;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.Nested;
import org.gradle.api.tasks.TaskAction;
import org.gradle.internal.logging.ConsoleRenderer;
import org.gradle.util.ClosureBackedAction;

import javax.inject.Inject;
import java.util.Set;

/**
 * Generates an HTML dependency report. This report
 * combines the features of the ASCII dependency report and those of the ASCII
 * dependency insight report. For a given project, it generates a tree of the dependencies
 * of every configuration, and each dependency can be clicked to show the insight of
 * this dependency.
 *

 * This task generates a report for the task's containing project by default. But it can also generate
 * a report for multiple projects, by setting the value of the
 * projects property. Here's how to generate an HTML
 * dependency report for all the projects of a multi-project build, for example:
 *

 * htmlDependencyReport {
 *     projects = project.allprojects
 * }
 *

 *

 * The report is generated in the build/reports/project/dependencies directory by default.
 * This can also be changed by setting the reports.html.destination property:
 *

 * htmlDependencyReport {
 *     reports.html.destination = file("build/reports/project/dependencies")
 * }
 *

 */
public class HtmlDependencyReportTask extends ConventionTask implements Reporting<DependencyReportContainer> {
    private Set<Project> projects;
    private final DependencyReportContainer reports;

    public HtmlDependencyReportTask() {
        reports = getObjectFactory().newInstance(DefaultDependencyReportContainer.class, this, getCallbackActionDecorator());
        reports.getHtml().setEnabled(true);
        getOutputs().upToDateWhen(new Spec<Task>() {
            @Override
            public boolean isSatisfiedBy(Task element) {
                return false;
            }
        });
    }

    @Nested
    @Override
    public DependencyReportContainer getReports() {
        return reports;
    }

    @Override
    public DependencyReportContainer reports(Closure closure) {
        return reports(new ClosureBackedAction<DependencyReportContainer>(closure));
    }

    @Override
    public DependencyReportContainer reports(Action<? super DependencyReportContainer> configureAction) {
        configureAction.execute(reports);
        return reports;
    }

    @Inject
    protected ObjectFactory getObjectFactory() {
        throw new UnsupportedOperationException();
    }

    @Inject
    protected VersionSelectorScheme getVersionSelectorScheme() {
        throw new UnsupportedOperationException();
    }

    @Inject
    protected VersionComparator getVersionComparator() {
        throw new UnsupportedOperationException();
    }

    @Inject
    protected  VersionParser getVersionParser() {
        throw new UnsupportedOperationException();
    }

    /**
     * Required for decorating reports container callbacks for tracing user code application.
     *
     * @since 5.1
     */
    @Inject
    protected CollectionCallbackActionDecorator getCallbackActionDecorator() {
        throw new UnsupportedOperationException();
    }

    @TaskAction
    public void generate() {
        if (!reports.getHtml().isEnabled()) {
            setDidWork(false);
            return;
        }

        HtmlDependencyReporter reporter = new HtmlDependencyReporter(getVersionSelectorScheme(), getVersionComparator(), getVersionParser());
        reporter.render(getProjects(), reports.getHtml().getDestination());

        getProject().getLogger().lifecycle("See the report at: {}", new ConsoleRenderer().asClickableFileUrl(reports.getHtml().getEntryPoint()));
    }

    /**
     * Returns the set of projects to generate a report for. By default, the report is generated for the task's
     * containing project.
     *
     * @return The set of files.
     */
    @Internal
    public Set<Project> getProjects() {
        return projects;
    }

    /**
     * Specifies the set of projects to generate this report for.
     *
     * @param projects The set of projects. Must not be null.
     */
    public void setProjects(Set<Project> projects) {
        this.projects = projects;
    }
}


text:
extern NSString *XSDownloadComplete;

@interface DownloadWindow : ProgressWindow <NSURLDownloadDelegate> {
    NSString *displayText;
    NSURLResponse *response;
    NSUInteger bytesDownloaded;
    NSString *destination;
}
@property (retain) NSString *displayText;
@property (retain) NSURLResponse *response;
@property (retain) NSString *destination;
@end


text:
package breeze.generic

import collection.mutable.{ArrayBuffer, HashMap}
import java.util.concurrent.ConcurrentHashMap
import breeze.util.ReflectionUtil
import collection.mutable

/**
 * A Multimethod is basically a glorified registry that uses dynamic reflection (and subtyping) to determine which
 * version of the method to invoke.
 *
 * @author dlwh
 */
trait Multimethod[Method[AA, RR] <: MethodImpl[AA, RR], A <: AnyRef, R] extends MMRegistry1[Method[_ <: A, _ <: R]] { this: Method[A, R] =>
  protected def bindingMissing(a: A): R = throw new UnsupportedOperationException("Types not found!")
  protected def multipleOptions(a: A, m: Map[Class[_],Method[_ <: A, _ <: R]]) = {
    throw new RuntimeException("Multiple bindings for method: " + m)
  }

  def apply(a: A): R = {
    val ac = a.asInstanceOf[AnyRef].getClass

    val cached = cache.get(ac)
    if(cached != null) {
      cached.asInstanceOf[Method[A, R]].apply(a)
    } else {
      val options = resolve(ac)
      options.size match {
        case 0 => bindingMissing(a)
        case 1 =>
          val method = options.values.head
          cache.put(ac, method)
          method.asInstanceOf[Method[A, R]].apply(a)
        case _ =>
          val selected = selectBestOption(options)
          if(selected.size != 1)
            multipleOptions(a, options)
          else {
            val method = selected.values.head
            cache.put(ac, method)
            method.asInstanceOf[Method[A, R]].apply(a)
          }
      }
    }
  }

  def register[AA <: A](op: Method[AA, _ <: R])(implicit manA: Manifest[AA]) {
    super.register(manA.erasure.asInstanceOf[Class[AA]], op)
  }
}

/**
 * Basically Function1, but not because we don't want these coming up when implicit search happens...
 * @tparam A
 * @tparam R
 */
trait MethodImpl[A,+R] {
  def apply(a: A):R
}

trait Multimethod2[Method[AA,BB,RR]<:Function2[AA,BB,RR],A, B, R] extends ((A, B) => R) with MMRegistry2[Method[_<:A, _<:B, _<:R]] { this: Method[A, B, R] =>
  protected def bindingMissing(a: A, b: B):R = throw new UnsupportedOperationException("Types not found!" + a + b + " " + ops)
  protected def multipleOptions(a: A, b: B, m: Map[(Class[_],Class[_]),Method[_ <: A, _ <: B, _ <: R]]) = {
    throw new RuntimeException("Multiple bindings for method: " + m)
  }

  def apply(a: A, b: B): R = {
    val ac = a.asInstanceOf[AnyRef].getClass
    val bc = b.asInstanceOf[AnyRef].getClass

    val cached = cache.get(ac -> bc)
    if(cached != null) {
      cached match {
        case None => bindingMissing(a, b)
        case Some(m) =>
          m.asInstanceOf[Method[A, B, R]].apply(a, b)
      }
    } else {
      val options = resolve(ac, bc.asInstanceOf[Class[_<:B]])
      options.size match {
        case 0 =>
          cache.put(ac -> bc, None)
          bindingMissing(a, b)
        case 1 =>
          val method = options.values.head
          cache.put(ac -> bc, Some(method))
          method.asInstanceOf[Method[A, B, R]].apply(a, b)
        case _ =>
          val selected = selectBestOption(options)
          if(selected.size != 1)
            multipleOptions(a, b, options)
          else {
            val method = selected.values.head
            cache.put(ac -> bc, Some(method))
            method.asInstanceOf[Method[A, B, R]].apply(a, b)
          }
      }
    }
  }

  def register[AA<:A, BB<:B](op: Method[AA, BB, _ <: R])(implicit manA: Manifest[AA], manB: Manifest[BB]) {
    super.register(manA.erasure.asInstanceOf[Class[_]], manB.erasure.asInstanceOf[Class[_]], op)
  }

}

/**
 * A Multiproc2 is a Multimethod that is guaranteed to return Unit
 * @author dlwh
 */
trait Multiproc2[Method[AA,BB]<:(AA, BB) => Unit,A<:AnyRef,B] extends ((A, B) => Unit) with MMRegistry2[Method[_<:A, _<:B]] { this: Method[A, B] =>
  protected def bindingMissing(a: A, b: B):Unit = throw new UnsupportedOperationException("Types not found!")
  protected def multipleOptions(a: A, b: B, m: Map[(Class[_],Class[_]),Method[_ <: A, _ <: B]]) = {
    throw new RuntimeException("Multiple bindings for method: " + m)
  }

  def apply(a: A, b: B):Unit = {
    val ac = a.asInstanceOf[AnyRef].getClass
    val bc = b.asInstanceOf[AnyRef].getClass

    val cached = cache.get(ac -> bc)
    if(cached != null) {
      cached match {
        case None => bindingMissing(a, b)
        case Some(m) =>
          m.asInstanceOf[Method[A, B]].apply(a, b)
      }
    } else {
      val m = resolve(a.getClass, b.asInstanceOf[AnyRef].getClass.asInstanceOf[Class[_<:B]])
      m.size match {
        case 0 =>
          cache.put(ac -> bc, None)
          bindingMissing(a, b)
        case 1 =>
          val method = m.values.head
          cache.put(ac -> bc, Some(method))
          method.asInstanceOf[Method[A, B]].apply(a, b)
        case _ =>
          val selected = selectBestOption(m)
          if(selected.size != 1)
            multipleOptions(a, b, m)
          else {
            val method = selected.values.head
            cache.put(ac -> bc, Some(method))
            selected.values.head.asInstanceOf[Method[A, B]].apply(a, b)
          }
      }
    }
  }

  def register[AA<:A, BB<:B](op: Method[AA, BB])(implicit manA: Manifest[AA], manB: Manifest[BB]) {
    super.register(manA.erasure.asInstanceOf[Class[AA]], manB.erasure.asInstanceOf[Class[BB]], op)
  }

}

trait MMRegistry2[R] {
  protected val ops = HashMap[(Class[_],Class[_]), R]()
  protected val cache = new ConcurrentHashMap[(Class[_], Class[_]), Option[R]]()

  def register(a: Class[_], b: Class[_], op: R) {
    ops(a -> b) = op
    if(b.isPrimitive) {
      ops(a -> ReflectionUtil.boxedFromPrimitive(b)) = op
    }
    if(a.isPrimitive) {
      ops(ReflectionUtil.boxedFromPrimitive(a) -> b) = op
      if(b.isPrimitive) {
        ops(ReflectionUtil.boxedFromPrimitive(a) -> ReflectionUtil.boxedFromPrimitive(b)) = op
      }
    }
    cache.clear()
  }

  private def closeSupertypes(a: Class[_]) = {
    val result = collection.mutable.Set[Class[_]]()
    val queue = new mutable.Queue[Class[_]]()
    queue.enqueue(a)
    while(queue.nonEmpty) {
      val t = queue.dequeue()
      result += t
      val s = t.getSuperclass
      if(s != null) {
        queue += s
      }
      for(i <- t.getInterfaces) {
        if(!result(i)) {
          queue += i
        }
      }
    }
    result
  }

  protected def resolve(a: Class[_], b: Class[_]):Map[(Class[_], Class[_]), R] = {
    ops.get(a -> b) match {
      case Some(m) => Map((a->b) -> m)
      case None =>
        val newCA = a.getInterfaces
        val newCB = b.getInterfaces
        val sa = closeSupertypes(a)
        val sb = closeSupertypes(b)
        val candidates = ArrayBuffer[((Class[_], Class[_]), R)]()
        for( aa <- sa; bb <- sb; op <- ops.get(aa -> bb)) {
          candidates += ((aa -> bb) -> op)
        }
        candidates.toMap[(Class[_], Class[_]), R]
    }

  }

  /** This selects based on the partial order induced by the inheritance hierarchy.
   *  If there is ambiguity, all are returned.
   **/
  protected def selectBestOption(options:Map[(Class[_],Class[_]),R]) = {
    var bestCandidates = Set[(Class[_],Class[_])]()
    for ( pair@(aa,bb) <- options.keys) {
      // if there is no option (aaa,bbb) s.t. aaa <: aa && bbb <: bb, then add it to the list
      if (!bestCandidates.exists(pair => aa.isAssignableFrom(pair._1) && bb.isAssignableFrom(pair._2))) {
        bestCandidates = bestCandidates.filterNot(pair => pair._1.isAssignableFrom(aa) && pair._2.isAssignableFrom(bb))
        bestCandidates += pair
      }
    }

    options.filterKeys(bestCandidates)
  }
}

trait MMRegistry1[M] {
  protected val ops = HashMap[Class[_], M]()
  protected val cache = new ConcurrentHashMap[Class[_], M]()

  def register(a: Class[_], op: M) {
    ops(a) = op
    if(a.isPrimitive) {
      ops(ReflectionUtil.boxedFromPrimitive(a)) = op
    }
    cache.clear()
  }

  protected def resolve(a: Class[_], checkedA: Set[Class[_]] = Set.empty):Map[Class[_], M] = {
    ops.get(a) match {
      case Some(m) => Map(a -> m)
      case None =>
        val newCA = checkedA ++ a.getInterfaces
        val sa = a.getSuperclass +: a.getInterfaces.filterNot(checkedA)
        val allParents = for(aa <- sa; if aa != null; m <- resolve(aa, newCA)) yield {
          m
        }
        allParents.toMap
    }

  }

  /** This selects based on the partial order induced by the inheritance hierarchy.
   *  If there is ambiguity, all are returned.
   **/
  protected def selectBestOption(options:Map[Class[_],M]) = {
    var bestCandidates = Set[Class[_]]()
    for ( aa <- options.keys) {
      // if there is no option (aaa,bbb) s.t. aaa <: aa && bbb <: bb, then add it to the list
      if (!bestCandidates.exists(c => aa.isAssignableFrom(c))) {
        bestCandidates = bestCandidates.filterNot(c => c.isAssignableFrom(aa))
        bestCandidates += aa
      }
    }

    options.filterKeys(bestCandidates)
  }
}


text:
@interface _STDSSelectionButtonView: UIView
@property (nonatomic) BOOL isCheckbox;
@property (nonatomic) STDSSelectionCustomization *customization;
@property (nonatomic, getter = isSelected) BOOL selected;
@end

@implementation _STDSSelectionButtonView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.opaque = NO;
    }

    return self;
}

- (void)setSelected:(BOOL)selected {
    _selected = selected;
    [self setNeedsDisplay];
}

- (void)setCustomization:(STDSSelectionCustomization *)customization {
    _customization = customization;
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    if (self.isCheckbox) {
        [self _drawCheckboxWithRect:rect];
    } else {
        [self _drawRadioButtonWithRect:rect];
    }
}

- (void)_drawRadioButtonWithRect:(CGRect)rect {
    // Draw background
    UIBezierPath *background = [UIBezierPath bezierPathWithOvalInRect:rect];
    if (self.isSelected) {
        [self.customization.primarySelectedColor setFill];
    } else {
        [self.customization.unselectedBackgroundColor setFill];
    }
    [background fill];

    // Draw unselected border
    if (!self.isSelected) {
        UIBezierPath *border = [UIBezierPath bezierPathWithOvalInRect:CGRectInset(rect, 0.5, 0.5)];
        [self.customization.unselectedBorderColor setStroke];
        [border stroke];
    }

    // Draw inner circle if selected
    if (self.isSelected) {
        CGRect selectedRect = CGRectInset(rect, 9, 9);
        UIBezierPath *selected = [UIBezierPath bezierPathWithOvalInRect:selectedRect];
        [self.customization.secondarySelectedColor setFill];
        [selected fill];
    }
}

- (void)_drawCheckboxWithRect:(CGRect)rect {
    // Draw background
    UIBezierPath *background = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:8];
    if (self.isSelected) {
        [self.customization.primarySelectedColor setFill];
    } else {
        [self.customization.unselectedBackgroundColor setFill];
    }
    [background fill];

    // Draw unselected border
    if (!self.isSelected) {
        UIBezierPath *border = [UIBezierPath bezierPathWithRoundedRect:CGRectInset(rect, 0.5, 0.5) cornerRadius:8];
        border.lineWidth = 0.5;
        [self.customization.unselectedBorderColor setStroke];
        [border stroke];
    }

    // Draw check mark if selected
    if (self.isSelected) {
        UIBezierPath *checkmark = [UIBezierPath bezierPath];
        [checkmark moveToPoint: CGPointMake(10, 15)];
        [checkmark addLineToPoint:CGPointMake(13.5, 18.5)];
        [checkmark addLineToPoint:CGPointMake(22, 10)];
        [self.customization.secondarySelectedColor setStroke];
        checkmark.lineWidth = 2;
        [checkmark stroke];
    }
}

@end

static const CGFloat kMinimumTouchAreaDimension = 42.f;
static const CGFloat kContentSizeDimension = 30.f;

@implementation STDSSelectionButton {
    _STDSSelectionButtonView *_contentView;
}

- (instancetype)initWithCustomization:(STDSSelectionCustomization *)customization {
    self = [super init];
    if (self) {
        _contentView = [[_STDSSelectionButtonView alloc] initWithFrame:CGRectMake(0, 0, kContentSizeDimension, kContentSizeDimension)];
        _contentView.userInteractionEnabled = NO;
        [self addSubview:_contentView];
        self.customization = customization;
    }
    return self;
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    BOOL pointInside = [super pointInside:point withEvent:event];
    if (!pointInside &&
        self.enabled &&
        !self.isHidden &&
        (CGRectGetWidth(self.bounds) < kMinimumTouchAreaDimension || CGRectGetHeight(self.bounds) < kMinimumTouchAreaDimension)
        ) {
        // Make sure that we intercept touch events even outside our bounds if they are within the
        // minimum touch area. Otherwise this button is too hard to tap
        CGRect expandedBounds = CGRectInset(self.bounds, MIN(CGRectGetWidth(self.bounds) - kMinimumTouchAreaDimension, 0), MIN(CGRectGetHeight(self.bounds) < kMinimumTouchAreaDimension, 0));
        pointInside = CGRectContainsPoint(expandedBounds, point);
    }

    return pointInside;
}

- (CGSize)intrinsicContentSize {
    return CGSizeMake(kContentSizeDimension, kContentSizeDimension);
}

- (void)setSelected:(BOOL)selected {
    [super setSelected:selected];
    _contentView.selected = selected;
}

- (void)setCustomization:(STDSSelectionCustomization *)customization {
    _contentView.customization = customization;
}

- (STDSSelectionCustomization *)customization {
    return _contentView.customization;
}

- (void)setIsCheckbox:(BOOL)isCheckbox {
    _contentView.isCheckbox = isCheckbox;
}

- (BOOL)isCheckbox {
    return _contentView.isCheckbox;
}

@end


text:
    <input type="text" ng-model="search" placeholder="Search events">

            {{ link.title }}

           Expiration: {{ link.expiration |  date : format : timezone}}

           People needed: {{ link.thresholdPeople - link.committedPeople }}

       Cost per person: ${{ link.thresholdMoney / link.thresholdPeople | number:2 }}

       Remaining money needed: ${{ link.thresholdMoney - (link.committedPeople * (link.thresholdMoney / link.thresholdPeople)) | number:2}}


text:
from functools import wraps

from flask import redirect, session, url_for

def login_required(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        if session.get('logged_in', False):
            return f(*args, **kwargs)
        return redirect(url_for('public.login'))
    return wrapper


text:
<?php

namespace Ivory\Tests\OrderedForm;

use Ivory\OrderedForm\OrderedResolvedFormTypeFactory;

/**
 * Ordered resolved form type factory test.
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class OrderedResolvedFormTypeFactoryTest extends \PHPUnit_Framework_TestCase
{
    /** @var \Ivory\OrderedForm\OrderedResolvedFormTypeFactory */
    protected $resolvedFactory;

    /** @var \Ivory\OrderedForm\Orderer\FormOrdererFactoryInterface */
    protected $orderer;

    /**
     * {@inheritdoc}
     */
    protected function setUp()
    {
        $this->orderer = $this->getMock('Ivory\OrderedForm\Orderer\FormOrdererInterface');
        $this->resolvedFactory = new OrderedResolvedFormTypeFactory($this->orderer);
    }

    /**
     * {@inheritdoc}
     */
    protected function tearDown()
    {
        unset($this->orderer);
        unset($this->resolvedFactory);
    }

    public function testCreateWithOrderer()
    {
        $this->assertInstanceOf(
            'Ivory\OrderedForm\OrderedResolvedFormType',
            $this->resolvedFactory->createResolvedType($this->createFormType(), array())
        );
    }

    public function testCreateWithoutOrderer()
    {
        $this->resolvedFactory = new OrderedResolvedFormTypeFactory();

        $this->assertInstanceOf(
            'Ivory\OrderedForm\OrderedResolvedFormType',
            $this->resolvedFactory->createResolvedType($this->createFormType(), array())
        );
    }

    /**
     * Creates a form type.
     *
     * @return \Symfony\Component\Form\FormTypeInterface The form type.
     */
    protected function createFormType()
    {
        return $this->getMock('Symfony\Component\Form\FormTypeInterface');
    }
}


text:
FROM python:2
MAINTAINER Evan Gray <evan@evanscottgray.com>

RUN 	apt-get update && apt-get upgrade -y && apt-get install -y wget git unzip tcpdump
RUN   wget http://www.secdev.org/projects/scapy/files/scapy-latest.zip && unzip scapy-latest.zip && cd scapy-2.* && python setup.py install
ADD 	./large_fragments.py /

ENTRYPOINT 	python /large_fragments.py


text:
 #-*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from openerp.addons.analytic.models import analytic
from openerp.osv import fields,osv,orm
from openerp.tools.translate import _

class project_issue(osv.osv):
    _inherit = 'project.issue'
    _description = 'project issue'

    def _hours_get(self, cr, uid, ids, field_names, args, context=None):
        res = {}
        for issue in self.browse(cr, uid, ids, context=context):
            res[issue.id] = { 'progress' : issue.task_id.progress or 0.0 }
        return res

    def _get_issue_task(self, cr, uid, task_ids, context=None):
        return self.pool['project.issue'].search(cr, uid, [('task_id', 'in', task_ids)], context=context)

    _columns = {
        'progress': fields.function(_hours_get, string='Progress (%)', multi='line_id', group_operator="avg", help="Computed as: Time Spent / Total Time.",
            store = {
                'project.issue': (lambda self, cr, uid, ids, c={}: ids, ['task_id'], 10),
                'project.task': (_get_issue_task, ['progress'], 10),
            }),
        'timesheet_ids': fields.one2many('account.analytic.line', 'issue_id', 'Timesheets'),
        'analytic_account_id': fields.many2one('account.analytic.account', 'Analytic Account'),
    }

    def on_change_project(self, cr, uid, ids, project_id, context=None):
        if not project_id:
            return {'value': {'analytic_account_id': False}}

        result = super(project_issue, self).on_change_project(cr, uid, ids, project_id, context=context)

        project = self.pool.get('project.project').browse(cr, uid, project_id, context=context)
        if 'value' not in result:
            result['value'] = {}

        account = project.analytic_account_id
        if account:
            result['value']['analytic_account_id'] = account.id

        return result

class account_analytic_line(osv.osv):
    _inherit = 'account.analytic.line'
    _description = 'account analytic line'
    _columns = {
        'issue_id' : fields.many2one('project.issue', 'Issue'),
    }


text:
require 'thread'

module AWS
  module Core

    # Provides lazy creation of error classes via {#const_missing}.
    #
    # Extend this module provides 3 benefits to another module:
    #
    # * A method that accepts strings and returns error classes.
    # * Thread-safe dynamic error class creation via {#const_missing}
    # * An error grammar for parsing AWS xml errors
    #
    # Here is an example of how it works:
    #
    #     Class Foo
    #       module Errors
    #         extend AWS::Core::LazyErrorClasses
    #       end
    #     end
    #
    #     Foo::Errors.error_class('NoSuchKey')
    #     #=> Foo::Errors::NoSuckKey
    #
    #     Foo::Errors.error_class('Nested.Error.Klasses')
    #     #=> Foo::Errors::Nested::Error::Klasses
    #
    # The errors returned from {#error_class} are subclasses
    # of {AWS::Errors::Base}.
    #
    module LazyErrorClasses

      # This grammar parses the defualt AWS XML error format
      BASE_ERROR_GRAMMAR = XML::Grammar.customize do
        element("Error") do
          ignore
        end
      end

      # @api private
      def self.extended base

        unless base.const_defined?(:GRAMMAR)
          base.const_set(:GRAMMAR, BASE_ERROR_GRAMMAR)
        end

        mutex = Mutex.new
        MetaUtils.extend_method(base, :const_missing_mutex) { mutex }

      end

      # Defines a new error class.
      # @param [String,Symbol] constant
      # @return [nil]
      def const_missing constant
        const_missing_mutex.synchronize do
          const_set(constant, Class.new(Errors::Base) { extend LazyErrorClasses })
        end
      end

      # Converts the error code into an error class constant.
      #
      #     AWS::EC2::Errors.error_class('Non.Existent.Error')
      #     #=> AWS::EC2::Errors::Non::Existent::Error
      #
      # @param [String] code An AWS error code.
      #
      # @return [Class] Returns the error class defiend by the error code.
      #
      def error_class code
        module_eval("#{self}::#{code.gsub('.Range','Range').gsub(".","::")}")
      end

    end

  end
end