text:
using J2N.Collections.Generic.Extensions;
using J2N.Text;
using J2N.Threading;
using J2N.Threading.Atomic;
using Lucene.Net.Analysis;
using Lucene.Net.Codecs;
using Lucene.Net.Codecs.Lucene46;
using Lucene.Net.Codecs.SimpleText;
using Lucene.Net.Documents;
using Lucene.Net.Documents.Extensions;
using Lucene.Net.Index.Extensions;
using Lucene.Net.Randomized.Generators;
using Lucene.Net.Search;
using Lucene.Net.Store;
using Lucene.Net.Support;
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using JCG = J2N.Collections.Generic;
using Console = Lucene.Net.Util.SystemConsole;
using Assert = Lucene.Net.TestFramework.Assert;

#if TESTFRAMEWORK_MSTEST
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#elif TESTFRAMEWORK_NUNIT
using Test = NUnit.Framework.TestAttribute;
#elif TESTFRAMEWORK_XUNIT
using Test = Lucene.Net.TestFramework.SkippableFactAttribute;
#endif

namespace Lucene.Net.Index
{

    /// <summary>
    /// Base class aiming at testing <see cref="Codecs.StoredFieldsFormat"/>.
    /// To test a new format, all you need is to register a new <see cref="Codec"/> which
    /// uses it and extend this class and override <see cref="BaseIndexFileFormatTestCase.GetCodec()"/>.
    /// <para/>
    /// @lucene.experimental
    /// </summary>
    public abstract class BaseStoredFieldsFormatTestCase : BaseIndexFileFormatTestCase
#if TESTFRAMEWORK_XUNIT
        , Xunit.IClassFixture<BeforeAfterClass>
    {
        public BaseStoredFieldsFormatTestCase(BeforeAfterClass beforeAfter)
            : base(beforeAfter)
        {
        }
#else
    {
#endif
        protected override void AddRandomFields(Document d)
        {
            int numValues = Random.Next(3);
            for (int i = 0; i < numValues; ++i)
            {
                d.Add(new StoredField("f", TestUtil.RandomSimpleString(Random, 100)));
            }
        }

        [Test]
        public virtual void TestRandomStoredFields()
        {
            using (Directory dir = NewDirectory())
            {
                Random rand = Random;
                using (RandomIndexWriter w = new RandomIndexWriter(rand, dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMaxBufferedDocs(TestUtil.NextInt32(rand, 5, 20))))
                {
                    //w.w.setNoCFSRatio(0.0);
                    int docCount = AtLeast(200);
                    int fieldCount = TestUtil.NextInt32(rand, 1, 5);

                    IList<int?> fieldIDs = new List<int?>();

                    FieldType customType = new FieldType(TextField.TYPE_STORED);
                    customType.IsTokenized = false;
                    Field idField = NewField("id", "", customType);

                    for (int i = 0; i < fieldCount; i++)
                    {
                        fieldIDs.Add(i);
                    }

                    IDictionary<string, Document> docs = new Dictionary<string, Document>();

                    if (Verbose)
                    {
                        Console.WriteLine("TEST: build index docCount=" + docCount);
                    }

                    FieldType customType2 = new FieldType();
                    customType2.IsStored = true;
                    for (int i = 0; i < docCount; i++)
                    {
                        Document doc = new Document();
                        doc.Add(idField);
                        string id = "" + i;
                        idField.SetStringValue(id);
                        docs[id] = doc;
                        if (Verbose)
                        {
                            Console.WriteLine("TEST: add doc id=" + id);
                        }

                        foreach (int field in fieldIDs)
                        {
                            string s;
                            if (rand.Next(4) != 3)
                            {
                                s = TestUtil.RandomUnicodeString(rand, 1000);
                                doc.Add(NewField("f" + field, s, customType2));
                            }
                            else
                            {
                                s = null;
                            }
                        }
                        w.AddDocument(doc);
                        if (rand.Next(50) == 17)
                        {
                            // mixup binding of field name -> Number every so often
                            fieldIDs.Shuffle(Random);
                        }
                        if (rand.Next(5) == 3 && i > 0)
                        {
                            string delID = "" + rand.Next(i);
                            if (Verbose)
                            {
                                Console.WriteLine("TEST: delete doc id=" + delID);
                            }
                            w.DeleteDocuments(new Term("id", delID));
                            docs.Remove(delID);
                        }
                    }

                    if (Verbose)
                    {
                        Console.WriteLine("TEST: " + docs.Count + " docs in index; now load fields");
                    }
                    if (docs.Count > 0)
                    {
                        string[] idsList = docs.Keys.ToArray(/*new string[docs.Count]*/);

                        for (int x = 0; x < 2; x++)
                        {
                            using (IndexReader r = w.GetReader())
                            {
                                IndexSearcher s = NewSearcher(r);

                                if (Verbose)
                                {
                                    Console.WriteLine("TEST: cycle x=" + x + " r=" + r);
                                }

                                int num = AtLeast(1000);
                                for (int iter = 0; iter < num; iter++)
                                {
                                    string testID = idsList[rand.Next(idsList.Length)];
                                    if (Verbose)
                                    {
                                        Console.WriteLine("TEST: test id=" + testID);
                                    }
                                    TopDocs hits = s.Search(new TermQuery(new Term("id", testID)), 1);
                                    Assert.AreEqual(1, hits.TotalHits);
                                    Document doc = r.Document(hits.ScoreDocs[0].Doc);
                                    Document docExp = docs[testID];
                                    for (int i = 0; i < fieldCount; i++)
                                    {
                                        assertEquals("doc " + testID + ", field f" + fieldCount + " is wrong", docExp.Get("f" + i), doc.Get("f" + i));
                                    }
                                }
                            } // r.Dispose();
                            w.ForceMerge(1);
                        }
                    }
                } // w.Dispose();
            } // dir.Dispose();
        }

        [Test]
        // LUCENE-1727: make sure doc fields are stored in order
        public virtual void TestStoredFieldsOrder()
        {
            using (Directory d = NewDirectory())
            using (IndexWriter w = new IndexWriter(d, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))))
            {
                Document doc = new Document();

                FieldType customType = new FieldType();
                customType.IsStored = true;
                doc.Add(NewField("zzz", "a b c", customType));
                doc.Add(NewField("aaa", "a b c", customType));
                doc.Add(NewField("zzz", "1 2 3", customType));
                w.AddDocument(doc);
                using (IndexReader r = w.GetReader())
                {
                    Document doc2 = r.Document(0);
                    IEnumerator<IIndexableField> it = doc2.Fields.GetEnumerator();
                    Assert.IsTrue(it.MoveNext());
                    Field f = (Field)it.Current;
                    Assert.AreEqual(f.Name, "zzz");
                    Assert.AreEqual(f.GetStringValue(), "a b c");

                    Assert.IsTrue(it.MoveNext());
                    f = (Field)it.Current;
                    Assert.AreEqual(f.Name, "aaa");
                    Assert.AreEqual(f.GetStringValue(), "a b c");

                    Assert.IsTrue(it.MoveNext());
                    f = (Field)it.Current;
                    Assert.AreEqual(f.Name, "zzz");
                    Assert.AreEqual(f.GetStringValue(), "1 2 3");
                    Assert.IsFalse(it.MoveNext());
                } // r.Dispose();
            } // w.Dispose();, d.Dispose();
        }

