text:
package org.elasticsearch.index.fielddata;

import org.apache.lucene.document.*;
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.index.CompositeReaderContext;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.English;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.index.fielddata.BytesValues.Iter;
import org.elasticsearch.index.mapper.FieldMapper;
import org.junit.Test;

import java.util.*;
import java.util.Map.Entry;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;

public class DuelFieldDataTests extends AbstractFieldDataTests {

    @Override
    protected FieldDataType getFieldDataType() {
        return null;
    }

    public static int atLeast(Random random, int i) {
        int min = i;
        int max = min + (min / 2);
        return min + random.nextInt(max - min);
    }

    @Test
    public void testDuelAllTypesSingleValue() throws Exception {
        Random random = getRandom();
        int atLeast = atLeast(random, 1000);
        for (int i = 0; i < atLeast; i++) {
            int v = (random.nextBoolean() ? -1 * random.nextInt(Byte.MAX_VALUE) : random.nextInt(Byte.MAX_VALUE));
            Document d = new Document();
            d.add(new StringField("_id", "" + i, Field.Store.NO));
            if (random.nextInt(15) != 0) {
                d.add(new LongField("long", v, Field.Store.NO));
                d.add(new IntField("integer", v, Field.Store.NO));
                d.add(new DoubleField("double", v, Field.Store.NO));
                d.add(new FloatField("float", v, Field.Store.NO));
                d.add(new StringField("bytes", "" + v, Field.Store.NO));
            }
            writer.addDocument(d);
            if (random.nextInt(10) == 0) {
                refreshReader();
            }
        }
        AtomicReaderContext context = refreshReader();
        Map<FieldDataType, Type> typeMap = new HashMap<FieldDataType, DuelFieldDataTests.Type>();
        typeMap.put(new FieldDataType("string", ImmutableSettings.builder().put("format", "fst")), Type.Bytes);
        typeMap.put(new FieldDataType("string", ImmutableSettings.builder().put("format", "paged_bytes")), Type.Bytes);
        typeMap.put(new FieldDataType("byte"), Type.Integer);
        typeMap.put(new FieldDataType("short"), Type.Integer);
        typeMap.put(new FieldDataType("int"), Type.Integer);
        typeMap.put(new FieldDataType("long"), Type.Long);
        typeMap.put(new FieldDataType("double"), Type.Double);
        typeMap.put(new FieldDataType("float"), Type.Float);
        ArrayList<Entry<FieldDataType, Type>> list = new ArrayList<Entry<FieldDataType, Type>>(typeMap.entrySet());
        Preprocessor pre = new ToDoublePreprocessor();
        while (!list.isEmpty()) {
            Entry<FieldDataType, Type> left;
            Entry<FieldDataType, Type> right;
            if (list.size() > 1) {
                left = list.remove(random.nextInt(list.size()));
                right = list.remove(random.nextInt(list.size()));
            } else {
                right = left = list.remove(0);
            }
            ifdService.clear();
            IndexFieldData leftFieldData = ifdService.getForField(new FieldMapper.Names(left.getValue().name().toLowerCase(Locale.ROOT)),
                    left.getKey());
            ifdService.clear();
            IndexFieldData rightFieldData = ifdService.getForField(new FieldMapper.Names(right.getValue().name().toLowerCase(Locale.ROOT)),
                    right.getKey());
            duelFieldDataBytes(random, context, leftFieldData, rightFieldData, pre);
            duelFieldDataBytes(random, context, rightFieldData, leftFieldData, pre);

            DirectoryReader perSegment = DirectoryReader.open(writer, true);
            CompositeReaderContext composite = perSegment.getContext();
            List<AtomicReaderContext> leaves = composite.leaves();
            for (AtomicReaderContext atomicReaderContext : leaves) {
                duelFieldDataBytes(random, atomicReaderContext, leftFieldData, rightFieldData, pre);
            }
        }
    }

    @Test
    public void testDuelIntegers() throws Exception {
        Random random = getRandom();
        int atLeast = atLeast(random, 1000);
        for (int i = 0; i < atLeast; i++) {
            Document d = new Document();
            d.add(new StringField("_id", "" + i, Field.Store.NO));
            if (random.nextInt(15) != 0) {
                int[] numbers = getNumbers(random, Byte.MAX_VALUE);
                for (int j : numbers) {
                    d.add(new LongField("long", j, Field.Store.NO));
                    d.add(new IntField("integer", j, Field.Store.NO));
                }
            }
            writer.addDocument(d);
            if (random.nextInt(10) == 0) {
                refreshReader();
            }
        }
        AtomicReaderContext context = refreshReader();
        Map<FieldDataType, Type> typeMap = new HashMap<FieldDataType, DuelFieldDataTests.Type>();
        typeMap.put(new FieldDataType("byte"), Type.Integer);
        typeMap.put(new FieldDataType("short"), Type.Integer);
        typeMap.put(new FieldDataType("int"), Type.Integer);
        typeMap.put(new FieldDataType("long"), Type.Long);
        ArrayList<Entry<FieldDataType, Type>> list = new ArrayList<Entry<FieldDataType, Type>>(typeMap.entrySet());
        while (!list.isEmpty()) {
            Entry<FieldDataType, Type> left;
            Entry<FieldDataType, Type> right;
            if (list.size() > 1) {
                left = list.remove(random.nextInt(list.size()));
                right = list.remove(random.nextInt(list.size()));
            } else {
                right = left = list.remove(0);
            }
            ifdService.clear();
            IndexNumericFieldData leftFieldData = ifdService.getForField(new FieldMapper.Names(left.getValue().name().toLowerCase(Locale.ROOT)),
                    left.getKey());
            ifdService.clear();
            IndexNumericFieldData rightFieldData = ifdService.getForField(new FieldMapper.Names(right.getValue().name().toLowerCase(Locale.ROOT)),
                    right.getKey());
            duelFieldDataLong(random, context, leftFieldData, rightFieldData);
            duelFieldDataLong(random, context, rightFieldData, leftFieldData);

            DirectoryReader perSegment = DirectoryReader.open(writer, true);
            CompositeReaderContext composite = perSegment.getContext();
            List<AtomicReaderContext> leaves = composite.leaves();
            for (AtomicReaderContext atomicReaderContext : leaves) {
                duelFieldDataLong(random, atomicReaderContext, leftFieldData, rightFieldData);
            }
        }

    }

    @Test
    public void testDuelDoubles() throws Exception {
        Random random = getRandom();
        int atLeast = atLeast(random, 1000);
        for (int i = 0; i < atLeast; i++) {
            Document d = new Document();
            d.add(new StringField("_id", "" + i, Field.Store.NO));
            if (random.nextInt(15) != 0) {
                int[] numbers = getNumbers(random, Short.MAX_VALUE);
                for (int j : numbers) {
                    d.add(new FloatField("float", j, Field.Store.NO));
                    d.add(new DoubleField("double", j, Field.Store.NO));
                }
            }
            writer.addDocument(d);
            if (random.nextInt(10) == 0) {
                refreshReader();
            }
        }
        AtomicReaderContext context = refreshReader();
        Map<FieldDataType, Type> typeMap = new HashMap<FieldDataType, DuelFieldDataTests.Type>();
        typeMap.put(new FieldDataType("float"), Type.Float);
        typeMap.put(new FieldDataType("double"), Type.Double);
        ArrayList<Entry<FieldDataType, Type>> list = new ArrayList<Entry<FieldDataType, Type>>(typeMap.entrySet());
        while (!list.isEmpty()) {
            Entry<FieldDataType, Type> left;
            Entry<FieldDataType, Type> right;
            if (list.size() > 1) {
                left = list.remove(random.nextInt(list.size()));
                right = list.remove(random.nextInt(list.size()));
            } else {
                right = left = list.remove(0);
            }
            ifdService.clear();
            IndexNumericFieldData leftFieldData = ifdService.getForField(new FieldMapper.Names(left.getValue().name().toLowerCase(Locale.ROOT)),
                    left.getKey());
            ifdService.clear();
            IndexNumericFieldData rightFieldData = ifdService.getForField(new FieldMapper.Names(right.getValue().name().toLowerCase(Locale.ROOT)),
                    right.getKey());
            duelFieldDataDouble(random, context, leftFieldData, rightFieldData);
            duelFieldDataDouble(random, context, rightFieldData, leftFieldData);

            DirectoryReader perSegment = DirectoryReader.open(writer, true);
            CompositeReaderContext composite = perSegment.getContext();
            List<AtomicReaderContext> leaves = composite.leaves();
            for (AtomicReaderContext atomicReaderContext : leaves) {
                duelFieldDataDouble(random, atomicReaderContext, leftFieldData, rightFieldData);
            }
        }

    }

    @Test
    public void testDuelStrings() throws Exception {
        Random random = getRandom();
        int atLeast = atLeast(random, 1000);
        for (int i = 0; i < atLeast; i++) {
            Document d = new Document();
            d.add(new StringField("_id", "" + i, Field.Store.NO));
            if (random.nextInt(15) != 0) {
                int[] numbers = getNumbers(random, Integer.MAX_VALUE);
                for (int j : numbers) {
                    d.add(new StringField("bytes", English.longToEnglish(j), Field.Store.NO));
                }
                if (random.nextInt(10) == 0) {
                    d.add(new StringField("bytes", "", Field.Store.NO));
                }
            }
            writer.addDocument(d);
            if (random.nextInt(10) == 0) {
                refreshReader();
            }
        }
        AtomicReaderContext context = refreshReader();
        Map<FieldDataType, Type> typeMap = new HashMap<FieldDataType, DuelFieldDataTests.Type>();
        typeMap.put(new FieldDataType("string", ImmutableSettings.builder().put("format", "fst")), Type.Bytes);
        typeMap.put(new FieldDataType("string", ImmutableSettings.builder().put("format", "paged_bytes")), Type.Bytes);
        // TODO add filters
        ArrayList<Entry<FieldDataType, Type>> list = new ArrayList<Entry<FieldDataType, Type>>(typeMap.entrySet());
        Preprocessor pre = new Preprocessor();
        while (!list.isEmpty()) {
            Entry<FieldDataType, Type> left;
            Entry<FieldDataType, Type> right;
            if (list.size() > 1) {
                left = list.remove(random.nextInt(list.size()));
                right = list.remove(random.nextInt(list.size()));
            } else {
                right = left = list.remove(0);
            }
            ifdService.clear();
            IndexFieldData leftFieldData = ifdService.getForField(new FieldMapper.Names(left.getValue().name().toLowerCase(Locale.ROOT)),
                    left.getKey());
            ifdService.clear();
            IndexFieldData rightFieldData = ifdService.getForField(new FieldMapper.Names(right.getValue().name().toLowerCase(Locale.ROOT)),
                    right.getKey());
            duelFieldDataBytes(random, context, leftFieldData, rightFieldData, pre);
            duelFieldDataBytes(random, context, rightFieldData, leftFieldData, pre);

            DirectoryReader perSegment = DirectoryReader.open(writer, true);
            CompositeReaderContext composite = perSegment.getContext();
            List<AtomicReaderContext> leaves = composite.leaves();
            for (AtomicReaderContext atomicReaderContext : leaves) {
                duelFieldDataBytes(random, atomicReaderContext, leftFieldData, rightFieldData, pre);
            }
            perSegment.close();
        }

    }