        [Test]
        // LUCENE-1219
        public virtual void TestBinaryFieldOffsetLength()
        {
            using (Directory dir = NewDirectory())
            {
                var b = new byte[50];
                using (IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))))
                {
                    for (int i = 0; i < 50; i++)
                    {
                        b[i] = (byte)(i + 77);
                    }

                    Document doc = new Document();
                    Field f = new StoredField("binary", b, 10, 17);
                    var bx = f.GetBinaryValue().Bytes;
                    Assert.IsTrue(bx != null);
                    Assert.AreEqual(50, bx.Length);
                    Assert.AreEqual(10, f.GetBinaryValue().Offset);
                    Assert.AreEqual(17, f.GetBinaryValue().Length);
                    doc.Add(f);
                    w.AddDocument(doc);
                } // w.Dispose();

                using (IndexReader ir = DirectoryReader.Open(dir))
                {
                    Document doc2 = ir.Document(0);
                    IIndexableField f2 = doc2.GetField("binary");
                    b = f2.GetBinaryValue().Bytes;
                    Assert.IsTrue(b != null);
                    Assert.AreEqual(17, b.Length, 17);
                    Assert.AreEqual((byte)87, b[0]);
                } // ir.Dispose();
            } // dir.Dispose();
        }

        [Test]
        public virtual void TestNumericField()
        {
            using (Directory dir = NewDirectory())
            {
                DirectoryReader r = null;
                try
                {
                    var numDocs = AtLeast(500);
                    var answers = new object[numDocs];
                    using (var w = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
                        this,
#endif
                        Random, dir))
                    {
                        NumericType[] typeAnswers = new NumericType[numDocs];
                        for (int id = 0; id < numDocs; id++)
                        {
                            Document doc = new Document();
                            Field nf;
                            Field sf;
                            object answer;
                            NumericType typeAnswer;
                            if (Random.NextBoolean())
                            {
                                // float/double
                                if (Random.NextBoolean())
                                {
                                    float f = Random.NextSingle();
                                    answer = Convert.ToSingle(f, CultureInfo.InvariantCulture);
                                    nf = new SingleField("nf", f, Field.Store.NO);
                                    sf = new StoredField("nf", f);
                                    typeAnswer = NumericType.SINGLE;
                                }
                                else
                                {
                                    double d = Random.NextDouble();
                                    answer = Convert.ToDouble(d, CultureInfo.InvariantCulture);
                                    nf = new DoubleField("nf", d, Field.Store.NO);
                                    sf = new StoredField("nf", d);
                                    typeAnswer = NumericType.DOUBLE;
                                }
                            }
                            else
                            {
                                // int/long
                                if (Random.NextBoolean())
                                {
                                    int i = Random.Next();
                                    answer = Convert.ToInt32(i, CultureInfo.InvariantCulture);
                                    nf = new Int32Field("nf", i, Field.Store.NO);
                                    sf = new StoredField("nf", i);
                                    typeAnswer = NumericType.INT32;
                                }
                                else
                                {
                                    long l = Random.NextInt64();
                                    answer = Convert.ToInt64(l, CultureInfo.InvariantCulture);
                                    nf = new Int64Field("nf", l, Field.Store.NO);
                                    sf = new StoredField("nf", l);
                                    typeAnswer = NumericType.INT64;
                                }
                            }
                            doc.Add(nf);
                            doc.Add(sf);
                            answers[id] = answer;
                            typeAnswers[id] = typeAnswer;
                            FieldType ft = new FieldType(Int32Field.TYPE_STORED);
                            ft.NumericPrecisionStep = int.MaxValue;
                            doc.Add(new Int32Field("id", id, ft));
                            w.AddDocument(doc);
                        }
                        r = w.GetReader();
                    } // w.Dispose();

                    Assert.AreEqual(numDocs, r.NumDocs);

                    foreach (AtomicReaderContext ctx in r.Leaves)
                    {
                        AtomicReader sub = ctx.AtomicReader; // LUCENENET TODO: Dispose() ?
                        FieldCache.Int32s ids = FieldCache.DEFAULT.GetInt32s(sub, "id", false);
                        for (int docID = 0; docID < sub.NumDocs; docID++)
                        {
                            Document doc = sub.Document(docID);
                            Field f = doc.GetField<Field>("nf");
                            Assert.IsTrue(f is StoredField, "got f=" + f);
#pragma warning disable 612, 618
                            Assert.AreEqual(answers[ids.Get(docID)], f.GetNumericValue());
#pragma warning restore 612, 618
                        }
                    }
                }
                finally
                {
                    r?.Dispose();
                }
            } // dir.Dispose();
        }

        [Test]
        public virtual void TestIndexedBit()
        {
            using (Directory dir = NewDirectory())
            {
                IndexReader r = null;
                try
                {
                    using (RandomIndexWriter w = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
                        this,
#endif
                        Random, dir))
                    {
                        Document doc = new Document();
                        FieldType onlyStored = new FieldType();
                        onlyStored.IsStored = true;
                        doc.Add(new Field("field", "value", onlyStored));
                        doc.Add(new StringField("field2", "value", Field.Store.YES));
                        w.AddDocument(doc);
                        r = w.GetReader();
                    } // w.Dispose();
                    Assert.IsFalse(r.Document(0).GetField("field").IndexableFieldType.IsIndexed);
                    Assert.IsTrue(r.Document(0).GetField("field2").IndexableFieldType.IsIndexed);
                }
                finally
                {
                    r?.Dispose();
                }
            } // dir.Dispose();
        }

        [Test]
        public virtual void TestReadSkip()
        {
            using (Directory dir = NewDirectory())
            {
                IndexWriterConfig iwConf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random));
                iwConf.SetMaxBufferedDocs(RandomInts.RandomInt32Between(Random, 2, 30));
                using (RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwConf))
                {

                    FieldType ft = new FieldType();
                    ft.IsStored = true;
                    ft.Freeze();

                    string @string = TestUtil.RandomSimpleString(Random, 50);
                    var bytes = @string.GetBytes(Encoding.UTF8);
                    long l = Random.NextBoolean() ? Random.Next(42) : Random.NextInt64();
                    int i = Random.NextBoolean() ? Random.Next(42) : Random.Next();
                    float f = Random.NextSingle();
                    double d = Random.NextDouble();

                    Field[] fields = new Field[]
                    {
                        new Field("bytes", bytes, ft),
                        new Field("string", @string, ft),
                        new Int64Field("long", l, Field.Store.YES),
                        new Int32Field("int", i, Field.Store.YES),
                        new SingleField("float", f, Field.Store.YES),
                        new DoubleField("double", d, Field.Store.YES)
                    };

                    for (int k = 0; k < 100; ++k)
                    {
                        Document doc = new Document();
                        foreach (Field fld in fields)
                        {
                            doc.Add(fld);
                        }
                        iw.IndexWriter.AddDocument(doc);
                    }
                    iw.Commit();

                    using (DirectoryReader reader = DirectoryReader.Open(dir))
                    {
                        int docID = Random.Next(100);
                        foreach (Field fld in fields)
                        {
                            string fldName = fld.Name;
                            Document sDoc = reader.Document(docID, new JCG.HashSet<string> { fldName });
                            IIndexableField sField = sDoc.GetField(fldName);
                            if (typeof(Field) == fld.GetType())
                            {
                                Assert.AreEqual(fld.GetBinaryValue(), sField.GetBinaryValue());
                                Assert.AreEqual(fld.GetStringValue(), sField.GetStringValue());
                            }
                            else
                            {
#pragma warning disable 612, 618
                                Assert.AreEqual(fld.GetNumericValue(), sField.GetNumericValue());
#pragma warning restore 612, 618
                            }
                        }
                    } // reader.Dispose();
                } // iw.Dispose();
            } // dir.Dispose();
        }

        [Test]
        public virtual void TestEmptyDocs()
        {
            using (Directory dir = NewDirectory())
            {
                IndexWriterConfig iwConf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random));
                iwConf.SetMaxBufferedDocs(RandomInts.RandomInt32Between(Random, 2, 30));
                using (RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwConf))
                {

                    // make sure that the fact that documents might be empty is not a problem
                    Document emptyDoc = new Document();
                    int numDocs = Random.NextBoolean() ? 1 : AtLeast(1000);
                    for (int i = 0; i < numDocs; ++i)
                    {
                        iw.AddDocument(emptyDoc);
                    }
                    iw.Commit();
                    using (DirectoryReader rd = DirectoryReader.Open(dir))
                    {
                        for (int i = 0; i < numDocs; ++i)
                        {
                            Document doc = rd.Document(i);
                            Assert.IsNotNull(doc);
                            Assert.IsTrue(doc.Fields.Count <= 0);
                        }
                    } // rd.Dispose();

                } // iw.Dispose();
            } // dir.Dispose();
        }

        [Test]
        public virtual void TestConcurrentReads()
        {
            using (Directory dir = NewDirectory())
            {
                IndexWriterConfig iwConf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random));
                iwConf.SetMaxBufferedDocs(RandomInts.RandomInt32Between(Random, 2, 30));
                using (RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwConf))
                {

                    // make sure the readers are properly cloned
                    Document doc = new Document();
                    Field field = new StringField("fld", "", Field.Store.YES);
                    doc.Add(field);
                    int numDocs = AtLeast(1000);
                    for (int i = 0; i < numDocs; ++i)
                    {
                        field.SetStringValue("" + i);
                        iw.AddDocument(doc);
                    }
                    iw.Commit();

                    AtomicReference<Exception> ex = new AtomicReference<Exception>();
                    using (DirectoryReader rd = DirectoryReader.Open(dir))
                    {
                        IndexSearcher searcher = new IndexSearcher(rd);
                        int concurrentReads = AtLeast(5);
                        int readsPerThread = AtLeast(50);
                        IList<ThreadJob> readThreads = new List<ThreadJob>();

                        for (int i = 0; i < concurrentReads; ++i)
                        {
                            readThreads.Add(new ThreadAnonymousInnerClassHelper(numDocs, rd, searcher, readsPerThread, ex, i));
                        }
                        foreach (ThreadJob thread in readThreads)
                        {
                            thread.Start();
                        }
                        foreach (ThreadJob thread in readThreads)
                        {
                            thread.Join();
                        }
                    } // rd.Dispose();
                    if (ex.Value != null)
                    {
                        throw ex.Value;
                    }

                } // iw.Dispose();
            } // dir.Dispose();
        }

        private class ThreadAnonymousInnerClassHelper : ThreadJob
        {
            private int numDocs;
            private readonly DirectoryReader rd;
            private readonly IndexSearcher searcher;
            private int readsPerThread;
            private AtomicReference<Exception> ex;
            private int i;
            private readonly int[] queries;

            public ThreadAnonymousInnerClassHelper(int numDocs, DirectoryReader rd, IndexSearcher searcher, int readsPerThread, AtomicReference<Exception> ex, int i)
            {
                this.numDocs = numDocs;
                this.rd = rd;
                this.searcher = searcher;
                this.readsPerThread = readsPerThread;
                this.ex = ex;
                this.i = i;

                queries = new int[this.readsPerThread];
                for (int j = 0; j < queries.Length; ++j)
                {
                    queries[j] = Random.Next(this.numDocs);
                }
            }

            public override void Run()
            {
                foreach (int q in queries)
                {
                    Query query = new TermQuery(new Term("fld", "" + q));
                    try
                    {
                        TopDocs topDocs = searcher.Search(query, 1);
                        if (topDocs.TotalHits != 1)
                        {
                            Console.WriteLine(query);
                            throw new InvalidOperationException("Expected 1 hit, got " + topDocs.TotalHits);
                        }
                        Document sdoc = rd.Document(topDocs.ScoreDocs[0].Doc);
                        if (sdoc == null || sdoc.Get("fld") == null)
                        {
                            throw new InvalidOperationException("Could not find document " + q);
                        }
                        if (!Convert.ToString(q, CultureInfo.InvariantCulture).Equals(sdoc.Get("fld"), StringComparison.Ordinal))
                        {
                            throw new InvalidOperationException("Expected " + q + ", but got " + sdoc.Get("fld"));
                        }
                    }
                    catch (Exception e)
                    {
                        ex.Value = e;
                    }
                }
            }
        }

        private static byte[] RandomByteArray(int length, int max)
        {
            var result = new byte[length];
            for (int i = 0; i < length; ++i)
            {
                result[i] = (byte)Random.Next(max);
            }
            return result;
        }

        [Test]
        public virtual void TestWriteReadMerge()
        {
            // get another codec, other than the default: so we are merging segments across different codecs
            Codec otherCodec;
            if ("SimpleText".Equals(Codec.Default.Name, StringComparison.Ordinal))
            {
                otherCodec = new Lucene46Codec();
            }
            else
            {
                otherCodec = new SimpleTextCodec();
            }
            using (Directory dir = NewDirectory())
            {
                IndexWriterConfig iwConf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random));
                iwConf.SetMaxBufferedDocs(RandomInts.RandomInt32Between(Random, 2, 30));
                RandomIndexWriter iw = new RandomIndexWriter(Random, dir, (IndexWriterConfig)iwConf.Clone());
                try
                {

                    int docCount = AtLeast(200);
                    var data = new byte[docCount][][];
                    for (int i = 0; i < docCount; ++i)
                    {
                        int fieldCount = Rarely() ? RandomInts.RandomInt32Between(Random, 1, 500) : RandomInts.RandomInt32Between(Random, 1, 5);
                        data[i] = new byte[fieldCount][];
                        for (int j = 0; j < fieldCount; ++j)
                        {
                            int length = Rarely() ? Random.Next(1000) : Random.Next(10);
                            int max = Rarely() ? 256 : 2;
                            data[i][j] = RandomByteArray(length, max);
                        }
                    }

                    FieldType type = new FieldType(StringField.TYPE_STORED);
                    type.IsIndexed = false;
                    type.Freeze();
                    Int32Field id = new Int32Field("id", 0, Field.Store.YES);
                    for (int i = 0; i < data.Length; ++i)
                    {
                        Document doc = new Document();
                        doc.Add(id);
                        id.SetInt32Value(i);
                        for (int j = 0; j < data[i].Length; ++j)
                        {
                            Field f = new Field("bytes" + j, data[i][j], type);
                            doc.Add(f);
                        }
                        iw.IndexWriter.AddDocument(doc);
                        if (Random.NextBoolean() && (i % (data.Length / 10) == 0))
                        {
                            iw.IndexWriter.Dispose();
                            // test merging against a non-compressing codec
                            if (iwConf.Codec == otherCodec)
                            {
                                iwConf.SetCodec(Codec.Default);
                            }
                            else
                            {
                                iwConf.SetCodec(otherCodec);
                            }
                            iw = new RandomIndexWriter(Random, dir, (IndexWriterConfig)iwConf.Clone());
                        }
                    }

                    for (int i = 0; i < 10; ++i)
                    {
                        int min = Random.Next(data.Length);
                        int max = min + Random.Next(20);
                        iw.DeleteDocuments(NumericRangeQuery.NewInt32Range("id", min, max, true, false));
                    }

                    iw.ForceMerge(2); // force merges with deletions

                    iw.Commit();

                    using (DirectoryReader ir = DirectoryReader.Open(dir))
                    {
                        Assert.IsTrue(ir.NumDocs > 0);
                        int numDocs = 0;
                        for (int i = 0; i < ir.MaxDoc; ++i)
                        {
                            Document doc = ir.Document(i);
                            if (doc == null)
                            {
                                continue;
                            }
                            ++numDocs;
                            int docId = (int)doc.GetField("id").GetInt32Value();
                            Assert.AreEqual(data[docId].Length + 1, doc.Fields.Count);
                            for (int j = 0; j < data[docId].Length; ++j)
                            {
                                var arr = data[docId][j];
                                BytesRef arr2Ref = doc.GetBinaryValue("bytes" + j);
                                var arr2 = Arrays.CopyOfRange(arr2Ref.Bytes, arr2Ref.Offset, arr2Ref.Offset + arr2Ref.Length);
                                Assert.AreEqual(arr, arr2);
                            }
                        }
                        Assert.IsTrue(ir.NumDocs <= numDocs);
                    } // ir.Dispose();

                    iw.DeleteAll();
                    iw.Commit();
                    iw.ForceMerge(1);

                }
                finally
                {
                    iw.Dispose();
                }
            } // dir.Dispose();
        }

        [Test]
        [Nightly]
        public virtual void TestBigDocuments()
        {
            // "big" as "much bigger than the chunk size"
            // for this test we force a FS dir
            // we can't just use newFSDirectory, because this test doesn't really index anything.
            // so if we get NRTCachingDir+SimpleText, we make massive stored fields and OOM (LUCENE-4484)
            using (Directory dir = new MockDirectoryWrapper(Random, new MMapDirectory(CreateTempDir("testBigDocuments"))))
            {
                IndexWriterConfig iwConf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random));
                iwConf.SetMaxBufferedDocs(RandomInts.RandomInt32Between(Random, 2, 30));
                using (RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwConf))
                {

                    if (dir is MockDirectoryWrapper)
                    {
                        ((MockDirectoryWrapper)dir).Throttling = Throttling.NEVER;
                    }

                    Document emptyDoc = new Document(); // emptyDoc
                    Document bigDoc1 = new Document(); // lot of small fields
                    Document bigDoc2 = new Document(); // 1 very big field

                    Field idField = new StringField("id", "", Field.Store.NO);
                    emptyDoc.Add(idField);
                    bigDoc1.Add(idField);
                    bigDoc2.Add(idField);

                    FieldType onlyStored = new FieldType(StringField.TYPE_STORED);
                    onlyStored.IsIndexed = false;

                    Field smallField = new Field("fld", RandomByteArray(Random.Next(10), 256), onlyStored);
                    int numFields = RandomInts.RandomInt32Between(Random, 500000, 1000000);
                    for (int i = 0; i < numFields; ++i)
                    {
                        bigDoc1.Add(smallField);
                    }

                    Field bigField = new Field("fld", RandomByteArray(RandomInts.RandomInt32Between(Random, 1000000, 5000000), 2), onlyStored);
                    bigDoc2.Add(bigField);

                    int numDocs = AtLeast(5);
                    Document[] docs = new Document[numDocs];
                    for (int i = 0; i < numDocs; ++i)
                    {
                        docs[i] = RandomPicks.RandomFrom(Random, new Document[] { emptyDoc, bigDoc1, bigDoc2 });
                    }
                    for (int i = 0; i < numDocs; ++i)
                    {
                        idField.SetStringValue("" + i);
                        iw.AddDocument(docs[i]);
                        if (Random.Next(numDocs) == 0)
                        {
                            iw.Commit();
                        }
                    }
                    iw.Commit();
                    iw.ForceMerge(1); // look at what happens when big docs are merged
                    using (DirectoryReader rd = DirectoryReader.Open(dir))
                    {
                        IndexSearcher searcher = new IndexSearcher(rd);
                        for (int i = 0; i < numDocs; ++i)
                        {
                            Query query = new TermQuery(new Term("id", "" + i));
                            TopDocs topDocs = searcher.Search(query, 1);
                            Assert.AreEqual(1, topDocs.TotalHits, "" + i);
                            Document doc = rd.Document(topDocs.ScoreDocs[0].Doc);
                            Assert.IsNotNull(doc);
                            IIndexableField[] fieldValues = doc.GetFields("fld");
                            Assert.AreEqual(docs[i].GetFields("fld").Length, fieldValues.Length);
                            if (fieldValues.Length > 0)
                            {
                                Assert.AreEqual(docs[i].GetFields("fld")[0].GetBinaryValue(), fieldValues[0].GetBinaryValue());
                            }
                        }
                    } // rd.Dispose();
                } // iw.Dispose();
            } // dir.Dispose();
        }

        [Test]
        public virtual void TestBulkMergeWithDeletes()
        {
            int numDocs = AtLeast(200);
            using (Directory dir = NewDirectory())
            {
                RandomIndexWriter w = new RandomIndexWriter(Random, dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMergePolicy(NoMergePolicy.COMPOUND_FILES));
                try
                {
                    for (int i = 0; i < numDocs; ++i)
                    {
                        Document doc = new Document();
                        doc.Add(new StringField("id", Convert.ToString(i, CultureInfo.InvariantCulture), Field.Store.YES));
                        doc.Add(new StoredField("f", TestUtil.RandomSimpleString(Random)));
                        w.AddDocument(doc);
                    }
                    int deleteCount = TestUtil.NextInt32(Random, 5, numDocs);
                    for (int i = 0; i < deleteCount; ++i)
                    {
                        int id = Random.Next(numDocs);
                        w.DeleteDocuments(new Term("id", Convert.ToString(id, CultureInfo.InvariantCulture)));
                    }
                    w.Commit();
                    w.Dispose();
                    w = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
                        this,
#endif
                        Random, dir);
                    w.ForceMerge(TestUtil.NextInt32(Random, 1, 3));
                    w.Commit();
                }
                finally
                {
                    w.Dispose();
                }
                TestUtil.CheckIndex(dir);
            } // dir.Dispose();
        }
    }
}


text:
using System;
using System.ComponentModel;

namespace Azure.ResourceManager.AppContainers.Models
{
    /// <summary> Provisioning state of the Environment. </summary>
    public readonly partial struct EnvironmentProvisioningState : IEquatable<EnvironmentProvisioningState>
    {
        private readonly string _value;

        /// <summary> Initializes a new instance of <see cref="EnvironmentProvisioningState"/>. </summary>
        /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
        public EnvironmentProvisioningState(string value)
        {
            _value = value ?? throw new ArgumentNullException(nameof(value));
        }

        private const string SucceededValue = "Succeeded";
        private const string FailedValue = "Failed";
        private const string CanceledValue = "Canceled";
        private const string WaitingValue = "Waiting";
        private const string InitializationInProgressValue = "InitializationInProgress";
        private const string InfrastructureSetupInProgressValue = "InfrastructureSetupInProgress";
        private const string InfrastructureSetupCompleteValue = "InfrastructureSetupComplete";
        private const string ScheduledForDeleteValue = "ScheduledForDelete";
        private const string UpgradeRequestedValue = "UpgradeRequested";
        private const string UpgradeFailedValue = "UpgradeFailed";

        /// <summary> Succeeded. </summary>
        public static EnvironmentProvisioningState Succeeded { get; } = new EnvironmentProvisioningState(SucceededValue);
        /// <summary> Failed. </summary>
        public static EnvironmentProvisioningState Failed { get; } = new EnvironmentProvisioningState(FailedValue);
        /// <summary> Canceled. </summary>
        public static EnvironmentProvisioningState Canceled { get; } = new EnvironmentProvisioningState(CanceledValue);
        /// <summary> Waiting. </summary>
        public static EnvironmentProvisioningState Waiting { get; } = new EnvironmentProvisioningState(WaitingValue);
        /// <summary> InitializationInProgress. </summary>
        public static EnvironmentProvisioningState InitializationInProgress { get; } = new EnvironmentProvisioningState(InitializationInProgressValue);
        /// <summary> InfrastructureSetupInProgress. </summary>
        public static EnvironmentProvisioningState InfrastructureSetupInProgress { get; } = new EnvironmentProvisioningState(InfrastructureSetupInProgressValue);
        /// <summary> InfrastructureSetupComplete. </summary>
        public static EnvironmentProvisioningState InfrastructureSetupComplete { get; } = new EnvironmentProvisioningState(InfrastructureSetupCompleteValue);
        /// <summary> ScheduledForDelete. </summary>
        public static EnvironmentProvisioningState ScheduledForDelete { get; } = new EnvironmentProvisioningState(ScheduledForDeleteValue);
        /// <summary> UpgradeRequested. </summary>
        public static EnvironmentProvisioningState UpgradeRequested { get; } = new EnvironmentProvisioningState(UpgradeRequestedValue);
        /// <summary> UpgradeFailed. </summary>
        public static EnvironmentProvisioningState UpgradeFailed { get; } = new EnvironmentProvisioningState(UpgradeFailedValue);
        /// <summary> Determines if two <see cref="EnvironmentProvisioningState"/> values are the same. </summary>
        public static bool operator ==(EnvironmentProvisioningState left, EnvironmentProvisioningState right) => left.Equals(right);
        /// <summary> Determines if two <see cref="EnvironmentProvisioningState"/> values are not the same. </summary>
        public static bool operator !=(EnvironmentProvisioningState left, EnvironmentProvisioningState right) => !left.Equals(right);
        /// <summary> Converts a string to a <see cref="EnvironmentProvisioningState"/>. </summary>
        public static implicit operator EnvironmentProvisioningState(string value) => new EnvironmentProvisioningState(value);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool Equals(object obj) => obj is EnvironmentProvisioningState other && Equals(other);
        /// <inheritdoc />
        public bool Equals(EnvironmentProvisioningState other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override int GetHashCode() => _value?.GetHashCode() ?? 0;
        /// <inheritdoc />
        public override string ToString() => _value;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package azurerm

import (
	"fmt"
	"testing"

	"github.com/hashicorp/terraform/helper/acctest"
	"github.com/hashicorp/terraform/helper/resource"
)

func TestAccAzureRMSqlFirewallRule_importBasic(t *testing.T) {
	resourceName := "azurerm_sql_firewall_rule.test"

	ri := acctest.RandInt()
	config := fmt.Sprintf(testAccAzureRMSqlFirewallRule_basic, ri, ri, ri)

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testCheckAzureRMSqlFirewallRuleDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: config,
			},

			resource.TestStep{
				ResourceName:      resourceName,
				ImportState:       true,
				ImportStateVerify: true,
			},
		},
	})
}