    private int[] getNumbers(Random random, int margin) {
        if (random.nextInt(20) == 0) {
            int[] num = new int[1 + random.nextInt(10)];
            for (int i = 0; i < num.length; i++) {
                int v = (random.nextBoolean() ? -1 * random.nextInt(margin) : random.nextInt(margin));
                num[i] = v;
            }
            return num;
        }
        return new int[]{(random.nextBoolean() ? -1 * random.nextInt(margin) : random.nextInt(margin))};
    }

    private static void duelFieldDataBytes(Random random, AtomicReaderContext context, IndexFieldData left, IndexFieldData right, Preprocessor pre) throws Exception {
        AtomicFieldData leftData = random.nextBoolean() ? left.load(context) : left.loadDirect(context);
        AtomicFieldData rightData = random.nextBoolean() ? right.load(context) : right.loadDirect(context);
        assertThat(leftData.isMultiValued(), equalTo(rightData.isMultiValued()));
        assertThat(leftData.getNumDocs(), equalTo(rightData.getNumDocs()));

        int numDocs = leftData.getNumDocs();
        BytesValues leftBytesValues = random.nextBoolean() ? leftData.getBytesValues() : leftData.getHashedBytesValues();
        BytesValues rightBytesValues = random.nextBoolean() ? rightData.getBytesValues() : rightData.getHashedBytesValues();
        for (int i = 0; i < numDocs; i++) {
            assertThat(leftBytesValues.hasValue(i), equalTo(rightBytesValues.hasValue(i)));
            if (leftBytesValues.hasValue(i)) {
                assertThat(pre.toString(leftBytesValues.getValue(i)), equalTo(pre.toString(rightBytesValues.getValue(i))));

            } else {
                assertThat(leftBytesValues.getValue(i), nullValue());
                assertThat(rightBytesValues.getValue(i), nullValue());
            }

            boolean hasValue = leftBytesValues.hasValue(i);
            Iter leftIter = leftBytesValues.getIter(i);
            Iter rightIter = rightBytesValues.getIter(i);
            assertThat(leftIter.hasNext(), equalTo(rightIter.hasNext()));
            assertThat(leftIter.hasNext(), equalTo(hasValue));

            while (leftIter.hasNext()) {
                assertThat(hasValue, equalTo(true));
                assertThat(leftIter.hasNext(), equalTo(rightIter.hasNext()));
                BytesRef rightBytes = rightIter.next();
                BytesRef leftBytes = leftIter.next();

                assertThat(pre.toString(leftBytes), equalTo(pre.toString(rightBytes)));
                if (rightBytes.equals(leftBytes)) {
                    assertThat(leftIter.hash(), equalTo(rightIter.hash()));// call twice
                    assertThat(leftIter.hash(), equalTo(rightIter.hash()));
                    assertThat(leftIter.hash(), equalTo(rightBytes.hashCode()));
                    assertThat(rightIter.hash(), equalTo(leftBytes.hashCode()));
                }
            }
            assertThat(leftIter.hasNext(), equalTo(rightIter.hasNext()));
        }
    }

    private static void duelFieldDataDouble(Random random, AtomicReaderContext context, IndexNumericFieldData left, IndexNumericFieldData right) throws Exception {
        AtomicNumericFieldData leftData = random.nextBoolean() ? left.load(context) : left.loadDirect(context);
        AtomicNumericFieldData rightData = random.nextBoolean() ? right.load(context) : right.loadDirect(context);

        assertThat(leftData.isMultiValued(), equalTo(rightData.isMultiValued()));
        assertThat(leftData.getNumDocs(), equalTo(rightData.getNumDocs()));

        int numDocs = leftData.getNumDocs();
        DoubleValues leftDoubleValues = leftData.getDoubleValues();
        DoubleValues rightDoubleValues = rightData.getDoubleValues();
        for (int i = 0; i < numDocs; i++) {
            assertThat(leftDoubleValues.hasValue(i), equalTo(rightDoubleValues.hasValue(i)));
            if (leftDoubleValues.hasValue(i)) {
                assertThat(leftDoubleValues.getValue(i), equalTo(rightDoubleValues.getValue(i)));

            } else {
                assertThat(leftDoubleValues.getValue(i), equalTo(0d));
                assertThat(rightDoubleValues.getValue(i), equalTo(0d));
            }

            boolean hasValue = leftDoubleValues.hasValue(i);
            DoubleValues.Iter leftIter = leftDoubleValues.getIter(i);
            DoubleValues.Iter rightIter = rightDoubleValues.getIter(i);
            assertThat(leftIter.hasNext(), equalTo(rightIter.hasNext()));
            assertThat(leftIter.hasNext(), equalTo(hasValue));

            while (leftIter.hasNext()) {
                assertThat(hasValue, equalTo(true));
                assertThat(leftIter.hasNext(), equalTo(rightIter.hasNext()));
                double rightValue = rightIter.next();
                double leftValue = leftIter.next();

                assertThat(leftValue, equalTo(rightValue));
            }
            assertThat(leftIter.hasNext(), equalTo(rightIter.hasNext()));
        }
    }

    private static void duelFieldDataLong(Random random, AtomicReaderContext context, IndexNumericFieldData left, IndexNumericFieldData right) throws Exception {
        AtomicNumericFieldData leftData = random.nextBoolean() ? left.load(context) : left.loadDirect(context);
        AtomicNumericFieldData rightData = random.nextBoolean() ? right.load(context) : right.loadDirect(context);

        assertThat(leftData.isMultiValued(), equalTo(rightData.isMultiValued()));
        assertThat(leftData.getNumDocs(), equalTo(rightData.getNumDocs()));

        int numDocs = leftData.getNumDocs();
        LongValues leftDoubleValues = leftData.getLongValues();
        LongValues rightDoubleValues = rightData.getLongValues();
        for (int i = 0; i < numDocs; i++) {
            assertThat(leftDoubleValues.hasValue(i), equalTo(rightDoubleValues.hasValue(i)));
            if (leftDoubleValues.hasValue(i)) {
                assertThat(leftDoubleValues.getValue(i), equalTo(rightDoubleValues.getValue(i)));

            } else {
                assertThat(leftDoubleValues.getValue(i), equalTo(0l));
                assertThat(rightDoubleValues.getValue(i), equalTo(0l));
            }

            boolean hasValue = leftDoubleValues.hasValue(i);
            LongValues.Iter leftIter = leftDoubleValues.getIter(i);
            LongValues.Iter rightIter = rightDoubleValues.getIter(i);
            assertThat(leftIter.hasNext(), equalTo(rightIter.hasNext()));
            assertThat(leftIter.hasNext(), equalTo(hasValue));

            while (leftIter.hasNext()) {
                assertThat(hasValue, equalTo(true));
                assertThat(leftIter.hasNext(), equalTo(rightIter.hasNext()));
                long rightValue = rightIter.next();
                long leftValue = leftIter.next();

                assertThat(leftValue, equalTo(rightValue));
            }
            assertThat(leftIter.hasNext(), equalTo(rightIter.hasNext()));
        }
    }

    private static class Preprocessor {

        public String toString(BytesRef ref) {
            return ref.utf8ToString();
        }
    }

    private static class ToDoublePreprocessor extends Preprocessor {
        public String toString(BytesRef ref) {
            return Double.toString(Double.parseDouble(super.toString(ref)));
        }
    }

    private static enum Type {
        Float, Double, Integer, Long, Bytes
    }
}


text:
"""create database

Revision ID: 166ff2dcc48d
Revises:
Create Date: 2014-10-24 11:43:23.886123
"""

try:
    from hashlib import sha1
    sha1  # suppress pyflakes warning
except ImportError:  # pragma: nocover
    from sha import new as sha1

from alembic import op, context
from sqlalchemy import ForeignKey, Column, Table, MetaData
from sqlalchemy.types import Integer, Boolean, Unicode, String, Float, \
    UserDefinedType, DateTime

# revision identifiers, used by Alembic.
revision = "166ff2dcc48d"
down_revision = None

class TsVector(UserDefinedType):
    """ A custom type for PostgreSQL's tsvector type. """
    def get_col_spec(self):
        return "TSVECTOR"