text:
arguments_t::arguments_t() :
    managed_application(_X("")),
    own_path(_X("")),
    app_dir(_X("")),
    app_argc(0),
    app_argv(nullptr),
    dotnet_packages_cache(_X("")),
    dotnet_extensions(_X("")),
    deps_path(_X(""))
{
}

bool parse_arguments(const pal::string_t& deps_path, const std::vector<pal::string_t>& probe_paths, host_mode_t mode,
    const int argc, const pal::char_t* argv[], arguments_t* arg_out)
{
    arguments_t& args = *arg_out;
    // Get the full name of the application
    if (!pal::get_own_executable_path(&args.own_path) || !pal::realpath(&args.own_path))
    {
        trace::error(_X("Failed to locate current executable"));
        return false;
    }

    auto own_name = get_filename(args.own_path);
    auto own_dir = get_directory(args.own_path);

    if (mode != host_mode_t::standalone)
    {
        // corerun mode. First argument is managed app
        if (argc < 2)
        {
            return false;
        }
        args.managed_application = pal::string_t(argv[1]);
        if (!pal::realpath(&args.managed_application))
        {
            trace::error(_X("Failed to locate managed application: %s"), args.managed_application.c_str());
            return false;
        }
        args.app_dir = get_directory(args.managed_application);
        args.app_argc = argc - 2;
        args.app_argv = &argv[2];
    }
    else
    {
        // coreconsole mode. Find the managed app in the same directory
        pal::string_t managed_app(own_dir);
        managed_app.push_back(DIR_SEPARATOR);
        managed_app.append(get_executable(own_name));
        managed_app.append(_X(".dll"));
        args.managed_application = managed_app;
        if (!pal::realpath(&args.managed_application))
        {
            trace::error(_X("Failed to locate managed application: %s"), args.managed_application.c_str());
            return false;
        }
        args.app_dir = own_dir;
        args.app_argv = &argv[1];
        args.app_argc = argc - 1;
    }

    std::unordered_map<pal::string_t, std::vector<pal::string_t>> opts;
    std::vector<pal::string_t> known_opts = { _X("--depsfile"), _X("--additionalprobingpath") };
    int num_args = 0;
    if (!parse_known_args(args.app_argc, args.app_argv, known_opts, &opts, &num_args))
    {
        return false;
    }

    args.app_argc -= num_args;
    args.app_argv += num_args;
    pal::string_t opts_deps_file = _X("--depsfile");
    pal::string_t opts_probe_path = _X("--additionalprobingpath");
    pal::string_t deps_file = get_last_known_arg(opts, opts_deps_file, deps_path);
    if (opts.count(opts_probe_path))
    {
        for (const auto& str : opts[opts_probe_path])
        {
            args.probe_paths.push_back(str);
        }
    }

    if (!deps_file.empty())
    {
        args.deps_path = deps_file;
        args.app_dir = get_directory(args.deps_path);
    }

    for (const auto& probe : probe_paths)
    {
        args.probe_paths.push_back(probe);
    }

    if (args.deps_path.empty())
    {
        const auto& app_base = args.app_dir;
        auto app_name = get_filename(args.managed_application);

        args.deps_path.reserve(app_base.length() + 1 + app_name.length() + 5);
        args.deps_path.append(app_base);
        args.deps_path.push_back(DIR_SEPARATOR);
        args.deps_path.append(app_name, 0, app_name.find_last_of(_X(".")));
        args.deps_path.append(_X(".deps.json"));
    }

    pal::getenv(_X("DOTNET_HOSTING_OPTIMIZATION_CACHE"), &args.dotnet_packages_cache);
    pal::get_default_extensions_directory(&args.dotnet_extensions);

    return true;
}