def upgrade():
    schema = context.get_context().config.get_main_option("schema")
    parentschema = context.get_context().config.get_main_option("parentschema")
    srid = context.get_context().config.get_main_option("srid")

    engine = op.get_bind().engine
    if op.get_context().dialect.has_table(
        engine, "functionality", schema=schema
    ):  # pragma: nocover
        return

    op.create_table(
        "functionality",
        Column("id", Integer, primary_key=True),
        Column("name", Unicode, nullable=False),
        Column("value", Unicode, nullable=False),
        Column("description", Unicode),
        schema=schema,
    )
    op.create_table(
        "treeitem",
        Column("type", String(10), nullable=False),
        Column("id", Integer, primary_key=True),
        Column("name", Unicode),
        Column("order", Integer, nullable=False),
        Column("metadataURL", Unicode),
        schema=schema,
    )
    op.create_table(
        "restrictionarea",
        Column("id", Integer, primary_key=True),
        Column("name", Unicode),
        Column("description", Unicode),
        Column("readwrite", Boolean, default=False),
        schema=schema,
    )
    op.execute(
        "SELECT AddGeometryColumn('%(schema)s', 'restrictionarea', "
        "'area', %(srid)s, 'POLYGON', 2)" % {
            "schema": schema, "srid": srid
        }
    )
    op.create_table(
        "shorturl",
        Column("id", Integer, primary_key=True),
        Column("url", Unicode(1000)),
        Column("ref", String(20), index=True, unique=True, nullable=False),
        Column("creator_email", Unicode(200)),
        Column("creation", DateTime),
        Column("last_hit", DateTime),
        Column("nb_hits", Integer),
        schema=schema + "_static",
    )

    op.create_table(
        "role",
        Column("id", Integer, primary_key=True),
        Column("name", Unicode, unique=True, nullable=False),
        Column("description", Unicode),
        schema=schema,
    )
    op.execute(
        "SELECT AddGeometryColumn('%(schema)s', 'role', "
        "'extent', %(srid)s, 'POLYGON', 2)" % {
            "schema": schema, "srid": srid
        }
    )
    role = Table(
        "role", MetaData(),
        Column("name", Unicode, unique=True, nullable=False),
        schema=schema,
    )
    op.bulk_insert(role, [
        {"name": "role_admin"}
    ])

    op.create_table(
        "layer",
        Column(
            "id", Integer,
            ForeignKey(schema + ".treeitem.id"), primary_key=True
        ),
        Column("public", Boolean, default=True),
        Column("inMobileViewer", Boolean, default=True),
        Column("inDesktopViewer", Boolean, default=True),
        Column("isChecked", Boolean, default=True),
        Column("icon", Unicode),
        Column("layerType", Unicode(12)),
        Column("url", Unicode),
        Column("imageType", Unicode(10)),
        Column("style", Unicode),
        Column("dimensions", Unicode),
        Column("matrixSet", Unicode),
        Column("wmsUrl", Unicode),
        Column("wmsLayers", Unicode),
        Column("queryLayers", Unicode),
        Column("kml", Unicode),
        Column("isSingleTile", Boolean),
        Column("legend", Boolean, default=True),
        Column("legendImage", Unicode),
        Column("legendRule", Unicode),
        Column("isLegendExpanded", Boolean, default=False),
        Column("minResolution", Float),
        Column("maxResolution", Float),
        Column("disclaimer", Unicode),
        Column("identifierAttributeField", Unicode),
        Column("geoTable", Unicode),
        Column("excludeProperties", Unicode),
        Column("timeMode", Unicode(8)),
        schema=schema,
    )
    op.create_table(
        "role_restrictionarea",
        Column(
            "role_id", Integer,
            ForeignKey(schema + ".role.id"), primary_key=True
        ),
        Column(
            "restrictionarea_id", Integer,
            ForeignKey(schema + ".restrictionarea.id"),
            primary_key=True
        ),
        schema=schema,
    )
    op.create_table(
        "tsearch",
        Column("id", Integer, primary_key=True),
        Column("label", Unicode),
        Column("layer_name", Unicode),
        Column("role_id", Integer, ForeignKey(schema + ".role.id"), nullable=True),
        Column("public", Boolean, server_default="true"),
        Column("ts", TsVector),
        Column("params", Unicode, nullable=True),
        schema=schema,
    )
    op.execute(
        "SELECT AddGeometryColumn('%(schema)s', 'tsearch', 'the_geom', "
        "%(srid)s, 'GEOMETRY', 2)" % {
            "schema": schema, "srid": srid
        }
    )
    op.create_index(
        "tsearch_ts_idx", "tsearch", ["ts"],
        schema=schema, postgresql_using="gin"
    )
    op.create_table(
        "treegroup",
        Column(
            "id", Integer,
            ForeignKey(schema + ".treeitem.id"), primary_key=True
        ),
        schema=schema,
    )

    op.create_table(
        "user",
        Column("type", String(10), nullable=False),
        Column("id", Integer, primary_key=True),
        Column("username", Unicode, unique=True, nullable=False),
        Column("password", Unicode, nullable=False),
        Column("email", Unicode, nullable=False),
        Column("is_password_changed", Boolean, default=False),
        Column("role_id", Integer, ForeignKey(schema + ".role.id"), nullable=False),
        schema=schema,
    )
    if parentschema is not None and parentschema is not "":  # pragma: nocover
        op.add_column(
            "user",
            Column("parent_role_id", Integer, ForeignKey(parentschema + ".role.id")),
            schema=schema
        )
    op.execute(
        "INSERT INTO %(schema)s.user (type, username, email, password, role_id) "
        "(SELECT 'user', 'admin', 'info@example.com', '%(pass)s', r.id "
        "FROM %(schema)s.role AS r "
        "WHERE r.name = 'role_admin')" % {
            "schema": schema,
            "pass": sha1("admin").hexdigest()
        }
    )

    op.create_table(
        "role_functionality",
        Column(
            "role_id", Integer,
            ForeignKey(schema + ".role.id"), primary_key=True
        ),
        Column(
            "functionality_id", Integer,
            ForeignKey(schema + ".functionality.id"), primary_key=True
        ),
        schema=schema,
    )
    op.create_table(
        "user_functionality",
        Column(
            "user_id", Integer,
            ForeignKey(schema + ".user.id"), primary_key=True
        ),
        Column(
            "functionality_id", Integer,
            ForeignKey(schema + ".functionality.id"), primary_key=True
        ),
        schema=schema,
    )
    op.create_table(
        "layergroup",
        Column(
            "id", Integer,
            ForeignKey(schema + ".treegroup.id"), primary_key=True
        ),
        Column("isExpanded", Boolean),
        Column("isInternalWMS", Boolean),
        # children have radio button instance of check box
        Column("isBaseLayer", Boolean),
        schema=schema,
    )
    op.create_table(
        "layer_restrictionarea",
        Column(
            "layer_id", Integer,
            ForeignKey(schema + ".layer.id"), primary_key=True
        ),
        Column(
            "restrictionarea_id", Integer,
            ForeignKey(schema + ".restrictionarea.id"), primary_key=True
        ),
        schema=schema,
    )
    op.create_table(
        "layergroup_treeitem",
        Column(
            "treegroup_id", Integer,
            ForeignKey(schema + ".treegroup.id"), primary_key=True
        ),
        Column(
            "treeitem_id", Integer,
            ForeignKey(schema + ".treeitem.id"), primary_key=True
        ),
        schema=schema,
    )
    op.create_table(
        "theme",
        Column(
            "id", Integer,
            ForeignKey(schema + ".treegroup.id"), primary_key=True
        ),
        Column("icon", Unicode),
        Column("inMobileViewer", Boolean, default=False),
        Column("inDesktopViewer", Boolean, default=True),
        schema=schema,
    )
    op.create_table(
        "theme_functionality",
        Column(
            "theme_id", Integer,
            ForeignKey(schema + ".theme.id"), primary_key=True
        ),
        Column(
            "functionality_id", Integer,
            ForeignKey(schema + ".functionality.id"), primary_key=True
        ),
        schema=schema,
    )

def downgrade():
    schema = context.get_context().config.get_main_option("schema")

    op.drop_table("theme_functionality", schema=schema)
    op.drop_table("theme", schema=schema)
    op.drop_table("layergroup_treeitem", schema=schema)
    op.drop_table("layer_restrictionarea", schema=schema)
    op.drop_table("layergroup", schema=schema)
    op.drop_table("user_functionality", schema=schema)
    op.drop_table("role_functionality", schema=schema)
    op.drop_table("user", schema=schema)
    op.drop_table("treegroup", schema=schema)
    op.drop_table("tsearch", schema=schema)
    op.drop_table("role_restrictionarea", schema=schema)
    op.drop_table("layer", schema=schema)
    op.drop_table("role", schema=schema)
    op.drop_table("shorturl", schema=schema + "_static")
    op.drop_table("restrictionarea", schema=schema)
    op.drop_table("treeitem", schema=schema)
    op.drop_table("functionality", schema=schema)

redpajama_set_name: RedPajamaGithub


text:
require 'rspec'
require 'aviglitch'
require 'pathname'
require 'fileutils'

FILES_DIR = Pathname.new(File.dirname(__FILE__)).realpath + 'files'
OUTPUT_DIR = FILES_DIR + 'output'

RSpec.configure do |config|
  config.filter_run_excluding :skip => true
  config.expect_with :rspec do |c|
    c.syntax = [:should, :expect]
  end
end


text:
namespace GoogleCloudPrintApi.Models.Printer
{
    /// <summary>
    /// Ticket item indicating which color option to use.
    /// </summary>
    public class ColorTicketItem
    {
        /// <summary>
        /// Vendor ID of the color (required if the type is CUSTOM_COLOR or CUSTOM_MONOCHROME).
        /// </summary>
        public string VendorId { get; set; }

        /// <summary>
        /// Type of the color (required).
        /// </summary>
        public Color.Type Type { get; set; }
    }
}


text:
package eu.fp7.eagle.portal.ui.dashboard;

import static com.google.common.base.Preconditions.checkNotNull;

import java.util.Locale;

import eu.fp7.eagle.service.exception.EagleServiceException;

import eu.fp7.eagle.portal.ui.WebApp;
import eu.fp7.eagle.portal.ui.dashboard.i18n.DashboardMessages;
import eu.fp7.eagle.portal.ui.dashboard.service.DashboardService;
import eu.fp7.eagle.portal.ui.dashboard.view.DashboardViewProvider;
import eu.fp7.eagle.portal.ui.dashboard.view.badges.BadgesViewImpl;
import eu.fp7.eagle.portal.ui.dashboard.view.badges.BadgesViewPresenter;
import eu.fp7.eagle.portal.ui.util.UIUtil.WebAppMode;
import eu.fp7.eagle.portal.ui.view.ViewHandler;

/**
 * @author Arun Prakash [arun.prakash@fokus.fraunhofer.de]
 *
 * @since 07-Sep-2016 (1.0.0)
 * @version 1.0.0
 */

public class Dashboard extends WebApp<DashboardMessages, DashboardService, DashboardViewProvider<? extends ViewHandler>> {