text: export { Gif20 as default } from "../../";


text:
package locus.api.android.utils;

import android.database.AbstractCursor;
import android.database.Cursor;
import android.database.CursorIndexOutOfBoundsException;

import java.util.ArrayList;

/**
 * A mutable cursor implementation backed by an array of {@code Object}s. Use
 * {@link #newRow()} to add rows. Automatically expands internal capacity
 * as needed.
 *

 * This is copy of MatrixCursor class from API25 that already fix problem with 'blob' objects
 */
public class MatrixCursor extends AbstractCursor {

    private final String[] columnNames;
    private Object[] data;
    private int rowCount = 0;
    private final int columnCount;

    /**
     * Constructs a new cursor with the given initial capacity.
     *
     * @param columnNames     names of the columns, the ordering of which
     *                        determines column ordering elsewhere in this cursor
     * @param initialCapacity in rows
     */
    public MatrixCursor(String[] columnNames, int initialCapacity) {
        this.columnNames = columnNames;
        this.columnCount = columnNames.length;

        if (initialCapacity < 1) {
            initialCapacity = 1;
        }

        this.data = new Object[columnCount * initialCapacity];
    }

    /**
     * Constructs a new cursor.
     *
     * @param columnNames names of the columns, the ordering of which
     *                    determines column ordering elsewhere in this cursor
     */
    public MatrixCursor(String[] columnNames) {
        this(columnNames, 16);
    }

    /**
     * Gets value at the given column for the current row.
     */
    private Object get(int column) {
        if (column < 0 || column >= columnCount) {
            throw new CursorIndexOutOfBoundsException("Requested column: "
                    + column + ", # of columns: " + columnCount);
        }
        if (mPos < 0) {
            throw new CursorIndexOutOfBoundsException("Before first row.");
        }
        if (mPos >= rowCount) {
            throw new CursorIndexOutOfBoundsException("After last row.");
        }
        return data[mPos * columnCount + column];
    }

    /**
     * Adds a new row to the end and returns a builder for that row. Not safe
     * for concurrent use.
     *
     * @return builder which can be used to set the column values for the new
     * row
     */
    public RowBuilder newRow() {
        final int row = rowCount++;
        final int endIndex = rowCount * columnCount;
        ensureCapacity(endIndex);
        return new RowBuilder(row);
    }

    /**
     * Adds a new row to the end with the given column values. Not safe
     * for concurrent use.
     *
     * @param columnValues in the same order as the the column names specified
     *                     at cursor construction time
     * @throws IllegalArgumentException if {@code columnValues.length !=
     *                                  columnNames.length}
     */
    public void addRow(Object[] columnValues) {
        if (columnValues.length != columnCount) {
            throw new IllegalArgumentException("columnNames.length = "
                    + columnCount + ", columnValues.length = "
                    + columnValues.length);
        }

        int start = rowCount++ * columnCount;
        ensureCapacity(start + columnCount);
        System.arraycopy(columnValues, 0, data, start, columnCount);
    }

    /**
     * Adds a new row to the end with the given column values. Not safe
     * for concurrent use.
     *
     * @param columnValues in the same order as the the column names specified
     *                     at cursor construction time
     * @throws IllegalArgumentException if {@code columnValues.size() !=
     *                                  columnNames.length}
     */
    public void addRow(Iterable<?> columnValues) {
        int start = rowCount * columnCount;
        int end = start + columnCount;
        ensureCapacity(end);

        if (columnValues instanceof ArrayList<?>) {
            addRow((ArrayList<?>) columnValues, start);
            return;
        }

        int current = start;
        Object[] localData = data;
        for (Object columnValue : columnValues) {
            if (current == end) {
                // TODO: null out row?
                throw new IllegalArgumentException(
                        "columnValues.size() > columnNames.length");
            }
            localData[current++] = columnValue;
        }

        if (current != end) {
            // TODO: null out row?
            throw new IllegalArgumentException(
                    "columnValues.size() < columnNames.length");
        }

        // Increase row count here in case we encounter an exception.
        rowCount++;
    }

    /**
     * Optimization for {@link ArrayList}.
     */
    private void addRow(ArrayList<?> columnValues, int start) {
        int size = columnValues.size();
        if (size != columnCount) {
            throw new IllegalArgumentException("columnNames.length = "
                    + columnCount + ", columnValues.size() = " + size);
        }

        rowCount++;
        Object[] localData = data;
        for (int i = 0; i < size; i++) {
            localData[start + i] = columnValues.get(i);
        }
    }

    /**
     * Ensures that this cursor has enough capacity.
     */
    private void ensureCapacity(int size) {
        if (size > data.length) {
            Object[] oldData = this.data;
            int newSize = data.length * 2;
            if (newSize < size) {
                newSize = size;
            }
            this.data = new Object[newSize];
            System.arraycopy(oldData, 0, this.data, 0, oldData.length);
        }
    }

    /**
     * Builds a row of values using either of these approaches:
     *

     *
Values can be added with explicit column ordering using
     * {@link #add(Object)}, which starts from the left-most column and adds one
     * column value at a time. This follows the same ordering as the column
     * names specified at cursor construction time.
     *
Column and value pairs can be offered for possible inclusion using
     * {@link #add(String, Object)}. If the cursor includes the given column,
     * the value will be set for that column, otherwise the value is ignored.
     * This approach is useful when matching data to a custom projection.
     *

     * Undefined values are left as {@code null}.
     */
    public class RowBuilder {
        private final int row;
        private final int endIndex;

        private int index;

        RowBuilder(int row) {
            this.row = row;
            this.index = row * columnCount;
            this.endIndex = index + columnCount;
        }

        /**
         * Sets the next column value in this row.
         */
        public RowBuilder add(Object columnValue) {
            if (index == endIndex) {
                throw new CursorIndexOutOfBoundsException(
                        "No more columns left.");
            }

            data[index++] = columnValue;
            return this;
        }

        /**
         * Offer value for possible inclusion if this cursor defines the given
         * column. Columns not defined by the cursor are silently ignored.
         */
        public RowBuilder add(String columnName, Object value) {
            for (int i = 0; i < columnNames.length; i++) {
                if (columnName.equals(columnNames[i])) {
                    data[(row * columnCount) + i] = value;
                }
            }
            return this;
        }
    }

    // AbstractCursor implementation.

    @Override
    public int getCount() {
        return rowCount;
    }

    @Override
    public String[] getColumnNames() {
        return columnNames;
    }

    @Override
    public String getString(int column) {
        Object value = get(column);
        if (value == null) return null;
        return value.toString();
    }

    @Override
    public short getShort(int column) {
        Object value = get(column);
        if (value == null) return 0;
        if (value instanceof Number) return ((Number) value).shortValue();
        return Short.parseShort(value.toString());
    }

    @Override
    public int getInt(int column) {
        Object value = get(column);
        if (value == null) return 0;
        if (value instanceof Number) return ((Number) value).intValue();
        return Integer.parseInt(value.toString());
    }

    @Override
    public long getLong(int column) {
        Object value = get(column);
        if (value == null) return 0;
        if (value instanceof Number) return ((Number) value).longValue();
        return Long.parseLong(value.toString());
    }

    @Override
    public float getFloat(int column) {
        Object value = get(column);
        if (value == null) return 0.0f;
        if (value instanceof Number) return ((Number) value).floatValue();
        return Float.parseFloat(value.toString());
    }

    @Override
    public double getDouble(int column) {
        Object value = get(column);
        if (value == null) return 0.0d;
        if (value instanceof Number) return ((Number) value).doubleValue();
        return Double.parseDouble(value.toString());
    }

    @Override
    public byte[] getBlob(int column) {
        Object value = get(column);
        return (byte[]) value;
    }

    /**
     * Returns data type of the given object's value.
     * Returned values are
     *

     *
{@link Cursor#FIELD_TYPE_NULL}

     *
{@link Cursor#FIELD_TYPE_INTEGER}

     *
{@link Cursor#FIELD_TYPE_FLOAT}

     *
{@link Cursor#FIELD_TYPE_STRING}

     *
{@link Cursor#FIELD_TYPE_BLOB}

     *

     */
    @Override
    public int getType(int column) {
        // copy from 'DatabaseUtils.getTypeOfObject'
        Object obj = get(column);
        if (obj == null) {
            return Cursor.FIELD_TYPE_NULL;
        } else if (obj instanceof byte[]) {
            return Cursor.FIELD_TYPE_BLOB;
        } else if (obj instanceof Float || obj instanceof Double) {
            return Cursor.FIELD_TYPE_FLOAT;
        } else if (obj instanceof Long || obj instanceof Integer
                || obj instanceof Short || obj instanceof Byte) {
            return Cursor.FIELD_TYPE_INTEGER;
        } else {
            return Cursor.FIELD_TYPE_STRING;
        }
    }

    @Override
    public boolean isNull(int column) {
        return get(column) == null;
    }
}


text:
bulgarian-liberation-day
========================

This is a simple gesture for Bulgarian Liberation Day (3rd March) on which we are  celebrating liberation from Ottoman rule.