	/**
	 * @param service
	 */
	public Dashboard(final DashboardService service) {
		super(new DashboardMessages(), checkNotNull(service, "Service must not be null"));
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see eu.fp7.eagle.portal.ui.WebApp#init(java.util.Locale,
	 * eu.fp7.eagle.portal.ui.util.UIUtil.WebAppMode)
	 */
	@Override
	protected void init(final Locale locale, final WebAppMode appMode) {
		super.init(locale, appMode, true);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see eu.fp7.eagle.portal.ui.WebApp#initWebAppMainView()
	 */
	@Override
	protected DashboardViewProvider<? extends ViewHandler> initWebAppMainView() throws EagleServiceException {
		return super.initWebAppView(new BadgesViewImpl(), new BadgesViewPresenter());
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see eu.fp7.eagle.portal.ui.WebApp#initWebAppPreferencesView()
	 */
	@Override
	protected DashboardViewProvider<? extends ViewHandler> initWebAppPreferencesView() throws EagleServiceException {
		// TODO Auto-generated method stub
		return null;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see eu.fp7.eagle.portal.ui.WebApp#initWebAppHelpView()
	 */
	@Override
	protected DashboardViewProvider<? extends ViewHandler> initWebAppHelpView() throws EagleServiceException {
		// TODO Auto-generated method stub
		return null;
	}

}


text:
Template['albumActions'].events({
  'click .ui.album-actions .album-settings.button' : function () {
    // todo: toggle settings section by id
    Session.set('settingsActive', !Session.get('settingsActive'));
    Session.set('settingsShow', !Session.get('settingsShow'));
  }
});


text:
package com.alibaba.tamper.core.helper;

import com.alibaba.tamper.core.BeanMappingException;

/**
 * 批量处理对象的holder处理
 *
 * @author jianghang 2011-6-2 下午12:44:26
 */
public class BatchObjectHolder {

    private Object[] batchValues = null;
    private int      currentIndex;

    public void setBatchValues(Object[] batchValues) {
        this.batchValues = batchValues;
    }

    public BatchObjectHolder(Object[] values){
        if (values == null) {
            throw new BeanMappingException("batch values is null!");
        }
        this.batchValues = values;
        this.currentIndex = -1;
    }

    public Object[] getBatchValues() {
        return batchValues;
    }

    public Object getNext() {
        currentIndex = currentIndex + 1;
        if (currentIndex > batchValues.length) {
            throw new BeanMappingException("batch values index is out of Array!");
        }
        return batchValues[currentIndex];
    }

    public void setObject(Object value) {
        batchValues[currentIndex] = value;
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="CompilerConfiguration">
    <bytecodeTargetLevel>
      <module name="idea-cli-inspector.git.main" target="1.8" />
      <module name="idea-cli-inspector.git.test" target="1.8" />
      <module name="projects.idea-cli-inspector.git.main" target="1.8" />
      <module name="projects.idea-cli-inspector.git.test" target="1.8" />
    </bytecodeTargetLevel>
  </component>
</project>


text:
from directory.models import StaticPage

def static_pages(request):
    all_static_pages = StaticPage.objects.all()

    return {
        'static_pages': all_static_pages,
    }


text:
<?php
/**
 * AffiliateLinkerLinksApi
 * PHP version 5
 *
 * @category Class
 * @package  Swagger\Client
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * RevenueWire JackFruit REST API (Alpha)
 *
 * This API *does not* represent the final product. Some of the APIs listed below are *highly experimental* and *will likely change* before the final release. They may come with *crashes and bugs* and may potentially cause *data loss*.
 *
 * OpenAPI spec version: v1
 *
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 *
 */

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

namespace Swagger\Client\Jackfruit;

use \Swagger\Client\ApiClient;
use \Swagger\Client\ApiException;
use \Swagger\Client\Configuration;
use \Swagger\Client\ObjectSerializer;

/**
 * AffiliateLinkerLinksApi Class Doc Comment
 *
 * @category Class
 * @package  Swagger\Client
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */
class AffiliateLinkerLinksApi
{
    /**
     * API Client
     *
     * @var \Swagger\Client\ApiClient instance of the ApiClient
     */
    protected $apiClient;

    /**
     * Constructor
     *
     * @param \Swagger\Client\ApiClient|null $apiClient The api client to use
     */
    public function __construct(\Swagger\Client\ApiClient $apiClient = null)
    {
        if ($apiClient === null) {
            $apiClient = new ApiClient();
        }

        $this->apiClient = $apiClient;
    }

    /**
     * Get API client
     *
     * @return \Swagger\Client\ApiClient get the API client
     */
    public function getApiClient()
    {
        return $this->apiClient;
    }

    /**
     * Set the API client
     *
     * @param \Swagger\Client\ApiClient $apiClient set the API client
     *
     * @return AffiliateLinkerLinksApi
     */
    public function setApiClient(\Swagger\Client\ApiClient $apiClient)
    {
        $this->apiClient = $apiClient;
        return $this;
    }

    /**
     * Operation affiliateLinksGet
     *
     *
     *
     * @param string $catalogFid Offer's catalog FID (optional)
     * @throws \Swagger\Client\ApiException on non-2xx response
     * @return \Swagger\Client\Model\InlineResponse200
     */
    public function affiliateLinksGet($catalogFid = null)
    {
        list($response) = $this->affiliateLinksGetWithHttpInfo($catalogFid);
        return $response;
    }

    /**
     * Operation affiliateLinksGetWithHttpInfo
     *
     *
     *
     * @param string $catalogFid Offer's catalog FID (optional)
     * @throws \Swagger\Client\ApiException on non-2xx response
     * @return array of \Swagger\Client\Model\InlineResponse200, HTTP status code, HTTP response headers (array of strings)
     */
    public function affiliateLinksGetWithHttpInfo($catalogFid = null)
    {
        // parse inputs
        $resourcePath = "/affiliatelinks";
        $httpBody = '';
        $queryParams = [];
        $headerParams = [];
        $formParams = [];
        $_header_accept = $this->apiClient->selectHeaderAccept(['application/json']);
        if (!is_null($_header_accept)) {
            $headerParams['Accept'] = $_header_accept;
        }
        $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json']);

        // query params
        if ($catalogFid !== null) {
            $queryParams['catalogFid'] = $this->apiClient->getSerializer()->toQueryValue($catalogFid);
        }
        // default format to json
        $resourcePath = str_replace("{format}", "json", $resourcePath);

        // for model (json/xml)
        if (isset($_tempBody)) {
            $httpBody = $_tempBody; // $_tempBody is the method argument, if present
        } elseif (count($formParams) > 0) {
            $httpBody = $formParams; // for HTTP post (form)
        }
        // this endpoint requires API key authentication
        $apiKey = $this->apiClient->getApiKeyWithPrefix('X-Authorization-JWT');
        if (strlen($apiKey) !== 0) {
            $headerParams['X-Authorization-JWT'] = $apiKey;
        }
        // this endpoint requires API key authentication
        $apiKey = $this->apiClient->getApiKeyWithPrefix('X-API-KEY');
        if (strlen($apiKey) !== 0) {
            $headerParams['X-API-KEY'] = $apiKey;
        }
        // make the API Call
        try {
            list($response, $statusCode, $httpHeader) = $this->apiClient->callApi(
                $resourcePath,
                'GET',
                $queryParams,
                $httpBody,
                $headerParams,
                '\Swagger\Client\Model\InlineResponse200',
                '/affiliatelinks'
            );

            return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\InlineResponse200', $httpHeader), $statusCode, $httpHeader];
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\InlineResponse200', $e->getResponseHeaders());
                    $e->setResponseObject($data);
                    break;
                case 500:
                    $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Error', $e->getResponseHeaders());
                    $e->setResponseObject($data);
                    break;
            }

            throw $e;
        }
    }
}


text:
using System;
using System.IO;

namespace ChocoPacker.SevenZip
{
    public class SevenZipExtractor : ISevenZipExtractor
    {
        private readonly string _sevenZipPath;

        public SevenZipExtractor(string sevenZipPath)
        {
            if (string.IsNullOrEmpty(sevenZipPath))
                throw new ArgumentNullException(nameof(sevenZipPath));

            if (!File.Exists(sevenZipPath))
                throw new ArgumentException($"Invalid path to 7za.exe provided: '{sevenZipPath}'");

            _sevenZipPath = sevenZipPath;
        }

        public IArchive OpenArchive(string path) => new Archive(_sevenZipPath, path);
    }
}


text:
if [ "`uname`" == "Darwin" ]; then
    LIBTOOLIZE=glibtoolize
else
    LIBTOOLIZE=libtoolize
fi

$LIBTOOLIZE && autoreconf --install


text:
#ifndef __REMOVE_H
#define __REMOVE_H

#include "options.h"

int remove_link(const char *path);
int remove_recursive(const char *const path);

#endif /* __REMOVE_H */


text:
<?php

class Vclub extends Storage
{
    public function __construct(){
        parent::__construct();
    }

    /**
     * Check directory and return list of media files
     *
     * @param string $name
     * @return array
     */
    public function checkMedia($name){
        $result = array();

        $result['series'] = array();
        $result['series_file'] = array();
        $result['files']  = array();

        $md5_sum = array();
        $md5_file = VIDEO_STORAGE_DIR.$name.'/'.$name.'.md5';

        if (is_file($md5_file)){
            $md5_content = file($md5_file);

            foreach ($md5_content as $md5_record){
                list($md5, $media_file) = @preg_split("/[\s\t]+/", $md5_record);

                if(strpos($media_file, "*") === 0){
                    $media_file = substr($media_file, 1, strlen($media_file));
                }

                if (strpos($media_file, "/") !== false){
                    preg_match("/([^\/]*)\.(".$this->media_ext_str.")$/i", $media_file, $file_arr);
                    $media_file = $file_arr[0];
                }

                $md5_sum[trim($media_file)] = trim($md5);
            }
        }

        if(is_file('/tmp/'.$name.'_'.$this->storage_name.'.pid')){
            $status = 'counting';
        }else{
            $status = 'done';
        }

        if ($handle = @opendir(VIDEO_STORAGE_DIR.$name)) {

            $file_list = scandir(VIDEO_STORAGE_DIR.$name);

            $subtitles = array_filter($file_list, function($file){
                return in_array(substr($file, strrpos($file, '.') + 1), array('srt', 'sub', 'ass'));
            });

            while (false !== ($file = readdir($handle))) {

                if ($file != "." && $file != ".." && preg_match("/([\S\s]+)\.(".$this->media_ext_str.")$/i", $file)) {

                    array_key_exists($file, $md5_sum) ? $sum = $md5_sum[$file] : $sum='';

                    $info = array(
                        'name'   => $file,
                        'md5'    => $sum,
                        'status' => $status
                    );

                    if (preg_match("/^([\d]+)\.(".$this->media_ext_str.")$/i", $file, $tmp_arr)){
                        $result['series'][] = (int)$tmp_arr[1];
                        $result['series_file'][] = $file;
                    } else if (preg_match("/s\d+e(\d+).*(".$this->media_ext_str.")$/i", $file, $tmp_arr)){
                        $result['series'][] = (int)$tmp_arr[1];
                        $result['series_file'][] = $file;
                    }

                    $movie_base = substr($file, 0, strrpos($file, '.'));

                    $movie_subtitles = array_filter($subtitles, function($subtitle_file) use ($movie_base, $result){
                        if (empty($result['series'])){
                            return strpos($subtitle_file, $movie_base) === 0;
                        }else{
                            return substr($subtitle_file, 0, strrpos($subtitle_file, '.')) == $movie_base;
                        }
                    });

                    if (!empty($movie_subtitles)){
                        $info['subtitles'] = array_values($movie_subtitles);
                    }

                    $result['files'][] = $info;
                }
            }
            @closedir($handle);
        }else{
            //throw new IOException('Could not open directory '.VIDEO_STORAGE_DIR.$name.' on '.$this->storage_name);
        }

        return $result;
    }

    /**
     * Create hard link $file in stb home directory
     *
     * @param string $media_file
     * @param int $media_id
     * @param string $proto
     * @return boolean
     */
    public function createLink($media_file, $media_id, $proto = ''){

        $this->user->checkHome();

        preg_match("/([\S\s]+)\.(".$this->media_ext_str.")$/i", $media_file, $arr);

        $ext = $arr[2];

        $from = VIDEO_STORAGE_DIR.$media_file;

        $path = dirname($from);
        $file = basename($from);

        $movie_base = substr($file, 0, strrpos($file, '.'));

        $file_list = scandir($path);

        if ($file_list === false){
            throw new IOException('Could not scan dir'.$path.' on '.$this->storage_name);
        }

        $subtitles = array_filter($file_list, function($file){
            return in_array(substr($file, strrpos($file, '.') + 1), array('srt', 'sub', 'ass'));
        });

        $movie_subtitles = array_filter($subtitles, function($subtitle_file) use ($movie_base){
            return strpos($subtitle_file, $movie_base) === 0;
        });

        if (!empty($movie_subtitles)){
            foreach ($movie_subtitles as $subtitle){

                $from_sub = $path.'/'.$subtitle;
                $to_sub   = NFS_HOME_PATH.$this->user->getMac().'/'.$subtitle;

                if ($proto == 'http'){
                    $link_result = @symlink($from_sub, $to_sub);
                }else{
                    $link_result = @link($from_sub, $to_sub);
                }

                if (!$link_result){
                    throw new IOException('Could not create link '.$from_sub.' to '.$to_sub.' on '.$this->storage_name);
                }
            }
        }

        $to = NFS_HOME_PATH.$this->user->getMac().'/'.$media_id.'.'.$ext;

        if ($proto == 'http'){
            $link_result = @symlink($from, $to);
        }else{
            $link_result = @link($from, $to);
        }

        if (!$link_result){
            throw new IOException('Could not create link '.$from.' to '.$to.' on '.$this->storage_name);
        }

        if (!is_readable($to)){
            throw new IOException('File '.$to.' is not readable on '.$this->storage_name);
        }

        return true;
    }

    /**
     * Create directory for video
     *
     * @param string $name
     * @return boolean
     * @throws Exception
     */
    public function createDir($name){
        if (!is_dir(VIDEO_STORAGE_DIR.$name)) {
            umask(0);
            if(!mkdir(VIDEO_STORAGE_DIR.$name, 0777)){
                throw new IOException('Could not create directory '.VIDEO_STORAGE_DIR.$name.' on '.$this->storage_name);
            }
        }
        return true;
    }

    /**
     * Start counting MD5 SUM for media
     *
     * @param string $media_name
     * @throws Exception
     */
    public function startMD5Sum($media_name){

        if (!is_dir(VIDEO_STORAGE_DIR.$media_name)){
            throw new IOException('Directory '.VIDEO_STORAGE_DIR.$media_name.' not exist on '.$this->storage_name);
        }

        if (!is_writable(VIDEO_STORAGE_DIR.$media_name)){
            throw new IOException('Directory '.VIDEO_STORAGE_DIR.$media_name.' is not writable on '.$this->storage_name);
        }

        if (!function_exists('exec')){
            throw new BadFunctionCallException('Function [exec] not exist on '.$this->storage_name);
        }

        $storage_dir = VIDEO_STORAGE_DIR;
        $launch_dir = substr($_SERVER['SCRIPT_FILENAME'], 0, strrpos($_SERVER['SCRIPT_FILENAME'],'/'));
        exec("$launch_dir/md5sumlauncher.sh $media_name $storage_dir $this->storage_name > /dev/null &");
    }
}

?>


text:
<?php

$lang = array(

//----------------------------------------
// Required for MODULES page
//----------------------------------------

"comment_module_name" =>
"Comment",

"comment_module_description" =>
"User commenting system",

//----------------------------------------

'comment_moved' =>
'Comment moved',

'comments_moved' =>
'Comments moved',

'filter_comments' =>
'Filter Comments',

'comment' =>
'Comment',

'comments' =>
'Comments',

'edit_comment' =>
'Edit Comment',

'settings' =>
'Settings',

'comment_settings' =>
'Comment Settings',

'delete_confirm' =>
'Delete Comment Confirmation',

'delete_comment_confirm' =>
'Are you sure you want to permanently delete this comment?',

'delete_comments_confirm' =>
'Are you sure you want to permanently delete these comments?',

'comment_deleted' =>
'Comment Deleted',

'status_changed' =>
'Status Changed',

'comment_word_censoring' =>
'Force word censoring for comments',

'comment_moderation_override' =>
'Moderate expired entries',

'comment_smart_notifications' =>
'Enable Smart Notifications',

'selection_required' =>
'At least one selection is required to submit',

'close_selected' =>
'Set Status to Closed',

'open_selected' =>
'Set Status to Open',

'pending_selected' =>
'Set Status to Pending',

'move_selected' =>
'Move Selected',

'instructions' =>
'Instructions: ',

'move' =>
'Move',

'move_comment_instr' =>
'Enter the new entry id number:',

'registered_member' =>
'Registered member',

'url' =>
'URL',

'location' =>
'Location',

'choose_entry_for_comment_move' =>
'Choose Entry for Comment Move',

'move_comments_to_entry' =>
'Move Comments to Entry',

'filter_by_channel' =>
'Filter by Channel',

'filter_by_status' =>
'Filter by Status',

'filter_by_author' =>
'Filter by Author',

'collapsed_display' =>
'Collapsed Display',

'expanded_display' =>
'Expanded Display',

'date_range' =>
'Date Range',

'keywords' =>
'Keywords',

'open' =>
'Open',

'closed' =>
'Closed',

'entry_title' =>
'Entry Title',

'email' =>
'Email',

'name' =>
'Name',

'ip_address' =>
'IP',

'delete_selected' =>
'Delete Selected',

'blacklist' =>
'Add IPs to Blacklist',

'search_in_comments' =>
'Search in Comments',

'search_in_ips' =>
'Search in IPs',

'search_in_entry_titles' =>
'Search in Entry Titles',

'search_in_names' =>
'Search in Names',

'search_in_emails' =>
'Search in Email Addresses',

'today' =>
'Today',

'past_day' =>
'Last 24 hours',

'past_week' =>
'Last 7 days',

'past_month' =>
'Last 30 days',

'past_six_months' =>
'Last 180 days',

'past_year' =>
'Last 365 days',

'any_date' =>
'Custom Date Range',

//

"cmt_commenting_has_expired" =>
"Commenting is not available in this channel entry.",

"cmt_name_not_allowed" =>
"The name you are posting with is reserved.  Please choose a different name.",

"cmt_must_be_member" =>
"You must be a registered member to post comments",

"cmt_no_authorized_for_comments" =>
"You are not allowed to post comments",

"cmt_account_not_active" =>
"Your membership account has not been activated yet",

"cmt_comments_not_allowed" =>
"Comments are not allowed in this channel",

"cmt_missing_name" =>
"The name field is required",

"cmt_missing_comment" =>
"The comment field is required",

"cmt_missing_email" =>
"The email field is required",

"cmt_invalid_email" =>
"The email address you submitted is not valid",

"cmt_banned_email" =>
"The email address you submitted is banned",

"cmt_too_large" =>
"The comment you submitted contains %n characters.  Only %x characters are allowed.",

"cmt_comments_timelock" =>
"You are only allowed to post comments every %s seconds.",

"cmt_duplicate_comment_warning" =>
"Unable to receive your comment at this time.",

"cmt_no_preview_template_specified" =>
"The comment form tag does not contain the location of your preview template.",

"cmt_comment_response_title" =>
"Someone just responded to your comment",

"cmt_comment_response_body" =>
"Someone just responded to the entry you subscribed to at:",

"cmt_comment_title" =>
"The title of the entry is:",

"cmt_comment_url" =>
"You can see the comment at the following URL:",

"cmt_comment_removal" =>
"To stop receiving notifications for this comment, click here:",

"cmt_notification_removal" =>
"Notification removal",

"cmt_you_have_been_removed" =>
"You have been removed from receiving further notifications.",

"cmt_comment_accepted" =>
"Comment Accepted",

"cmt_will_be_reviewed" =>
"Your comment will be reviewed by a moderator for approval.",

"cmt_return_to_comments" =>
"Return to Comments",

'you_have_been_subscribed' =>
'You are now subscribed to the following entry:',

'you_have_been_unsubscribed' =>
'Your subscription to the following entry has been removed:',

'cmt_subscribe' =>
'Subscribe to this comment',

'cmt_unsubscribe' =>
'Un-subscribe from this comment',

'invalid_entry_id' =>
'Invalid Entry ID',

'no_valid_comments' =>
'No Valid Comments',

'comment_edit_time_limit' =>
'Comment Edit Time Limit (in seconds, set to 0 for no limit)',

'already_subscribed' =>
'You are already subscribed to this comment.',

'not_currently_subscribed' =>
'You do not appear to be subscribed to the entry ID you submitted',

'invalid_subscription' =>
'The URL you submitted is invalid',

'settings_updated' =>
'Settings Updated',

'comment_updated' =>
'Comment Updated',

'start_date' =>
'Start Date',

'end_date' =>
'End Date',

'expand' =>
'Expand',

'no_results' =>
'No Results',

);

/* End of file comment_lang.php */
/* Location: ./system/expressionengine/language/english/comment_lang.php */


text:
<?xml version='1.0' encoding='UTF-8'?>
<footer name="footer">
  <category title="Bydelsgaranti">
    <element href="/sor-tromsoya">Sør-Tromsøya</element>
    <element href="/midtpa">Midt på Tromsøya</element>
    <element href="/nordoya">Nord-Tromsøya</element>
    <element href="/langnes_mortensnes/">Mortensnes-Langnes</element>
  </category>
  <category title="Bydelsgaranti">
    <element href="/sentrum">Sentrum</element>
    <element href="/tromsdalen">Tromsdalen</element>
    <element href="/hamna">Hamna</element>
    <element href="/kroken/">Tomasjord/Lunheim/Kroken</element>
  </category>
  <category title="Hva skjer i din bydel?">
    <element href="mailto: tips@byavisatromso.no">Send oss en e-post</element>
    <element href="http://www.Facebook.com/byavisatromso">Besøk vår Facebook-side!</element>
    <element href="http://www.nordlys.no">Siste nytt fra Nordlys</element>
    <element href="https://www.buyandread.com/custom/ePaper.htm?pub=byavisatromso">Bla i papirutgaven vår digitalt!</element>
  </category>
  <category title="Kundeservice">
    <element>Adresse: Rådhusgata 3, Tromsø</element>
    <element href="mailto:anders.opdahl@nordlys.no">Ansvarlig redaktør: Anders Opdahl</element>
    <element href="mailto:stian.saur@byavisatromso.no">Redaktør: Stian Saur</element>
    <element href="http://presse.no/Etisk-regelverk/Redaktoerplakaten">Redaktørplakaten</element>
    <element href="http://www.pfu.no">PFU</element>
    <element>Kontakt annonseavdelingen!</element>
    <element href="mailto:grete@byavisatromso.no">Grete Nilsen</element>
    <element href="mailto:Lasse@byavisatromso.no">Lasse Aleksandersen</element>
  </category>
</footer>


text:
package org.nem.deploy;

import org.nem.core.utils.*;

import java.io.*;
import java.util.Properties;
import java.util.logging.*;

/**
 * Static class that is used to bootstrap the logging subsystem.
 */
public class LoggingBootstrapper {
	private static final Logger LOGGER = Logger.getLogger(LoggingBootstrapper.class.getName());

	/**
	 * Bootstraps the logging subsystem.
	 *
	 * @param nemFolder The NEM folder location.
	 */
	public static void bootstrap(final String nemFolder) {
		try (final InputStream inputStream = LoggingBootstrapper.class.getClassLoader().getResourceAsStream("logalpha.properties");
				final InputStream inputStringStream = adaptFileLocation(inputStream, nemFolder)) {
			final LogManager logManager = LogManager.getLogManager();
			logManager.readConfiguration(inputStringStream);
			final File logFile = new File(logManager.getProperty("java.util.logging.FileHandler.pattern"));
			final File logDirectory = new File(logFile.getParent());
			if (!logDirectory.exists() && !logDirectory.mkdirs()) {
				throw new IOException(String.format("unable to create log directory %s", logDirectory));
			}

			LOGGER.info("NEM logging has been bootstrapped!");
		} catch (final IOException e) {
			LOGGER.severe("Could not load default logging properties file");
			LOGGER.severe(e.toString());
		}
	}

	/**
	 * log configuration may include a placeholder for the nem folder The method replaces the pattern ${nem.folder} with the value defined
	 * within the NisConfiguration Only for "java.util.logging.FileHandler.pattern" value
	 *
	 * @param inputStream stream of the logging properties.
	 * @param nemFolder The NEM folder location.
	 * @return new stream which contains the replaced FileHandler.pattern
	 * @throws IOException
	 */
	private static InputStream adaptFileLocation(final InputStream inputStream, final String nemFolder) throws IOException {
		final Properties props = new Properties();
		props.load(inputStream);
		final String tmpStr = props.getProperty("java.util.logging.FileHandler.pattern");
		props.setProperty("java.util.logging.FileHandler.pattern", StringUtils.replaceVariable(tmpStr, "nem.folder", nemFolder));
		final StringWriter stringWriter = new StringWriter();
		props.store(stringWriter, null);
		return new ByteArrayInputStream(StringEncoder.getBytes(stringWriter.toString()));
	}
}


text:
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

from matplotlib.text import Text

FACES = ["plain", "italic", "bold", "bold.italic"]

class element_text(object):
    """
    Customize text for your plots

    Parameters
    ----------
    text:
        value of text
    family:
        font family
    face:
        ????
    color:
        color of the text
    size:
        font size
    hjust:
        horizontal adjustment from true x
    vjust:
        vertical adjustment from true y
    angle:
        rotate text
    lineheight:
        spacing between lines of text
    margin:
        margin around text

    Examples
    --------
    >>> theme(axis_text=element_text(size=20))
    >>> theme(x_axis_text=element_text(color="orange"), y_axis_text=element_text(color="blue"))
    >>> theme(axis_text=element_text(size=20), x_axis_text=element_text(color="orange"), y_axis_text=element_text(color="blue"))
    """
    def __init__(self, text=None, family=None, face=None, color=None, size=None,
            hjust=0, vjust=0, angle=None, lineheight=None, margin=None,
            debug=None):

        if text is None:
            text = ""

        # if face not in FACES:
        #     raise Exception("Invalid font face: %s" + face)

        self.args = [hjust, vjust, text]
        font = dict(
            family=family,
            weight=face,
            rotation=angle,
            color=color,
            linespacing=lineheight,
            size=size
        )
        font = {k: v for k,v in font.items() if v}
        self.kwargs = dict(horizontalalignment='center', fontdict=font)

    def override(self, x, y, overrides={}):
        self.args[0] += x
        self.args[1] += y
        for key, value in overrides.items():
            self.kwargs[key] = value

    def apply_to_fig(self, fig):
        fig.text(*self.args, **self.kwargs)


text:
.class Landroid/gesture/GestureLibraries$FileGestureLibrary;
.super Landroid/gesture/GestureLibrary;
.source "GestureLibraries.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/gesture/GestureLibraries;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "FileGestureLibrary"
.end annotation

# instance fields
.field private final mPath:Ljava/io/File;

# direct methods
.method public constructor <init>(Ljava/io/File;)V
    .locals 0
    .param p1, "path"    # Ljava/io/File;

    .prologue
    .line 54
    invoke-direct {p0}, Landroid/gesture/GestureLibrary;-><init>()V

    .line 55
    iput-object p1, p0, Landroid/gesture/GestureLibraries$FileGestureLibrary;->mPath:Ljava/io/File;

    .line 56
    return-void
.end method

# virtual methods
.method public isReadOnly()Z
    .locals 1

    .prologue
    .line 60
    iget-object v0, p0, Landroid/gesture/GestureLibraries$FileGestureLibrary;->mPath:Ljava/io/File;

    invoke-virtual {v0}, Ljava/io/File;->canWrite()Z

    move-result v0

    if-nez v0, :cond_0

    const/4 v0, 0x1

    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

.method public load()Z
    .locals 6

    .prologue
    .line 91
    const/4 v2, 0x0

    .line 92
    .local v2, "result":Z
    iget-object v1, p0, Landroid/gesture/GestureLibraries$FileGestureLibrary;->mPath:Ljava/io/File;

    .line 93
    .local v1, "file":Ljava/io/File;
    invoke-virtual {v1}, Ljava/io/File;->exists()Z

    move-result v3

    if-eqz v3, :cond_0

    invoke-virtual {v1}, Ljava/io/File;->canRead()Z

    move-result v3

    if-eqz v3, :cond_0

    .line 95
    :try_start_0
    iget-object v3, p0, Landroid/gesture/GestureLibraries$FileGestureLibrary;->mStore:Landroid/gesture/GestureStore;

    new-instance v4, Ljava/io/FileInputStream;

    invoke-direct {v4, v1}, Ljava/io/FileInputStream;-><init>(Ljava/io/File;)V

    const/4 v5, 0x1

    invoke-virtual {v3, v4, v5}, Landroid/gesture/GestureStore;->load(Ljava/io/InputStream;Z)V
    :try_end_0
    .catch Ljava/io/FileNotFoundException; {:try_start_0 .. :try_end_0} :catch_0
    .catch Ljava/io/IOException; {:try_start_0 .. :try_end_0} :catch_1

    .line 96
    const/4 v2, 0x1

    .line 104
    :cond_0
    :goto_0
    return v2

    .line 97
    :catch_0
    move-exception v0

    .line 98
    .local v0, "e":Ljava/io/FileNotFoundException;
    const-string v3, "Gestures"

    new-instance v4, Ljava/lang/StringBuilder;

    invoke-direct {v4}, Ljava/lang/StringBuilder;-><init>()V

    const-string v5, "Could not load the gesture library from "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    iget-object v5, p0, Landroid/gesture/GestureLibraries$FileGestureLibrary;->mPath:Ljava/io/File;

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-static {v3, v4, v0}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I

    goto :goto_0

    .line 99
    .end local v0    # "e":Ljava/io/FileNotFoundException;
    :catch_1
    move-exception v0

    .line 100
    .local v0, "e":Ljava/io/IOException;
    const-string v3, "Gestures"

    new-instance v4, Ljava/lang/StringBuilder;

    invoke-direct {v4}, Ljava/lang/StringBuilder;-><init>()V

    const-string v5, "Could not load the gesture library from "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    iget-object v5, p0, Landroid/gesture/GestureLibraries$FileGestureLibrary;->mPath:Ljava/io/File;

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-static {v3, v4, v0}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I

    goto :goto_0
.end method

.method public save()Z
    .locals 7

    .prologue
    const/4 v3, 0x1

    .line 64
    iget-object v4, p0, Landroid/gesture/GestureLibraries$FileGestureLibrary;->mStore:Landroid/gesture/GestureStore;

    invoke-virtual {v4}, Landroid/gesture/GestureStore;->hasChanged()Z

    move-result v4

    if-nez v4, :cond_0

    .line 87
    :goto_0
    return v3

    .line 66
    :cond_0
    iget-object v1, p0, Landroid/gesture/GestureLibraries$FileGestureLibrary;->mPath:Ljava/io/File;

    .line 68
    .local v1, "file":Ljava/io/File;
    invoke-virtual {v1}, Ljava/io/File;->getParentFile()Ljava/io/File;

    move-result-object v2

    .line 69
    .local v2, "parentFile":Ljava/io/File;
    invoke-virtual {v2}, Ljava/io/File;->exists()Z

    move-result v4

    if-nez v4, :cond_1

    .line 70
    invoke-virtual {v2}, Ljava/io/File;->mkdirs()Z

    move-result v4

    if-nez v4, :cond_1

    .line 71
    const/4 v3, 0x0

    goto :goto_0

    .line 75
    :cond_1
    const/4 v3, 0x0

    .line 78
    .local v3, "result":Z
    :try_start_0
    invoke-virtual {v1}, Ljava/io/File;->createNewFile()Z

    .line 79
    iget-object v4, p0, Landroid/gesture/GestureLibraries$FileGestureLibrary;->mStore:Landroid/gesture/GestureStore;

    new-instance v5, Ljava/io/FileOutputStream;

    invoke-direct {v5, v1}, Ljava/io/FileOutputStream;-><init>(Ljava/io/File;)V

    const/4 v6, 0x1

    invoke-virtual {v4, v5, v6}, Landroid/gesture/GestureStore;->save(Ljava/io/OutputStream;Z)V
    :try_end_0
    .catch Ljava/io/FileNotFoundException; {:try_start_0 .. :try_end_0} :catch_0
    .catch Ljava/io/IOException; {:try_start_0 .. :try_end_0} :catch_1

    .line 80
    const/4 v3, 0x1

    goto :goto_0

    .line 81
    :catch_0
    move-exception v0

    .line 82
    .local v0, "e":Ljava/io/FileNotFoundException;
    const-string v4, "Gestures"

    new-instance v5, Ljava/lang/StringBuilder;

    invoke-direct {v5}, Ljava/lang/StringBuilder;-><init>()V

    const-string v6, "Could not save the gesture library in "

    invoke-virtual {v5, v6}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v5

    iget-object v6, p0, Landroid/gesture/GestureLibraries$FileGestureLibrary;->mPath:Ljava/io/File;

    invoke-virtual {v5, v6}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v5

    invoke-virtual {v5}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v5

    invoke-static {v4, v5, v0}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I

    goto :goto_0

    .line 83
    .end local v0    # "e":Ljava/io/FileNotFoundException;
    :catch_1
    move-exception v0

    .line 84
    .local v0, "e":Ljava/io/IOException;
    const-string v4, "Gestures"

    new-instance v5, Ljava/lang/StringBuilder;

    invoke-direct {v5}, Ljava/lang/StringBuilder;-><init>()V

    const-string v6, "Could not save the gesture library in "

    invoke-virtual {v5, v6}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v5

    iget-object v6, p0, Landroid/gesture/GestureLibraries$FileGestureLibrary;->mPath:Ljava/io/File;

    invoke-virtual {v5, v6}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v5

    invoke-virtual {v5}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v5

    invoke-static {v4, v5, v0}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I

    goto :goto_0
.end method


text:
The MVC Crystal Framework for Rubyists

**Work in progress**

## Installation

TODO

## Usage

TODO

## Development

TODO

## Generators Rails style

### Generate model
```shell
steven generator model foo bar:integer
```

```crystal
class Foot < ActiveRecord::Base
end
```

### Generate controller
```shell
steven generate controller hello index
```

```crystal
class HelloController < Steven::Controller
  get "/hello" do
    view("hello/index")
  end
end
```

### Generate migrations
```shell
steven g migration add_description_to_products description:string
```

```crystal
TODO
```

## Contributing

1. Fork it ( https://github.com/dayvsonlima/steven-framework/fork )
2. Create your feature branch (git checkout -b my-new-feature)
3. Commit your changes (git commit -am 'Add some feature')
4. Push to the branch (git push origin my-new-feature)
5. Create a new Pull Request

## Contributors

- [dayvsonlima](https://github.com/dayvsonlima) Dayvson Lima - creator, maintainer


text:
#include <aws/swf/model/ListClosedWorkflowExecutionsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::SWF::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

ListClosedWorkflowExecutionsRequest::ListClosedWorkflowExecutionsRequest() :
    m_domainHasBeenSet(false),
    m_startTimeFilterHasBeenSet(false),
    m_closeTimeFilterHasBeenSet(false),
    m_executionFilterHasBeenSet(false),
    m_closeStatusFilterHasBeenSet(false),
    m_typeFilterHasBeenSet(false),
    m_tagFilterHasBeenSet(false),
    m_nextPageTokenHasBeenSet(false),
    m_maximumPageSize(0),
    m_maximumPageSizeHasBeenSet(false),
    m_reverseOrder(false),
    m_reverseOrderHasBeenSet(false)
{
}

Aws::String ListClosedWorkflowExecutionsRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_domainHasBeenSet)
  {
   payload.WithString("domain", m_domain);

  }

  if(m_startTimeFilterHasBeenSet)
  {
   payload.WithObject("startTimeFilter", m_startTimeFilter.Jsonize());

  }

  if(m_closeTimeFilterHasBeenSet)
  {
   payload.WithObject("closeTimeFilter", m_closeTimeFilter.Jsonize());

  }

  if(m_executionFilterHasBeenSet)
  {
   payload.WithObject("executionFilter", m_executionFilter.Jsonize());

  }

  if(m_closeStatusFilterHasBeenSet)
  {
   payload.WithObject("closeStatusFilter", m_closeStatusFilter.Jsonize());

  }

  if(m_typeFilterHasBeenSet)
  {
   payload.WithObject("typeFilter", m_typeFilter.Jsonize());

  }

  if(m_tagFilterHasBeenSet)
  {
   payload.WithObject("tagFilter", m_tagFilter.Jsonize());

  }

  if(m_nextPageTokenHasBeenSet)
  {
   payload.WithString("nextPageToken", m_nextPageToken);

  }

  if(m_maximumPageSizeHasBeenSet)
  {
   payload.WithInteger("maximumPageSize", m_maximumPageSize);

  }

  if(m_reverseOrderHasBeenSet)
  {
   payload.WithBool("reverseOrder", m_reverseOrder);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection ListClosedWorkflowExecutionsRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "SimpleWorkflowService.ListClosedWorkflowExecutions"));
  return headers;

}


text:
using erl.Oracle.TnsNames.Antlr4.Runtime;
using erl.Oracle.TnsNames.Antlr4.Runtime.Misc;
using erl.Oracle.TnsNames.Antlr4.Runtime.Sharpen;
using System.IO;

namespace erl.Oracle.TnsNames.Antlr4.Runtime
{
    ///
    /// The interface for defining strategies to deal with syntax errors encountered
    /// during a parse by ANTLR-generated parsers.
    ///
    /// <remarks>
    /// The interface for defining strategies to deal with syntax errors encountered
    /// during a parse by ANTLR-generated parsers. We distinguish between three
    /// different kinds of errors:
    ///

    ///
The parser could not figure out which path to take in the ATN (none of
    /// the available alternatives could possibly match)

    ///
The current input does not match what we were looking for

    ///
A predicate evaluated to false

    ///

    /// Implementations of this interface report syntax errors by calling
    /// <see cref="Parser.NotifyErrorListeners(string)"/>
    /// .
    ///
TODO: what to do about lexers

    /// </remarks>
    public interface IAntlrErrorStrategy
    {
        ///
        /// Reset the error handler state for the specified
        /// <paramref name="recognizer"/>
        /// .
        ///
        /// <param name="recognizer">the parser instance</param>
        void Reset(Parser recognizer);

        ///
        /// This method is called when an unexpected symbol is encountered during an
        /// inline match operation, such as
        /// <see cref="Parser.Match(int)"/>
        /// . If the error
        /// strategy successfully recovers from the match failure, this method
        /// returns the
        /// <see cref="IToken"/>
        /// instance which should be treated as the
        /// successful result of the match.
        ///
Note that the calling code will not report an error if this method
        /// returns successfully. The error strategy implementation is responsible
        /// for calling
        /// <see cref="Parser.NotifyErrorListeners(string)"/>
        /// as appropriate.

        ///
        /// <param name="recognizer">the parser instance</param>
        /// <exception cref="RecognitionException">
        /// if the error strategy was not able to
        /// recover from the unexpected input symbol
        /// </exception>
        /// <exception cref="erl.Oracle.TnsNames.Antlr4.Runtime.RecognitionException"/>
        [return: NotNull]
        IToken RecoverInline(Parser recognizer);

        ///
        /// This method is called to recover from exception
        /// <paramref name="e"/>
        /// . This method is
        /// called after
        /// <see cref="ReportError(Parser, RecognitionException)"/>
        /// by the default exception handler
        /// generated for a rule method.
        ///
        /// <seealso cref="ReportError(Parser, RecognitionException)"/>
        /// <param name="recognizer">the parser instance</param>
        /// <param name="e">the recognition exception to recover from</param>
        /// <exception cref="RecognitionException">
        /// if the error strategy could not recover from
        /// the recognition exception
        /// </exception>
        /// <exception cref="erl.Oracle.TnsNames.Antlr4.Runtime.RecognitionException"/>
        void Recover(Parser recognizer, RecognitionException e);

        ///
        /// This method provides the error handler with an opportunity to handle
        /// syntactic or semantic errors in the input stream before they result in a
        /// <see cref="RecognitionException"/>
        /// .
        ///
The generated code currently contains calls to
        /// <see cref="Sync(Parser)"/>
        /// after
        /// entering the decision state of a closure block (
        /// <c>(...)*</c>
        /// or
        /// <c>(...)+</c>
        /// ).

        ///
For an implementation based on Jim Idle's "magic sync" mechanism, see
        /// <see cref="DefaultErrorStrategy.Sync(Parser)"/>
        /// .

        ///
        /// <seealso cref="DefaultErrorStrategy.Sync(Parser)"/>
        /// <param name="recognizer">the parser instance</param>
        /// <exception cref="RecognitionException">
        /// if an error is detected by the error
        /// strategy but cannot be automatically recovered at the current state in
        /// the parsing process
        /// </exception>
        /// <exception cref="erl.Oracle.TnsNames.Antlr4.Runtime.RecognitionException"/>
        void Sync(Parser recognizer);

        ///
        /// Tests whether or not
        /// <paramref name="recognizer"/>
        /// is in the process of recovering
        /// from an error. In error recovery mode,
        /// <see cref="Parser.Consume()"/>
        /// adds
        /// symbols to the parse tree by calling
        /// <see cref="ParserRuleContext.AddErrorNode(IToken)"/>
        /// instead of
        /// <see cref="ParserRuleContext.AddChild(IToken)"/>
        /// .
        ///
        /// <param name="recognizer">the parser instance</param>
        /// <returns>
        ///
        /// <see langword="true"/>
        /// if the parser is currently recovering from a parse
        /// error, otherwise
        /// <see langword="false"/>
        /// </returns>
        bool InErrorRecoveryMode(Parser recognizer);

        ///
        /// This method is called by when the parser successfully matches an input
        /// symbol.
        ///
        /// <remarks>
        /// This method is called by when the parser successfully matches an input
        /// symbol.
        /// </remarks>
        /// <param name="recognizer">the parser instance</param>
        void ReportMatch(Parser recognizer);

        ///
        /// Report any kind of
        /// <see cref="RecognitionException"/>
        /// . This method is called by
        /// the default exception handler generated for a rule method.
        ///
        /// <param name="recognizer">the parser instance</param>
        /// <param name="e">the recognition exception to report</param>
        void ReportError(Parser recognizer, RecognitionException e);
    }
}


text:
**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public NavigationNode[] NavigationNode { get; set; }
```

### Property Value
Type: [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.NavigationNode[]](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.NavigationNode.md)

## See also
- [StructuralNavigation](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.StructuralNavigation.md)
- [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605.md)


text:
<?php
/**
 * @license © 2005 - 2016 by Zend Technologies Ltd. All rights reserved.
 */

namespace FluxoCaixa\Factory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use FluxoCaixa\Form\ReceberForm;

/**
 * SIGA-Smart
 *
 * Esta class foi gerada via Zend\Code\Generator.
 */
class ReceberFormFactory implements FactoryInterface
{

    /**
     * createService Factory
     *
     * @return createService
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        return new ReceberForm($serviceLocator);
    }

}


text:
package org.jvnet.hyperjaxb3.ejb.strategy.mapping;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EnumType;
import javax.xml.namespace.QName;

import org.jvnet.hyperjaxb3.codemodel.util.JTypeUtils;
import org.jvnet.hyperjaxb3.xsd.util.XMLSchemaConstrants;
import org.jvnet.hyperjaxb3.xsom.SimpleTypeAnalyzer;
import org.jvnet.hyperjaxb3.xsom.TypeUtils;
import org.jvnet.jaxb2_commons.util.FieldAccessorUtils;

import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JMethod;
import com.sun.codemodel.JType;
import com.sun.java.xml.ns.persistence.orm.AttributeOverride;
import com.sun.java.xml.ns.persistence.orm.Basic;
import com.sun.java.xml.ns.persistence.orm.Column;
import com.sun.java.xml.ns.persistence.orm.EmbeddableAttributes;
import com.sun.java.xml.ns.persistence.orm.Embedded;
import com.sun.java.xml.ns.persistence.orm.Lob;
import com.sun.tools.xjc.Options;
import com.sun.tools.xjc.model.CClassInfo;
import com.sun.tools.xjc.model.CEnumLeafInfo;
import com.sun.tools.xjc.model.CPropertyInfo;
import com.sun.tools.xjc.model.CTypeInfo;
import com.sun.tools.xjc.outline.ClassOutline;
import com.sun.tools.xjc.outline.FieldOutline;
import com.sun.tools.xjc.outline.Outline;
import com.sun.xml.xsom.XSComponent;

public final class DefaultAttributeMapping implements AttributeMapping {

	public final Column createColumn(Mapping context,
			FieldOutline fieldOutline, Column column) {

		if (column == null) {
			column = new Column();
		}

		if (column.getName() == null || "##default".equals(column.getName())) {
			column.setName(context.getNaming().getColumn$Name(context,
					fieldOutline));
		}

		assignColumn$LengthPrecisionScale(fieldOutline, column);
		return column;
	}

	private void assignColumn$LengthPrecisionScale(FieldOutline fieldOutline,
			final Column column) {
		if (column.getLength() == null) {
			column.setLength(createColumn$Length(fieldOutline));
		}

		final Integer precision = createColumn$Precision(fieldOutline);
		final Integer scale = createColumn$Scale(fieldOutline);

		if (precision != null && precision.intValue() != 0) {
			column.setPrecision(precision);
		} else {
			if (scale != null && scale.intValue() != 0) {
				final Integer defaultPrecision = column.getPrecision();
				if (defaultPrecision != null) {
					final Integer defaultScale = column.getScale();
					final int integerDigits = defaultPrecision
							- (defaultScale == null ? 0 : defaultScale
									.intValue());
					column.setPrecision(integerDigits + scale.intValue());
					column.setScale(scale);
				}
			}
		}
		if (scale != null && scale.intValue() != 0) {
			column.setScale(scale);
		}
	}

	public Integer createColumn$Precision(FieldOutline fieldOutline) {
		final Integer precision;
		final Long totalDigits = SimpleTypeAnalyzer.getTotalDigits(fieldOutline
				.getPropertyInfo().getSchemaComponent());
		final Long fractionDigits = SimpleTypeAnalyzer
				.getFractionDigits(fieldOutline.getPropertyInfo()
						.getSchemaComponent());
		if (totalDigits != null) {
			if (fractionDigits != null) {
				precision = totalDigits.intValue() + fractionDigits.intValue();
			} else {
				precision = totalDigits.intValue() * 2;
			}
		} else {
			precision = null;
		}
		return precision;
	}

	public Integer createColumn$Scale(FieldOutline fieldOutline) {
		final Integer scale;
		final Long fractionDigits = SimpleTypeAnalyzer
				.getFractionDigits(fieldOutline.getPropertyInfo()
						.getSchemaComponent());
		final Long totalDigits = SimpleTypeAnalyzer.getTotalDigits(fieldOutline
				.getPropertyInfo().getSchemaComponent());
		if (fractionDigits != null) {
			scale = fractionDigits.intValue();
		} else if (totalDigits != null) {
			scale = totalDigits.intValue();
		} else {
			scale = null;
		}
		return scale;
	}

	public Integer createColumn$Length(FieldOutline fieldOutline) {
		final Integer finalLength;
		final Long length = SimpleTypeAnalyzer.getLength(fieldOutline
				.getPropertyInfo().getSchemaComponent());

		if (length != null) {
			finalLength = length.intValue();
		} else {
			final Long maxLength = SimpleTypeAnalyzer.getMaxLength(fieldOutline
					.getPropertyInfo().getSchemaComponent());
			if (maxLength != null) {
				finalLength = maxLength.intValue();
			} else {
				final Long minLength = SimpleTypeAnalyzer
						.getMinLength(fieldOutline.getPropertyInfo()
								.getSchemaComponent());
				if (minLength != null) {
					int intMinLength = minLength.intValue();
					if (intMinLength > 127) {
						finalLength = intMinLength * 2;
					} else {
						finalLength = null;
					}
				} else {
					finalLength = null;
				}
			}
		}
		return finalLength;
	}

	public boolean isTemporal(Mapping context, FieldOutline fieldOutline) {
		final JMethod getter = FieldAccessorUtils.getter(fieldOutline);
		final JType type = getter.type();
		return JTypeUtils.isTemporalType(type);
	}

	public String createTemporalType(Mapping context, FieldOutline fieldOutline) {
		final JMethod getter = FieldAccessorUtils.getter(fieldOutline);
		final JType type = getter.type();
		final JCodeModel codeModel = type.owner();
		// Detect SQL types
		if (codeModel.ref(java.sql.Time.class).equals(type)) {
			return "TIME";
		} else if (codeModel.ref(java.sql.Date.class).equals(type)) {
			return "DATE";
		} else if (codeModel.ref(java.sql.Timestamp.class).equals(type)) {
			return "TIMESTAMP";
		} else if (codeModel.ref(java.util.Calendar.class).equals(type)) {
			return "TIMESTAMP";
		} else {
			final List<QName> typeNames;
			final XSComponent schemaComponent = fieldOutline.getPropertyInfo()
					.getSchemaComponent();
			if (schemaComponent != null) {
				typeNames = TypeUtils.getTypeNames(schemaComponent);
			} else {
				typeNames = Collections.emptyList();
			}
			if (typeNames.contains(XMLSchemaConstrants.DATE_QNAME)
					||
					//
					typeNames.contains(XMLSchemaConstrants.G_YEAR_MONTH_QNAME)
					||
					//
					typeNames.contains(XMLSchemaConstrants.G_YEAR_QNAME) ||
					//
					typeNames.contains(XMLSchemaConstrants.G_MONTH_QNAME) ||
					//
					typeNames.contains(XMLSchemaConstrants.G_MONTH_DAY_QNAME) ||
					//
					typeNames.contains(XMLSchemaConstrants.G_DAY_QNAME)) {
				return "DATE";
			} else if (typeNames.contains(XMLSchemaConstrants.TIME_QNAME)) {
				return "TIME";
			} else if (typeNames.contains(XMLSchemaConstrants.DATE_TIME_QNAME)) {
				return "TIMESTAMP";
			} else {
				return "TIMESTAMP";
			}
		}
	}

	public final boolean isLob(Mapping context, FieldOutline fieldOutline) {
		return false;
	}

	public final Lob createLob(Mapping context, FieldOutline fieldOutline) {
		return new Lob();
	}

	public final boolean isEnumerated(Mapping context, FieldOutline fieldOutline) {
		final CPropertyInfo propertyInfo = fieldOutline.getPropertyInfo();

		final Collection<? extends CTypeInfo> types = context.getGetTypes()
				.process(context, propertyInfo);

		assert types.size() == 1;

		final CTypeInfo type = types.iterator().next();

		return type instanceof CEnumLeafInfo;
	}

	public String createEnumerated(Mapping context, FieldOutline fieldOutline) {
		return EnumType.STRING.name();
	}

	public void createAttributeOverride(Mapping context,
			FieldOutline fieldOutline,
			final List<AttributeOverride> attributeOverrides) {

		final CPropertyInfo propertyInfo = fieldOutline.getPropertyInfo();

		final Collection<? extends CTypeInfo> types = context.getGetTypes()
				.process(context, propertyInfo);

		assert types.size() == 1;

		final CTypeInfo typeInfo = types.iterator().next();

		assert typeInfo instanceof CClassInfo;

		final CClassInfo classInfo = (CClassInfo) typeInfo;

		final Outline outline = fieldOutline.parent().parent();

		final ClassOutline classOutline = outline.getClazz(classInfo);

		final Options options = outline.getModel().options;

		final Map<String, AttributeOverride> attributeOverridesMap = new HashMap<String, AttributeOverride>();
		for (final AttributeOverride attributeOverride : attributeOverrides) {
			attributeOverridesMap.put(attributeOverride.getName(),
					attributeOverride);
		}
		Mapping embeddedMapping = context.createEmbeddedMapping(context,
				fieldOutline);

		final EmbeddableAttributes embeddableAttributes = embeddedMapping
				.getEmbeddableAttributesMapping().process(embeddedMapping,
						classOutline, options);

		for (final Basic basic : embeddableAttributes.getBasic()) {
			final String name = basic.getName();
			final AttributeOverride attributeOverride;
			if (!attributeOverridesMap.containsKey(name)) {
				attributeOverride = new AttributeOverride();
				attributeOverride.setName(name);
				attributeOverride.setColumn(basic.getColumn());
				attributeOverridesMap.put(name, attributeOverride);
				attributeOverrides.add(attributeOverride);
			} else {
				attributeOverride = attributeOverridesMap.get(name);
			}

			// TODO Check that column is not null
			if (attributeOverride.getColumn() == null) {
				attributeOverride.setColumn(new Column());
			}
		}
		for (final Embedded embedded : embeddableAttributes.getEmbedded()) {
			final String parentName = embedded.getName();

			for (AttributeOverride embeddedAttributeOverride : embedded
					.getAttributeOverride()) {
				final String childName = embeddedAttributeOverride.getName();
				final String name = parentName + "." + childName;

				final AttributeOverride attributeOverride;
				if (!attributeOverridesMap.containsKey(name)) {
					attributeOverride = new AttributeOverride();
					attributeOverride.setName(name);
					attributeOverride.setColumn(embeddedAttributeOverride
							.getColumn());
					attributeOverridesMap.put(name, attributeOverride);
					attributeOverrides.add(attributeOverride);
				} else {
					attributeOverride = attributeOverridesMap.get(name);
				}

				// TODO Check that column is not null
				if (attributeOverride.getColumn() == null) {
					attributeOverride.setColumn(new Column());
				}
			}
		}
	}

}


text:
package com.creatubbles.ctbmod.common.painting;

import java.util.Locale;
import java.util.Set;

import net.minecraft.util.IStringSerializable;

import com.google.common.collect.Sets;

import static com.creatubbles.ctbmod.common.painting.Connections.*;

public enum ConnectionType implements IStringSerializable {

    NONE,
    UP_ONLY(UP),
    DOWN_ONLY(DOWN),
    LEFT_ONLY(LEFT),
    RIGHT_ONLY(RIGHT),
    UP_DOWN(UP, DOWN),
    LEFT_RIGHT(LEFT, RIGHT),
    TOP_LEFT(UP, LEFT),
    TOP_RIGHT(UP, RIGHT),
    BOTTOM_RIGHT(DOWN, RIGHT),
    BOTTOM_LEFT(DOWN, LEFT),
    TOP_SIDE(DOWN, LEFT, RIGHT),
    BOTTOM_SIDE(UP, LEFT, RIGHT),
    LEFT_SIDE(RIGHT, UP, DOWN),
    RIGHT_SIDE(LEFT, UP, DOWN),
    ALL(UP, DOWN, LEFT, RIGHT);

    private Set<Connections> connections;

    private ConnectionType(Connections... connections) {
        this.connections = Sets.newHashSet(connections);
    }

    public static ConnectionType forConnections(Set<Connections> iter) {
        for (ConnectionType type : values()) {
            if (iter.equals(type.connections)) {
                return type;
            }
        }
        return null;
    }

    @Override
    public String getName() {
        return name().toLowerCase(Locale.US);
    }
}


text:
<?php

use yii\db\Migration;

class m161118_130947_manga_has_author extends Migration
{
    public function up()
    {
        $this->dropForeignKey('manga_author','manga');
        $this->dropColumn('manga','author_id');
        $this->createTable('manga_has_author',array(
            'manga_has_author_id' => $this->primaryKey()->unsigned(),
            'manga_id'  => $this->integer()->notNull()->unsigned(),
            'author_id'  => $this->integer()->notNull()->unsigned(),
        ));

        $this->addForeignKey(
            'manga_has_author_manga',
            'manga_has_author',
            'manga_id',
            'manga',
            'manga_id',
            'CASCADE',
            'CASCADE'
        );

        $this->addForeignKey(
            'manga_has_author_author',
            'manga_has_author',
            'author_id',
            'author',
            'author_id',
            'CASCADE',
            'CASCADE'
        );
    }

    public function down()
    {
        $this->dropForeignKey('manga_has_author_manga','manga_has_author');
        $this->dropForeignKey('manga_has_author_author','manga_has_author');
        $this->dropTable('manga_has_author');
        $this->addColumn('manga','author_id',$this->integer()->null()->unsigned()->after('manga_id'));
        $this->addForeignKey('manga_author','manga','author_id','author','author_id','NO ACTION','NO ACTION');
    }

}


text: linzhiyinglin