Demo - [http://valkirilov.github.io/bulgarian-liberation-day/](http://valkirilov.github.io/bulgarian-liberation-day/)

Video - [http://youtu.be/TjIPHncO6qA](http://youtu.be/TjIPHncO6qA)


text:
using System;
using System.Web.Mvc;
using JetBrains.Annotations;

namespace Arraybracket.TypedViews {
	public abstract class TypedLayoutPage<TLayoutModel> : WebViewPage {
		private TLayoutModel _LayoutModel;

		public override void InitHelpers() {
			base.InitHelpers();

			if (this.ViewBag.LayoutModel == null)
				throw new InvalidOperationException("You must specify LayoutModel when rendering a typed layout. Use the SetLayout() method from within your view.");
			if (!(this.ViewBag.LayoutModel is TLayoutModel))
				throw new InvalidOperationException(string.Format("The specified LayoutModel value is of type '{0}' and must be of type '{1}'.", this.ViewBag.LayoutModel.GetType(), typeof(TLayoutModel)));
			this._LayoutModel = this.ViewBag.LayoutModel;
		}

		[NotNull]
		public TLayoutModel LayoutModel {
			get { return this._LayoutModel; }
		}

		public void SetLayout([PathReference] string layout, [NotNull] object layoutModel) {
			if (layoutModel == null)
				throw new ArgumentNullException("layoutModel");
			this.ViewBag.LayoutModel = layoutModel;
			base.Layout = layout;
		}

		[Obsolete("You cannot use the Layout property when rendering a typed layout. Use the SetLayout() method instead.", true)]
		public new string Layout {
			get { throw new InvalidOperationException("You cannot use the Layout property when rendering a typed layout. Use the SetLayout() method instead."); }
			set { throw new InvalidOperationException("You cannot use the Layout property when rendering a typed layout. Use the SetLayout() method instead."); }
		}
	}
}


text:
var HEADER_NAME = 'MyApp-Handle-Errors-Generically';
var specificallyHandleInProgress = false;

// Para fazer um request http sem passar por aqui:
// # 1. Injetar RequestErrorHandler no Controller...
// RequestsErrorHandler.specificallyHandled(
// function() {
// # 2. passar a Promise do http
// $q.all({foo: FooService.fetch(), bar: BarService.fetch()}).then(
// function() { /* Handle success */ },
// function() { /* Handle specific errors */ }
// );
// }
// );

app.factory('RequestsErrorHandler', ['$rootScope', '$q', '$location', function($rootScope, $q, $location) {
  return {
      // --- The user's API for claiming responsiblity for requests ---
      specificallyHandled: function(specificallyHandledBlock) {
          specificallyHandleInProgress = true;
          try {
              return specificallyHandledBlock();
          } finally {
              specificallyHandleInProgress = false;
          }
      },

      // --- Response interceptor for handling errors generically ---
      responseError: function(rejection) {
          var shouldHandle = (rejection && rejection.config && rejection.config.headers
              && rejection.config.headers[HEADER_NAME]);

          if (shouldHandle) {
              // --- Your generic error handling goes here ---
          	console.error('generic error handler', rejection);

          	if (rejection.status === 401) {
          		$rootScope.nextLoadedTemplateUrl = $location.path();
          		$location.path('/login');
          	}

          }

          return $q.reject(rejection);
      }
  };
}]);

app.config(['$provide', '$httpProvider', function($provide, $httpProvider) {
  $httpProvider.interceptors.push('RequestsErrorHandler');

  // --- Decorate $http to add a special header by default ---

  function addHeaderToConfig(config) {
      config = config || {};
      config.headers = config.headers || {};

      // Add the header unless user asked to handle errors himself
      if (!specificallyHandleInProgress) {
          config.headers[HEADER_NAME] = true;
      }

      return config;
  }

  // The rest here is mostly boilerplate needed to decorate $http safely
  $provide.decorator('$http', ['$delegate', function($delegate) {
      function decorateRegularCall(method) {
          return function(url, config) {
              return $delegate[method](url, addHeaderToConfig(config));
          };
      }

      function decorateDataCall(method) {
          return function(url, data, config) {
              return $delegate[method](url, data, addHeaderToConfig(config));
          };
      }

      function copyNotOverriddenAttributes(newHttp) {
          for (var attr in $delegate) {
              if (!newHttp.hasOwnProperty(attr)) {
                  if (typeof($delegate[attr]) === 'function') {
                      newHttp[attr] = function() {
                          return $delegate[attr].apply($delegate, arguments);
                      };
                  } else {
                      newHttp[attr] = $delegate[attr];
                  }
              }
          }
      }

      var newHttp = function(config) {
          return $delegate(addHeaderToConfig(config));
      };

      newHttp.get = decorateRegularCall('get');
      newHttp.delete = decorateRegularCall('delete');
      newHttp.head = decorateRegularCall('head');
      newHttp.jsonp = decorateRegularCall('jsonp');
      newHttp.post = decorateDataCall('post');
      newHttp.put = decorateDataCall('put');

      copyNotOverriddenAttributes(newHttp);

      return newHttp;
  }]);
}]);


text:
package ca.sumost.kinetic.editor;

import ca.sumost.kinetic.RenderableBody;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.World;

public class RedAtomCreator extends AtomCreator
{
	private final World mWorld;

	private final static FixtureDef mFixtureDef = makeFixtureDef(1, 0.5f);

	private final static RenderableBody mRenderer = makeRenderableBody(Color.RED);

	public RedAtomCreator(World world)
	{
		mWorld = world;
	}

	@Override
	protected void makeAtom(Vector2 centre)
	{
		mBodyDef.position.set(centre);

		Body body = mWorld.createBody(mBodyDef);
		body.createFixture(mFixtureDef);
		body.setUserData(mRenderer);
	}

}


text:
class PyIEnumDebugExpressionContexts : public PyIUnknown
{
public:
	MAKE_PYCOM_CTOR(PyIEnumDebugExpressionContexts);
	static IEnumDebugExpressionContexts *GetI(PyObject *self);
	static PyComTypeObject type;

	// The Python methods
	static PyObject *Next(PyObject *self, PyObject *args);
	static PyObject *Skip(PyObject *self, PyObject *args);
	static PyObject *Reset(PyObject *self, PyObject *args);
	static PyObject *Clone(PyObject *self, PyObject *args);

protected:
	PyIEnumDebugExpressionContexts(IUnknown *pdisp);
	~PyIEnumDebugExpressionContexts();
};
// ---------------------------------------------------
//
// Gateway Declaration

class PyGEnumDebugExpressionContexts : public PyGatewayBase, public IEnumDebugExpressionContexts
{
protected:
	PyGEnumDebugExpressionContexts(PyObject *instance) : PyGatewayBase(instance) { ; }
	PYGATEWAY_MAKE_SUPPORT(PyGEnumDebugExpressionContexts, IEnumDebugExpressionContexts, IID_IEnumDebugExpressionContexts)

	// IEnumDebugExpressionContexts
	STDMETHOD(Next)(
		ULONG celt,
		IDebugExpressionContext __RPC_FAR *__RPC_FAR * ppdec,
		ULONG __RPC_FAR * pceltFetched);

	STDMETHOD(Skip)(
		ULONG celt);

	STDMETHOD(Reset)(
		void);

	STDMETHOD(Clone)(
		IEnumDebugExpressionContexts __RPC_FAR *__RPC_FAR * ppedec);

};


text:
namespace SynologyClient
{
    public class SharedFolderPerm
    {
        public string share_right { get; set; }
        public int posix { get; set; }
        public AdvancedRights adv_right { get; set; }
        public bool acl_enable { get; set; }
        public bool is_acl_mode { get; set; }
        public Acl Acl { get; set; }
    }
}


text:
'use strict';
// This is a basic test file for use with testling.
// The test script language comes from tape.
/* jshint node: true */
var test = require('tape');

var webdriver = require('selenium-webdriver');
var seleniumHelpers = require('../../../../../test/selenium-lib');

test('Candidate Gathering', function(t) {
  var driver = seleniumHelpers.buildDriver();

  driver.get('file://' + process.cwd() +
      '/src/content/peerconnection/trickle-ice/index.html')
  .then(function() {
    t.pass('page loaded');
    return driver.findElement(webdriver.By.id('gather')).click();
  })
  .then(function() {
    return driver.wait(function() {
      return driver.executeScript(
          'return pc === null && candidates.length > 0;');
    }, 30 * 1000);
  })
  .then(function() {
    t.pass('got candidates');
    t.end();
  })
  .then(null, function(err) {
    t.fail(err);
    t.end();
  });
});

test('Loading server data', function(t) {
  var driver = seleniumHelpers.buildDriver();

  driver.get('file://' + process.cwd() +
      '/src/content/peerconnection/trickle-ice/index.html')
  .then(function() {
    t.pass('page loaded');
    return driver.findElement(webdriver.By.css('#servers>option'));
  })
  .then(function(element) {
    return new webdriver.ActionSequence(driver).
        doubleClick(element).perform();
  })
  .then(function() {
    return driver.findElement(webdriver.By.id('url')).getAttribute('value');
  })
  .then(function(value) {
    t.ok(value !== '', 'doubleclick loads server data');
    t.end();
  })
  .then(null, function(err) {
    t.fail(err);
    t.end();
  });
});

test('Adding a server', function(t) {
  var driver = seleniumHelpers.buildDriver();

  driver.get('file://' + process.cwd() +
      '/src/content/peerconnection/trickle-ice/index.html')
  .then(function() {
    t.pass('page loaded');
    return driver.findElement(webdriver.By.id('url'))
        .sendKeys('stun:stun.l.google.com:19302');
  })
  .then(function() {
    t.pass('url input worked');
    return driver.findElement(webdriver.By.id('add')).click();
  })
  .then(function() {
    return driver.findElement(webdriver.By.css('#servers'))
        .getAttribute('length');
  })
  .then(function(length) {
    t.ok(length === '2', 'server added');
    t.end();
  })
  .then(null, function(err) {
    t.fail(err);
    t.end();
  });
});

test('Removing a server', function(t) {
  var driver = seleniumHelpers.buildDriver();

  driver.get('file://' + process.cwd() +
      '/src/content/peerconnection/trickle-ice/index.html')
  .then(function() {
    t.pass('page loaded');
    return driver.findElement(webdriver.By.css('#servers>option')).click();
  })
  .then(function() {
    return driver.findElement(webdriver.By.id('remove')).click();
  })
  .then(function() {
    return driver.findElement(webdriver.By.css('#servers'))
        .getAttribute('length');
  })
  .then(function(length) {
    t.ok(length === '0', 'server removed');
    t.end();
  })
  .then(null, function(err) {
    t.fail(err);
    t.end();
  });
});


text:
{% extends "base.html" %}

{% block title %}{{ SITENAME }} - About{% endblock %}

{% block content %}
{% block breadcrumb %}

Home

        About me

{% endblock %}
It's rainy here.
{% endblock %}


text:
<CartCreateResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2011-08-01">
  <OperationRequest>
    <HTTPHeaders>
      <Header Name="UserAgent" Value="Python-urllib/2.6"/>
    </HTTPHeaders>
    <RequestId>0J86QEH2WKYABRQ4PJY1</RequestId>
    <Arguments>
      <Argument Name="Service" Value="AWSECommerceService"/>
      <Argument Name="Item.1.Quantity" Value="2"/>
      <Argument Name="Operation" Value="CartCreate"/>
      <Argument Name="Timestamp" Value="2011-11-08T21:47:01Z"/>
      <Argument Name="Version" Value="2011-08-01"/>
      <Argument Name="AssociateTag" Value="XXXXXXXXXXXXXXX"/>
      <Argument Name="Item.1.ASIN" Value="0201896842"/>
      <Argument Name="Signature" Value="XXXXXXXXXXXXXXX"/>
      <Argument Name="Item.2.ASIN" Value="0201896834"/>
      <Argument Name="Item.2.Quantity" Value="1"/>
      <Argument Name="AWSAccessKeyId" Value="XXXXXXXXXXXXXXX"/>
    </Arguments>
    <RequestProcessingTime>0.149067163467407</RequestProcessingTime>
  </OperationRequest>
  <Cart>
    <Request>
      <IsValid>True</IsValid>
      <CartCreateRequest>
        <Items>
          <Item>
            <ASIN>0201896842</ASIN>
            <Quantity>2</Quantity>
          </Item>
          <Item>
            <ASIN>0201896834</ASIN>
            <Quantity>1</Quantity>
          </Item>
        </Items>
      </CartCreateRequest>
    </Request>
    <CartId>184-2024947-8200558</CartId>
    <HMAC>u6FqmXmqXKyMZDkXCDxIRBiUJ18=</HMAC>
    <URLEncodedHMAC>u6FqmXmqXKyMZDkXCDxIRBiUJ18%3D</URLEncodedHMAC>
    <PurchaseURL>https://www.amazon.com/gp/cart/aws-merge.html?cart-id=184-2024947-8200558%26associate-id=redtoad-21%26hmac=u6FqmXmqXKyMZDkXCDxIRBiUJ18=%26SubscriptionId=AKIAJTJID3GQ4PAFYOEQ%26MergeCart=False</PurchaseURL>
    <SubTotal>
      <Amount>17451</Amount>
      <CurrencyCode>USD</CurrencyCode>
      <FormattedPrice>$174.51</FormattedPrice>
    </SubTotal>
    <CartItems>
      <SubTotal>
        <Amount>17451</Amount>
        <CurrencyCode>USD</CurrencyCode>
        <FormattedPrice>$174.51</FormattedPrice>
      </SubTotal>
      <CartItem>
        <CartItemId>U24FI3NHT8Y1PC</CartItemId>
        <ASIN>0201896842</ASIN>
        <SellerNickname>Amazon.com</SellerNickname>
        <Quantity>2</Quantity>
        <Title>Art of Computer Programming, Volume 2: Seminumerical Algorithms (3rd Edition)</Title>
        <ProductGroup>Book</ProductGroup>
        <Price>
          <Amount>6001</Amount>
          <CurrencyCode>USD</CurrencyCode>
          <FormattedPrice>$60.01</FormattedPrice>
        </Price>
        <ItemTotal>
          <Amount>12002</Amount>
          <CurrencyCode>USD</CurrencyCode>
          <FormattedPrice>$120.02</FormattedPrice>
        </ItemTotal>
      </CartItem>
      <CartItem>
        <CartItemId>U1R5P2OIZBR21I</CartItemId>
        <ASIN>0201896834</ASIN>
        <SellerNickname>Amazon.com</SellerNickname>
        <Quantity>1</Quantity>
        <Title>Art of Computer Programming, Volume 1: Fundamental Algorithms (3rd Edition)</Title>
        <ProductGroup>Book</ProductGroup>
        <Price>
          <Amount>5449</Amount>
          <CurrencyCode>USD</CurrencyCode>
          <FormattedPrice>$54.49</FormattedPrice>
        </Price>
        <ItemTotal>
          <Amount>5449</Amount>
          <CurrencyCode>USD</CurrencyCode>
          <FormattedPrice>$54.49</FormattedPrice>
        </ItemTotal>
      </CartItem>
    </CartItems>
  </Cart>
</CartCreateResponse>