text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestosql.spi.predicate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.google.common.collect.ImmutableList;
import io.airlift.json.ObjectMapperProvider;
import io.airlift.slice.Slices;
import io.prestosql.spi.block.Block;
import io.prestosql.spi.block.TestingBlockEncodingSerde;
import io.prestosql.spi.block.TestingBlockJsonSerde;
import io.prestosql.spi.type.TestingTypeDeserializer;
import io.prestosql.spi.type.TestingTypeManager;
import io.prestosql.spi.type.Type;
import org.testng.annotations.Test;

import static io.prestosql.spi.type.BigintType.BIGINT;
import static io.prestosql.spi.type.BooleanType.BOOLEAN;
import static io.prestosql.spi.type.DoubleType.DOUBLE;
import static io.prestosql.spi.type.HyperLogLogType.HYPER_LOG_LOG;
import static io.prestosql.spi.type.RealType.REAL;
import static io.prestosql.spi.type.TestingIdType.ID;
import static io.prestosql.spi.type.VarcharType.VARCHAR;
import static java.lang.Double.longBitsToDouble;
import static java.lang.Float.floatToRawIntBits;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;

public class TestDomain
{
    @Test
    public void testOrderableNone()
    {
        Domain domain = Domain.none(BIGINT);
        assertTrue(domain.isNone());
        assertFalse(domain.isAll());
        assertFalse(domain.isSingleValue());
        assertFalse(domain.isNullableSingleValue());
        assertFalse(domain.isNullAllowed());
        assertEquals(domain.getValues(), ValueSet.none(BIGINT));
        assertEquals(domain.getType(), BIGINT);
        assertFalse(domain.includesNullableValue(Long.MIN_VALUE));
        assertFalse(domain.includesNullableValue(0L));
        assertFalse(domain.includesNullableValue(Long.MAX_VALUE));
        assertFalse(domain.includesNullableValue(null));
        assertEquals(domain.complement(), Domain.all(BIGINT));
    }

    @Test
    public void testEquatableNone()
    {
        Domain domain = Domain.none(ID);
        assertTrue(domain.isNone());
        assertFalse(domain.isAll());
        assertFalse(domain.isSingleValue());
        assertFalse(domain.isNullableSingleValue());
        assertFalse(domain.isNullAllowed());
        assertEquals(domain.getValues(), ValueSet.none(ID));
        assertEquals(domain.getType(), ID);
        assertFalse(domain.includesNullableValue(0L));
        assertFalse(domain.includesNullableValue(null));
        assertEquals(domain.complement(), Domain.all(ID));
    }

    @Test
    public void testUncomparableNone()
    {
        Domain domain = Domain.none(HYPER_LOG_LOG);
        assertTrue(domain.isNone());
        assertFalse(domain.isAll());
        assertFalse(domain.isSingleValue());
        assertFalse(domain.isNullableSingleValue());
        assertFalse(domain.isNullAllowed());
        assertEquals(domain.getValues(), ValueSet.none(HYPER_LOG_LOG));
        assertEquals(domain.getType(), HYPER_LOG_LOG);
        assertFalse(domain.includesNullableValue(Slices.EMPTY_SLICE));
        assertFalse(domain.includesNullableValue(null));
        assertEquals(domain.complement(), Domain.all(HYPER_LOG_LOG));
    }

    @Test
    public void testOrderableAll()
    {
        Domain domain = Domain.all(BIGINT);
        assertFalse(domain.isNone());
        assertTrue(domain.isAll());
        assertFalse(domain.isSingleValue());
        assertFalse(domain.isNullableSingleValue());
        assertFalse(domain.isOnlyNull());
        assertTrue(domain.isNullAllowed());
        assertEquals(domain.getValues(), ValueSet.all(BIGINT));
        assertEquals(domain.getType(), BIGINT);
        assertTrue(domain.includesNullableValue(Long.MIN_VALUE));
        assertTrue(domain.includesNullableValue(0L));
        assertTrue(domain.includesNullableValue(Long.MAX_VALUE));
        assertTrue(domain.includesNullableValue(null));
        assertEquals(domain.complement(), Domain.none(BIGINT));
    }

    @Test
    public void testFloatingPointOrderableAll()
    {
        Domain domain = Domain.all(REAL);
        assertFalse(domain.isNone());
        assertTrue(domain.isAll());
        assertFalse(domain.isSingleValue());
        assertFalse(domain.isNullableSingleValue());
        assertFalse(domain.isOnlyNull());
        assertTrue(domain.isNullAllowed());
        assertEquals(domain.getValues(), ValueSet.all(REAL));
        assertEquals(domain.getType(), REAL);
        assertTrue(domain.includesNullableValue((long) floatToRawIntBits(-Float.MAX_VALUE)));
        assertTrue(domain.includesNullableValue((long) floatToRawIntBits(0.0f)));
        assertTrue(domain.includesNullableValue((long) floatToRawIntBits(Float.MAX_VALUE)));
        assertTrue(domain.includesNullableValue((long) floatToRawIntBits(Float.MIN_VALUE)));
        assertTrue(domain.includesNullableValue(null));
        assertTrue(domain.includesNullableValue((long) floatToRawIntBits(Float.NaN)));
        assertTrue(domain.includesNullableValue((long) 0x7fc01234)); // different NaN representation
        assertEquals(domain.complement(), Domain.none(REAL));

        domain = Domain.all(DOUBLE);
        assertFalse(domain.isNone());
        assertTrue(domain.isAll());
        assertFalse(domain.isSingleValue());
        assertFalse(domain.isNullableSingleValue());
        assertFalse(domain.isOnlyNull());
        assertTrue(domain.isNullAllowed());
        assertEquals(domain.getValues(), ValueSet.all(DOUBLE));
        assertEquals(domain.getType(), DOUBLE);
        assertTrue(domain.includesNullableValue(-Double.MAX_VALUE));
        assertTrue(domain.includesNullableValue(0.0));
        assertTrue(domain.includesNullableValue(Double.MAX_VALUE));
        assertTrue(domain.includesNullableValue(Double.MIN_VALUE));
        assertTrue(domain.includesNullableValue(null));
        assertTrue(domain.includesNullableValue(Double.NaN));
        assertTrue(domain.includesNullableValue(longBitsToDouble(0x7ff8123412341234L))); // different NaN representation
        assertEquals(domain.complement(), Domain.none(DOUBLE));
    }

    @Test
    public void testEquatableAll()
    {
        Domain domain = Domain.all(ID);
        assertFalse(domain.isNone());
        assertTrue(domain.isAll());
        assertFalse(domain.isSingleValue());
        assertFalse(domain.isNullableSingleValue());
        assertFalse(domain.isOnlyNull());
        assertTrue(domain.isNullAllowed());
        assertEquals(domain.getValues(), ValueSet.all(ID));
        assertEquals(domain.getType(), ID);
        assertTrue(domain.includesNullableValue(0L));
        assertTrue(domain.includesNullableValue(null));
        assertEquals(domain.complement(), Domain.none(ID));
    }

    @Test
    public void testUncomparableAll()
    {
        Domain domain = Domain.all(HYPER_LOG_LOG);
        assertFalse(domain.isNone());
        assertTrue(domain.isAll());
        assertFalse(domain.isSingleValue());
        assertFalse(domain.isNullableSingleValue());
        assertFalse(domain.isOnlyNull());
        assertTrue(domain.isNullAllowed());
        assertEquals(domain.getValues(), ValueSet.all(HYPER_LOG_LOG));
        assertEquals(domain.getType(), HYPER_LOG_LOG);
        assertTrue(domain.includesNullableValue(Slices.EMPTY_SLICE));
        assertTrue(domain.includesNullableValue(null));
        assertEquals(domain.complement(), Domain.none(HYPER_LOG_LOG));
    }

    @Test
    public void testOrderableNullOnly()
    {
        Domain domain = Domain.onlyNull(BIGINT);
        assertFalse(domain.isNone());
        assertFalse(domain.isAll());
        assertFalse(domain.isSingleValue());
        assertTrue(domain.isNullAllowed());
        assertTrue(domain.isNullableSingleValue());
        assertTrue(domain.isOnlyNull());
        assertEquals(domain.getValues(), ValueSet.none(BIGINT));
        assertEquals(domain.getType(), BIGINT);
        assertFalse(domain.includesNullableValue(Long.MIN_VALUE));
        assertFalse(domain.includesNullableValue(0L));
        assertFalse(domain.includesNullableValue(Long.MAX_VALUE));
        assertTrue(domain.includesNullableValue(null));
        assertEquals(domain.complement(), Domain.notNull(BIGINT));
        assertEquals(domain.getNullableSingleValue(), null);
    }

    @Test
    public void testEquatableNullOnly()
    {
        Domain domain = Domain.onlyNull(ID);
        assertFalse(domain.isNone());
        assertFalse(domain.isAll());
        assertFalse(domain.isSingleValue());
        assertTrue(domain.isNullableSingleValue());
        assertTrue(domain.isOnlyNull());
        assertTrue(domain.isNullAllowed());
        assertEquals(domain.getValues(), ValueSet.none(ID));
        assertEquals(domain.getType(), ID);
        assertFalse(domain.includesNullableValue(0L));
        assertTrue(domain.includesNullableValue(null));
        assertEquals(domain.complement(), Domain.notNull(ID));
        assertEquals(domain.getNullableSingleValue(), null);
    }

    @Test
    public void testUncomparableNullOnly()
    {
        Domain domain = Domain.onlyNull(HYPER_LOG_LOG);
        assertFalse(domain.isNone());
        assertFalse(domain.isAll());
        assertFalse(domain.isSingleValue());
        assertTrue(domain.isNullableSingleValue());
        assertTrue(domain.isOnlyNull());
        assertTrue(domain.isNullAllowed());
        assertEquals(domain.getValues(), ValueSet.none(HYPER_LOG_LOG));
        assertEquals(domain.getType(), HYPER_LOG_LOG);
        assertFalse(domain.includesNullableValue(Slices.EMPTY_SLICE));
        assertTrue(domain.includesNullableValue(null));
        assertEquals(domain.complement(), Domain.notNull(HYPER_LOG_LOG));
        assertEquals(domain.getNullableSingleValue(), null);
    }

    @Test
    public void testOrderableNotNull()
    {
        Domain domain = Domain.notNull(BIGINT);
        assertFalse(domain.isNone());
        assertFalse(domain.isAll());
        assertFalse(domain.isSingleValue());
        assertFalse(domain.isNullableSingleValue());
        assertFalse(domain.isOnlyNull());
        assertFalse(domain.isNullAllowed());
        assertEquals(domain.getValues(), ValueSet.all(BIGINT));
        assertEquals(domain.getType(), BIGINT);
        assertTrue(domain.includesNullableValue(Long.MIN_VALUE));
        assertTrue(domain.includesNullableValue(0L));
        assertTrue(domain.includesNullableValue(Long.MAX_VALUE));
        assertFalse(domain.includesNullableValue(null));
        assertEquals(domain.complement(), Domain.onlyNull(BIGINT));
    }

    @Test
    public void testEquatableNotNull()
    {
        Domain domain = Domain.notNull(ID);
        assertFalse(domain.isNone());
        assertFalse(domain.isAll());
        assertFalse(domain.isSingleValue());
        assertFalse(domain.isNullableSingleValue());
        assertFalse(domain.isOnlyNull());
        assertFalse(domain.isNullAllowed());
        assertEquals(domain.getValues(), ValueSet.all(ID));
        assertEquals(domain.getType(), ID);
        assertTrue(domain.includesNullableValue(0L));
        assertFalse(domain.includesNullableValue(null));
        assertEquals(domain.complement(), Domain.onlyNull(ID));
    }

    @Test
    public void testUncomparableNotNull()
    {
        Domain domain = Domain.notNull(HYPER_LOG_LOG);
        assertFalse(domain.isNone());
        assertFalse(domain.isAll());
        assertFalse(domain.isSingleValue());
        assertFalse(domain.isNullableSingleValue());
        assertFalse(domain.isOnlyNull());
        assertFalse(domain.isNullAllowed());
        assertEquals(domain.getValues(), ValueSet.all(HYPER_LOG_LOG));
        assertEquals(domain.getType(), HYPER_LOG_LOG);
        assertTrue(domain.includesNullableValue(Slices.EMPTY_SLICE));
        assertFalse(domain.includesNullableValue(null));
        assertEquals(domain.complement(), Domain.onlyNull(HYPER_LOG_LOG));
    }

    @Test
    public void testOrderableSingleValue()
    {
        Domain domain = Domain.singleValue(BIGINT, 0L);
        assertFalse(domain.isNone());
        assertFalse(domain.isAll());
        assertTrue(domain.isSingleValue());
        assertTrue(domain.isNullableSingleValue());
        assertFalse(domain.isOnlyNull());
        assertFalse(domain.isNullAllowed());
        assertEquals(domain.getValues(), ValueSet.ofRanges(Range.equal(BIGINT, 0L)));
        assertEquals(domain.getType(), BIGINT);
        assertFalse(domain.includesNullableValue(Long.MIN_VALUE));
        assertTrue(domain.includesNullableValue(0L));
        assertFalse(domain.includesNullableValue(Long.MAX_VALUE));
        assertEquals(domain.complement(), Domain.create(ValueSet.ofRanges(Range.lessThan(BIGINT, 0L), Range.greaterThan(BIGINT, 0L)), true));
        assertEquals(domain.getSingleValue(), 0L);
        assertEquals(domain.getNullableSingleValue(), 0L);

        try {
            Domain.create(ValueSet.ofRanges(Range.range(BIGINT, 1L, true, 2L, true)), false).getSingleValue();
            fail();
        }
        catch (IllegalStateException e) {
        }
    }

    @Test
    public void testEquatableSingleValue()
    {
        Domain domain = Domain.singleValue(ID, 0L);
        assertFalse(domain.isNone());
        assertFalse(domain.isAll());
        assertTrue(domain.isSingleValue());
        assertTrue(domain.isNullableSingleValue());
        assertFalse(domain.isOnlyNull());
        assertFalse(domain.isNullAllowed());
        assertEquals(domain.getValues(), ValueSet.of(ID, 0L));
        assertEquals(domain.getType(), ID);
        assertTrue(domain.includesNullableValue(0L));
        assertFalse(domain.includesNullableValue(null));
        assertEquals(domain.complement(), Domain.create(ValueSet.of(ID, 0L).complement(), true));
        assertEquals(domain.getSingleValue(), 0L);
        assertEquals(domain.getNullableSingleValue(), 0L);

        try {
            Domain.create(ValueSet.of(ID, 0L, 1L), false).getSingleValue();
            fail();
        }
        catch (IllegalStateException e) {
        }
    }

    @Test(expectedExceptions = IllegalArgumentException.class)
    public void testUncomparableSingleValue()
    {
        Domain.singleValue(HYPER_LOG_LOG, Slices.EMPTY_SLICE);
    }

    @Test
    public void testOverlaps()
    {
        assertTrue(Domain.all(BIGINT).overlaps(Domain.all(BIGINT)));
        assertFalse(Domain.all(BIGINT).overlaps(Domain.none(BIGINT)));
        assertTrue(Domain.all(BIGINT).overlaps(Domain.notNull(BIGINT)));
        assertTrue(Domain.all(BIGINT).overlaps(Domain.onlyNull(BIGINT)));
        assertTrue(Domain.all(BIGINT).overlaps(Domain.singleValue(BIGINT, 0L)));

        assertFalse(Domain.none(BIGINT).overlaps(Domain.all(BIGINT)));
        assertFalse(Domain.none(BIGINT).overlaps(Domain.none(BIGINT)));
        assertFalse(Domain.none(BIGINT).overlaps(Domain.notNull(BIGINT)));
        assertFalse(Domain.none(BIGINT).overlaps(Domain.onlyNull(BIGINT)));
        assertFalse(Domain.none(BIGINT).overlaps(Domain.singleValue(BIGINT, 0L)));

        assertTrue(Domain.notNull(BIGINT).overlaps(Domain.all(BIGINT)));
        assertFalse(Domain.notNull(BIGINT).overlaps(Domain.none(BIGINT)));
        assertTrue(Domain.notNull(BIGINT).overlaps(Domain.notNull(BIGINT)));
        assertFalse(Domain.notNull(BIGINT).overlaps(Domain.onlyNull(BIGINT)));
        assertTrue(Domain.notNull(BIGINT).overlaps(Domain.singleValue(BIGINT, 0L)));

        assertTrue(Domain.onlyNull(BIGINT).overlaps(Domain.all(BIGINT)));
        assertFalse(Domain.onlyNull(BIGINT).overlaps(Domain.none(BIGINT)));
        assertFalse(Domain.onlyNull(BIGINT).overlaps(Domain.notNull(BIGINT)));
        assertTrue(Domain.onlyNull(BIGINT).overlaps(Domain.onlyNull(BIGINT)));
        assertFalse(Domain.onlyNull(BIGINT).overlaps(Domain.singleValue(BIGINT, 0L)));

        assertTrue(Domain.singleValue(BIGINT, 0L).overlaps(Domain.all(BIGINT)));
        assertFalse(Domain.singleValue(BIGINT, 0L).overlaps(Domain.none(BIGINT)));
        assertTrue(Domain.singleValue(BIGINT, 0L).overlaps(Domain.notNull(BIGINT)));
        assertFalse(Domain.singleValue(BIGINT, 0L).overlaps(Domain.onlyNull(BIGINT)));
        assertTrue(Domain.singleValue(BIGINT, 0L).overlaps(Domain.singleValue(BIGINT, 0L)));
    }

    @Test
    public void testContains()
    {
        assertTrue(Domain.all(BIGINT).contains(Domain.all(BIGINT)));
        assertTrue(Domain.all(BIGINT).contains(Domain.none(BIGINT)));
        assertTrue(Domain.all(BIGINT).contains(Domain.notNull(BIGINT)));
        assertTrue(Domain.all(BIGINT).contains(Domain.onlyNull(BIGINT)));
        assertTrue(Domain.all(BIGINT).contains(Domain.singleValue(BIGINT, 0L)));

        assertFalse(Domain.none(BIGINT).contains(Domain.all(BIGINT)));
        assertTrue(Domain.none(BIGINT).contains(Domain.none(BIGINT)));
        assertFalse(Domain.none(BIGINT).contains(Domain.notNull(BIGINT)));
        assertFalse(Domain.none(BIGINT).contains(Domain.onlyNull(BIGINT)));
        assertFalse(Domain.none(BIGINT).contains(Domain.singleValue(BIGINT, 0L)));

        assertFalse(Domain.notNull(BIGINT).contains(Domain.all(BIGINT)));
        assertTrue(Domain.notNull(BIGINT).contains(Domain.none(BIGINT)));
        assertTrue(Domain.notNull(BIGINT).contains(Domain.notNull(BIGINT)));
        assertFalse(Domain.notNull(BIGINT).contains(Domain.onlyNull(BIGINT)));
        assertTrue(Domain.notNull(BIGINT).contains(Domain.singleValue(BIGINT, 0L)));

        assertFalse(Domain.onlyNull(BIGINT).contains(Domain.all(BIGINT)));
        assertTrue(Domain.onlyNull(BIGINT).contains(Domain.none(BIGINT)));
        assertFalse(Domain.onlyNull(BIGINT).contains(Domain.notNull(BIGINT)));
        assertTrue(Domain.onlyNull(BIGINT).contains(Domain.onlyNull(BIGINT)));
        assertFalse(Domain.onlyNull(BIGINT).contains(Domain.singleValue(BIGINT, 0L)));

        assertFalse(Domain.singleValue(BIGINT, 0L).contains(Domain.all(BIGINT)));
        assertTrue(Domain.singleValue(BIGINT, 0L).contains(Domain.none(BIGINT)));
        assertFalse(Domain.singleValue(BIGINT, 0L).contains(Domain.notNull(BIGINT)));
        assertFalse(Domain.singleValue(BIGINT, 0L).contains(Domain.onlyNull(BIGINT)));
        assertTrue(Domain.singleValue(BIGINT, 0L).contains(Domain.singleValue(BIGINT, 0L)));
    }

    @Test
    public void testIntersect()
    {
        assertEquals(
                Domain.all(BIGINT).intersect(Domain.all(BIGINT)),
                Domain.all(BIGINT));

        assertEquals(
                Domain.none(BIGINT).intersect(Domain.none(BIGINT)),
                Domain.none(BIGINT));

        assertEquals(
                Domain.all(BIGINT).intersect(Domain.none(BIGINT)),
                Domain.none(BIGINT));

        assertEquals(
                Domain.notNull(BIGINT).intersect(Domain.onlyNull(BIGINT)),
                Domain.none(BIGINT));

        assertEquals(
                Domain.singleValue(BIGINT, 0L).intersect(Domain.all(BIGINT)),
                Domain.singleValue(BIGINT, 0L));

        assertEquals(
                Domain.singleValue(BIGINT, 0L).intersect(Domain.onlyNull(BIGINT)),
                Domain.none(BIGINT));

        assertEquals(
                Domain.create(ValueSet.ofRanges(Range.equal(BIGINT, 1L)), true).intersect(Domain.create(ValueSet.ofRanges(Range.equal(BIGINT, 2L)), true)),
                Domain.onlyNull(BIGINT));

        assertEquals(
                Domain.create(ValueSet.ofRanges(Range.equal(BIGINT, 1L)), true).intersect(Domain.create(ValueSet.ofRanges(Range.equal(BIGINT, 1L), Range.equal(BIGINT, 2L)), false)),
                Domain.singleValue(BIGINT, 1L));
    }

    @Test
    public void testUnion()
    {
        assertUnion(Domain.all(BIGINT), Domain.all(BIGINT), Domain.all(BIGINT));
        assertUnion(Domain.none(BIGINT), Domain.none(BIGINT), Domain.none(BIGINT));
        assertUnion(Domain.all(BIGINT), Domain.none(BIGINT), Domain.all(BIGINT));
        assertUnion(Domain.notNull(BIGINT), Domain.onlyNull(BIGINT), Domain.all(BIGINT));
        assertUnion(Domain.singleValue(BIGINT, 0L), Domain.all(BIGINT), Domain.all(BIGINT));
        assertUnion(Domain.singleValue(BIGINT, 0L), Domain.notNull(BIGINT), Domain.notNull(BIGINT));
        assertUnion(Domain.singleValue(BIGINT, 0L), Domain.onlyNull(BIGINT), Domain.create(ValueSet.ofRanges(Range.equal(BIGINT, 0L)), true));

        assertUnion(Domain.create(ValueSet.ofRanges(Range.equal(BIGINT, 1L)), true),
                Domain.create(ValueSet.ofRanges(Range.equal(BIGINT, 2L)), true),
                Domain.create(ValueSet.ofRanges(Range.equal(BIGINT, 1L), Range.equal(BIGINT, 2L)), true));

        assertUnion(Domain.create(ValueSet.ofRanges(Range.equal(BIGINT, 1L)), true),
                Domain.create(ValueSet.ofRanges(Range.equal(BIGINT, 1L), Range.equal(BIGINT, 2L)), false),
                Domain.create(ValueSet.ofRanges(Range.equal(BIGINT, 1L), Range.equal(BIGINT, 2L)), true));
    }

    @Test
    public void testSubtract()
    {
        assertEquals(
                Domain.all(BIGINT).subtract(Domain.all(BIGINT)),
                Domain.none(BIGINT));
        assertEquals(
                Domain.all(BIGINT).subtract(Domain.none(BIGINT)),
                Domain.all(BIGINT));
        assertEquals(
                Domain.all(BIGINT).subtract(Domain.notNull(BIGINT)),
                Domain.onlyNull(BIGINT));
        assertEquals(
                Domain.all(BIGINT).subtract(Domain.onlyNull(BIGINT)),
                Domain.notNull(BIGINT));
        assertEquals(
                Domain.all(BIGINT).subtract(Domain.singleValue(BIGINT, 0L)),
                Domain.create(ValueSet.ofRanges(Range.lessThan(BIGINT, 0L), Range.greaterThan(BIGINT, 0L)), true));

        assertEquals(
                Domain.none(BIGINT).subtract(Domain.all(BIGINT)),
                Domain.none(BIGINT));
        assertEquals(
                Domain.none(BIGINT).subtract(Domain.none(BIGINT)),
                Domain.none(BIGINT));
        assertEquals(
                Domain.none(BIGINT).subtract(Domain.notNull(BIGINT)),
                Domain.none(BIGINT));
        assertEquals(
                Domain.none(BIGINT).subtract(Domain.onlyNull(BIGINT)),
                Domain.none(BIGINT));
        assertEquals(
                Domain.none(BIGINT).subtract(Domain.singleValue(BIGINT, 0L)),
                Domain.none(BIGINT));

        assertEquals(
                Domain.notNull(BIGINT).subtract(Domain.all(BIGINT)),
                Domain.none(BIGINT));
        assertEquals(
                Domain.notNull(BIGINT).subtract(Domain.none(BIGINT)),
                Domain.notNull(BIGINT));
        assertEquals(
                Domain.notNull(BIGINT).subtract(Domain.notNull(BIGINT)),
                Domain.none(BIGINT));
        assertEquals(
                Domain.notNull(BIGINT).subtract(Domain.onlyNull(BIGINT)),
                Domain.notNull(BIGINT));
        assertEquals(
                Domain.notNull(BIGINT).subtract(Domain.singleValue(BIGINT, 0L)),
                Domain.create(ValueSet.ofRanges(Range.lessThan(BIGINT, 0L), Range.greaterThan(BIGINT, 0L)), false));

        assertEquals(
                Domain.onlyNull(BIGINT).subtract(Domain.all(BIGINT)),
                Domain.none(BIGINT));
        assertEquals(
                Domain.onlyNull(BIGINT).subtract(Domain.none(BIGINT)),
                Domain.onlyNull(BIGINT));
        assertEquals(
                Domain.onlyNull(BIGINT).subtract(Domain.notNull(BIGINT)),
                Domain.onlyNull(BIGINT));
        assertEquals(
                Domain.onlyNull(BIGINT).subtract(Domain.onlyNull(BIGINT)),
                Domain.none(BIGINT));
        assertEquals(
                Domain.onlyNull(BIGINT).subtract(Domain.singleValue(BIGINT, 0L)),
                Domain.onlyNull(BIGINT));

        assertEquals(
                Domain.singleValue(BIGINT, 0L).subtract(Domain.all(BIGINT)),
                Domain.none(BIGINT));
        assertEquals(
                Domain.singleValue(BIGINT, 0L).subtract(Domain.none(BIGINT)),
                Domain.singleValue(BIGINT, 0L));
        assertEquals(
                Domain.singleValue(BIGINT, 0L).subtract(Domain.notNull(BIGINT)),
                Domain.none(BIGINT));
        assertEquals(
                Domain.singleValue(BIGINT, 0L).subtract(Domain.onlyNull(BIGINT)),
                Domain.singleValue(BIGINT, 0L));
        assertEquals(
                Domain.singleValue(BIGINT, 0L).subtract(Domain.singleValue(BIGINT, 0L)),
                Domain.none(BIGINT));

        assertEquals(
                Domain.create(ValueSet.ofRanges(Range.equal(BIGINT, 1L)), true).subtract(Domain.create(ValueSet.ofRanges(Range.equal(BIGINT, 2L)), true)),
                Domain.singleValue(BIGINT, 1L));

        assertEquals(
                Domain.create(ValueSet.ofRanges(Range.equal(BIGINT, 1L)), true).subtract(Domain.create(ValueSet.ofRanges(Range.equal(BIGINT, 1L), Range.equal(BIGINT, 2L)), false)),
                Domain.onlyNull(BIGINT));
    }

    @Test
    public void testJsonSerialization()
            throws Exception
    {
        TestingTypeManager typeManager = new TestingTypeManager();
        TestingBlockEncodingSerde blockEncodingSerde = new TestingBlockEncodingSerde();

        ObjectMapper mapper = new ObjectMapperProvider().get()
                .registerModule(new SimpleModule()
                        .addDeserializer(Type.class, new TestingTypeDeserializer(typeManager))
                        .addSerializer(Block.class, new TestingBlockJsonSerde.Serializer(blockEncodingSerde))
                        .addDeserializer(Block.class, new TestingBlockJsonSerde.Deserializer(blockEncodingSerde)));

        Domain domain = Domain.all(BIGINT);
        assertEquals(domain, mapper.readValue(mapper.writeValueAsString(domain), Domain.class));

        domain = Domain.none(DOUBLE);
        assertEquals(domain, mapper.readValue(mapper.writeValueAsString(domain), Domain.class));

        domain = Domain.notNull(BOOLEAN);
        assertEquals(domain, mapper.readValue(mapper.writeValueAsString(domain), Domain.class));

        domain = Domain.notNull(HYPER_LOG_LOG);
        assertEquals(domain, mapper.readValue(mapper.writeValueAsString(domain), Domain.class));

        domain = Domain.onlyNull(VARCHAR);
        assertEquals(domain, mapper.readValue(mapper.writeValueAsString(domain), Domain.class));

        domain = Domain.onlyNull(HYPER_LOG_LOG);
        assertEquals(domain, mapper.readValue(mapper.writeValueAsString(domain), Domain.class));

        domain = Domain.singleValue(BIGINT, Long.MIN_VALUE);
        assertEquals(domain, mapper.readValue(mapper.writeValueAsString(domain), Domain.class));

        domain = Domain.singleValue(ID, Long.MIN_VALUE);
        assertEquals(domain, mapper.readValue(mapper.writeValueAsString(domain), Domain.class));

        domain = Domain.create(ValueSet.ofRanges(Range.lessThan(BIGINT, 0L), Range.equal(BIGINT, 1L), Range.range(BIGINT, 2L, true, 3L, true)), true);
        assertEquals(domain, mapper.readValue(mapper.writeValueAsString(domain), Domain.class));
    }

    private void assertUnion(Domain first, Domain second, Domain expected)
    {
        assertEquals(first.union(second), expected);
        assertEquals(Domain.union(ImmutableList.of(first, second)), expected);
    }
}


text:
__author__ = 'lvkun.lk'

import sys,os,time
import ConfigParser

class Config:
    def __init__(self, path):
        self.path = path
        self.cf = ConfigParser.ConfigParser()
        self.cf.read(self.path)

    def get(self, field, key):
        result = ""
        try:
            result = self.cf.get(field, key)
        except:
            result = ""
        return result

    def set(self, filed, key, value):
        try:
            self.cf.set(field, key, value)
            cf.write(open(self.path,'w'))
        except:
            return False
        return True

def read_config(config_file_path, field, key):
    cf = ConfigParser.ConfigParser()
    try:
        cf.read(config_file_path)
        result = cf.get(field, key)
    except:
        sys.exit(1)
    return result

def write_config(config_file_path, field, key, value):
    cf = ConfigParser.ConfigParser()
    try:
        cf.read(config_file_path)
        cf.set(field, key, value)
        cf.write(open(config_file_path,'w'))
    except:
        sys.exit(1)
    return True

redpajama_set_name: RedPajamaGithub


text:
import csv
import datautil

f = open('publishers.csv','wb')
fw = csv.writer(f, dialect='excel')
ft = open('timingsPublishers.csv','w')
h = ["PublisherGUID", "PublisherVersion", "PublisherDateModified", "PublisherName",
     "PublisherType", "ingest", "SrcDataFile", "IdbDataFile", "Publisher", "Code", "RecordsetGUID",
     "Specimens Provided", "Media Provided", "Identifications Provided",
     "Relationships Provided", "Specimens Ingested", "Media Ingested",
     "Specimens Indexed", "Media Indexed", "Remaining RecordSets"]
fw.writerow(h)
f.flush()
tw = [] # Wget timings
tl = [] # Load data timings

# Get all publishers
j = datautil.wgetLoadJsonTime('http://api.idigbio.org/v1/publishers', tw, tl)

for item in j['idigbio:items']:
    print item['idigbio:links']['publisher']
    # Get one particular publisher
    j2 = datautil.wgetLoadJsonTime(item['idigbio:links']['publisher'], tw, tl)
    if j2['idigbio:data']['name']:
        pubShortName = datautil.getPublisherShortName(j2['idigbio:data']['name'])
    else:
        pubShortName = datautil.getPublisherShortName(j2['idigbio:data']['base_url'])
    # Get current RSS feed for this publisher
    rss = datautil.wgetLoadRssTime(j2['idigbio:data']['rss_url'], tw, tl)
    r = [item['idigbio:uuid'], item['idigbio:version'], item['idigbio:dateModified'],
        j2['idigbio:data']['name'], j2['idigbio:data']['publisher_type']]
    # Get all recordsets of this publisher, if it is a link to the list of recordsets.
    # Otherwise make a copy of the recordset list.
    recordsets = []
    if j2['idigbio:links'].get('recordset', None):
        if len(j2['idigbio:links']['recordset']) == 1 and \
            j2['idigbio:links']['recordset'][0].endswith("recordsets"):
            j3 = datautil.wgetLoadJsonTime(j2['idigbio:links']['recordset'][0], tw, tl)
            for item3 in j3['idigbio:items']:
                recordsets.append(item3['idigbio:links']['recordset'])
        else:
            recordsets = j2['idigbio:links']['recordset']
    # For each recordset of the publisher
    for key2, item2 in j2['idigbio:data']['recordsets'].iteritems():
        # Find the previously published dataset in the current RSS
        currDatafile = datautil.findDatafileRssByGuid(rss, key2)
        datafile = item2['link'].encode('ascii','ignore')
        print currDatafile == datafile, currDatafile, key2
        if currDatafile is None:
            code = datautil.getCode(datafile)
            numRec = ['0', '0', '0', '0']
            status = "UNPUBLISHED"
        else:
            code = datautil.getCode(currDatafile)
            numRec = datautil.wgetLoadFileTime(currDatafile, item['idigbio:uuid'], tw, tl)
            status = item2['ingest']
        ingested = ['0', '0']
        indexed = ['0', '0']
        if j2['idigbio:links'].get('recordset', None):
            if len(recordsets) > 0:
                ingested, recset = datautil.findPubRecords(recordsets, datafile, tw, tl)
                if datafile.endswith(".csv") or datafile.endswith(".tsv"):
                    if int(ingested[0]) == 0 and int(ingested[1]) > 0:
                        numRec[1] = numRec[0]
                        numRec[0] = 0
                if recset:
                    indj = datautil.wgetLoadJsonTime('http://search.idigbio.org/idigbio/records/_search?q=recordset:' + recset, tw, tl)
                    indj2 = datautil.wgetLoadJsonTime('http://search.idigbio.org/idigbio/mediarecords/_search?q=recordset:' + recset, tw, tl)
                    indexed = [indj["hits"]["total"], indj2["hits"]["total"]]
        print r + [status, currDatafile, datafile, pubShortName, code, recset] + numRec + ingested + indexed + [len(recordsets)]
        fw.writerow(r + [status, currDatafile, datafile, pubShortName, code, recset] + numRec + ingested + indexed + [len(recordsets)])
        f.flush()
    # Look all recordsets not in publishers
    for recordset in recordsets:
        j3 = datautil.wgetLoadJsonTime(recordset, tw, tl)
        datafile = j3['idigbio:data']['link']
        # Find the previously published dataset in the current RSS
        if j3['idigbio:data'].get('id', None):
            currDatafile = datautil.findDatafileRssByGuid(rss, j3['idigbio:data']['id'])
        else:
            currDatafile = datautil.findDatafileRssByGuid(rss, j3['idigbio:recordIds'][0])
        if currDatafile is None:
            code = datautil.getCode(datafile)
            numRec = ['0', '0', '0', '0']
            status = "UNPUBLISHED"
        else:
            code = datautil.getCode(currDatafile)
            numRec = datautil.wgetLoadFileTime(currDatafile, item['idigbio:uuid'], tw, tl)
            status = "NOTINPUBLISHERS"
        ingested, recset = datautil.findPubRecordsAndDatafile(recordset, datafile, tw, tl)
        if datafile.endswith(".csv") or datafile.endswith(".tsv"):
            if int(ingested[0]) == 0 and int(ingested[1]) > 0:
                numRec[1] = numRec[0]
                numRec[0] = 0
        indj = datautil.wgetLoadJsonTime('http://search.idigbio.org/idigbio/records/_search?q=recordset:' + recset, tw, tl)
        indj2 = datautil.wgetLoadJsonTime('http://search.idigbio.org/idigbio/mediarecords/_search?q=recordset:' + recset, tw, tl)
        indexed = [indj["hits"]["total"], indj2["hits"]["total"]]
        print r + [status, currDatafile, datafile, pubShortName, code, recset] + numRec + ingested + indexed + [len(recordsets)]
        fw.writerow(r + [status, currDatafile, datafile, pubShortName, code, recset] + numRec + ingested + indexed + [len(recordsets)])
        f.flush()
    # Find all remaining new datasets for this publisher
    newData = datautil.getDatafileGuidInRss(rss)
    for dataset in newData:
        print "===New:", dataset[0], dataset[1]
        code = datautil.getCode(dataset[1])
        numRec = datautil.wgetLoadFileTime(dataset[1], item['idigbio:uuid'], tw, tl)
        print r + ["NEW", '', dataset[1], pubShortName, code, dataset[0]] + numRec + ['0', '0'] + ['0', '0'] + [len(recordsets)]
        fw.writerow(r + ["NEW", '', dataset[1], pubShortName, code, dataset[0]] + numRec + ['0', '0'] + ['0', '0'] + [len(recordsets)])
        f.flush()

sw = sum(tw)
sl = sum(tl)
print "Wget total: " + str(sw) + "s #: " + str(len(tw)) + " Avg: " + str(sw / len(tw))
print "Load total: " + str(sl) + "s #: " + str(len(tl)) + " Avg: " + str(sl / len(tl))
for item1, item2 in zip(tw, tl):
    ft.write(str(item1) + ',' + str(item2) + '\n')
f.close()
ft.close()


text:
package mil.navy.spawar.swif.ldap;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.support.AbstractContextMapper;

public class SwifUserContextMapper extends AbstractContextMapper {

    private String userNameMapping = "cn";
    private String userRealNameMapping;
    private String emailMapping;
    private String organizationMapping;
    private String phoneMapping;

    public Object doMapFromContext(DirContextOperations ctx) {
        SwifUser swifUser = new SwifUser();

        swifUser.setUserName(ctx.getStringAttribute(userNameMapping));
        swifUser.setUserRealName(ctx.getStringAttribute(userRealNameMapping));
        swifUser.setEmail(ctx.getStringAttribute(emailMapping));
        swifUser.setOrganization(ctx.getStringAttribute(organizationMapping));
        swifUser.setPhone(ctx.getStringAttribute(phoneMapping));

        return swifUser;
    }

    public void setUserNameMapping(String userNameMapping) {
        this.userNameMapping = userNameMapping;
    }

    public String getUserNameMapping() {
        return userNameMapping;
    }

    @Required
    public void setUserRealNameMapping(String userRealNameMapping) {
        this.userRealNameMapping = userRealNameMapping;
    }

    @Required
    public void setEmailMapping(String emailMapping) {
        this.emailMapping = emailMapping;
    }

    @Required
    public void setOrganizationMapping(String organizationMapping) {
        this.organizationMapping = organizationMapping;
    }

    @Required
    public void setPhoneMapping(String phoneMapping) {
        this.phoneMapping = phoneMapping;
    }
}


text:
@interface PodsDummy_Pods_Visy : NSObject
@end
@implementation PodsDummy_Pods_Visy
@end


text:
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
  private:
    int sum = 0;
  public:
    int rangeSumBST(TreeNode* root, int low, int high) {
      if(!root) return 0;
      if(root->val >= low and root->val <= high) sum += root->val;
      if(root->val > low) rangeSumBST(root->left, low, high);
      if(root->val < high) rangeSumBST(root->right, low, high);
      return sum;
    }
};


text:
package org.jreform;

import java.util.Map;

/**
 * A select that supports only one selection.
 *
 * @author armandino (at) gmail.com
 */
public interface Select<T> extends Input<T>
{
    public Map<String, SelectableState> getState();
}


text:
module Dynosaur
  module Controllers
    class RediscloudControllerPlugin < AbstractControllerPlugin

      def initialize(config)
        super(config)
        min_resource_name = default_value_if_blank(config['min_resource'], Dynosaur::Addons.all['rediscloud'].first['name'])
        max_resource_name = default_value_if_blank(config['max_resource'], Dynosaur::Addons.all['rediscloud'].last['name'])

        @min_resource = Dynosaur::Addons.plans_for_addon('rediscloud').find {|plan| plan['name'] == min_resource_name }
        if @min_resource.nil?
          raise "Min resource not found with name #{min_resource_name}"
        end
        @max_resource = Dynosaur::Addons.plans_for_addon('rediscloud').find {|plan| plan['name'] == max_resource_name }
        if @max_resource.nil?
          raise "Max resource not found with name #{max_resource_name}"
        end
        @stats_callback = nil # We can't log this on librato as we don't have numeric values
      end

      def scale
        heroku_manager.ensure_value(@current_estimate['name'])
      end

      def heroku_manager
        return @heroku_manager ||= HerokuAddonManager.new('rediscloud', @heroku_api_key, @heroku_app_name, @dry_run)
      end

    end
  end # Controllers
end # Dynosaur


text:
local Dta = select(2, ...)

Dta.ui = {}

Dta.ui.context = UI.CreateContext("Dta")
Dta.ui.context_top = UI.CreateContext("Dta_Top")
Dta.ui.context_top:SetStrata("topmost")
Dta.ui.windowtest = nil
Dta.ui.active = false
Dta.ui.restore = {}

Dta.ui.windowHelp = nil
Dta.ui.activeHelp = false

Dta.ui.loadLoSa = "Default"
Dta.ui.loadExpImp = "Saved"

function Dta.ui.checkNumber(n_str, default)
	if not n_str or n_str == "" then
		return default, true
	end
	local n_val = tonumber(n_str)
	return n_val, n_val ~= nil
end

-------------------------------
-- FOCUS CYCLING WITH [<Shift>]<Tab>
-------------------------------

function Dta.ui.ModifierKeyDownCallback(frame, hEvent, key)
	if key == "Shift" then
		Dta.ui.isShiftPressed = true
	elseif key == "Control" then
		Dta.ui.isControlPressed = true
	end
end

function Dta.ui.ModifierKeyUpCallback(frame, hEvent, key)
	if key == "Shift" then
		Dta.ui.isShiftPressed = false
	elseif key == "Control" then
		Dta.ui.isControlPressed = false
	end
end

function Dta.ui.KeyFocusLossCallback(frame, hEvent)
	if not Dta.ui.keyFocusTransfer then
		Dta.ui.isShiftPressed = false
		Dta.ui.isControlPressed = false
	end
end

-- Note: attaching to UIParent will trigger for any addon
UIParent:EventAttach(Event.UI.Input.Key.Down.Dive, Dta.ui.ModifierKeyDownCallback, "ShiftKeyDownSensor")
UIParent:EventAttach(Event.UI.Input.Key.Up.Dive, Dta.ui.ModifierKeyUpCallback, "ShiftKeyUpSensor")
UIParent:EventAttach(Event.UI.Input.Key.Focus.Loss.Dive, Dta.ui.KeyFocusLossCallback, "KeyFocusSensor")

function Dta.ui.AddFocusCycleElement(owner, frame)
	if not owner.focusCycleList then
		owner.focusCycleList = {}
	end
	local idx = #owner.focusCycleList + 1
	owner.focusCycleList[idx] = frame
	frame.focusCycleIndex = idx
	-- this was not planned, see comment in FocusCycleCallback
	frame.focusCycleList = owner.focusCycleList
end

function Dta.ui.FocusCycleCallback(frame, hEvent, key)
	local target = hEvent:GetTarget()
	-- apparently you can't get a reference to the "owner" frame to which this dive handler
	-- gets attached, instead the "frame" passed is the the target frames (a cycle list entry).
	-- i.e. frame and hEvent:GetTarget() are identical, which is weird
	if key == "Return" then
		target:SetKeyFocus(false)
		return
	elseif key ~= "Tab" or not frame.focusCycleList then
		return
	end

	local idx = target.focusCycleIndex
	if not idx then
		return
	end
	if Dta.ui.isShiftPressed then
		idx = idx - 1
		if idx == 0 then
			idx = #frame.focusCycleList
		end
	else
		idx = idx + 1
		if idx > #frame.focusCycleList then
			idx = 1
		end
	end
	Dta.ui.keyFocusTransfer = true
	frame.focusCycleList[idx]:SetKeyFocus(true)
	Dta.ui.keyFocusTransfer = false
	if type(target.TabFocusCycled) == "function" then
		target.TabFocusCycled(target)
	end
end

-------------------------------
-- CREATION OF THE WINDOW ELLEMENTS
-------------------------------
-- Create a text frame
function Dta.ui.createText(name, parent, x, y, text, fontsize, color, shadow)
	local textFrame = UI.CreateFrame("Text", name, parent)
	textFrame:SetFontSize(fontsize)
	textFrame:SetText(text)
	if x and y then
		textFrame:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
	end
	if color ~= nil then textFrame:SetFontColor(color[1], color[2], color[3], color[4]) end
	if shadow ~= false then textFrame:SetEffectGlow({offsetX=1, offsetY=1}) end
	return textFrame
end

-- create texture
function Dta.ui.createTexture(name, parent, source, texture, x, y, width, height)
	local textureFrame = UI.CreateFrame("Texture", name, parent)
	if texture ~= nil then textureFrame:SetTexture(source, texture) end
	if width ~= nil then textureFrame:SetWidth(width) end
	if height ~= nil then textureFrame:SetHeight(height) end
	textureFrame:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
	return textureFrame
end

-- textfield helper functions
-- TODO: think about proper class hierarchies
function Dta.ui.textfieldSelectAll(self)
	local sval = self:GetText()
	local slen = sval and string.len(sval) or 0
	if slen > 0 then self:SetSelection(0, slen) end
end

local function textfieldSwapText(self)
	local currentText = self:GetText()
	self:SetText(self.text_alt or "")
	self.text_alt = currentText
end

-- create textfield
function Dta.ui.createTextfield(name, parent, x, y, width, text)
	local textfield = UI.CreateFrame("RiftTextfield", name, parent)
	textfield:SetWidth(width)
	textfield:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
	textfield:SetBackgroundColor(0,0,0,0.75)
	if text ~= nil then textfield:SetText(text)
	else textfield:SetText("") end
	textfield.TabFocusCycled = Dta.ui.textfieldSelectAll
	textfield.SwapText = textfieldSwapText
	return textfield
end

-- create reload button to accompany certain textfields
function Dta.ui.createReloadButton(name, parent, x, y, callback)
	local reloadBtn = Dta.ui.Button.Create(name, parent, callback,
			"textures/reload_btn_normal.png",
			"textures/reload_btn_over.png",
			"textures/reload_btn_click.png",
			"textures/reload_btn_disable.png",
			Dta.AddonID
			)
	reloadBtn:SetWidth(20)
	reloadBtn:SetHeight(20)
	reloadBtn:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
	reloadBtn:SetBackgroundColor(0, 0, 0, 0.55)
	return reloadBtn
end

-- checkbox helper function
function Dta.ui.checkboxSetEnabled(self, enabled)
	if enabled then
		self.textFrame:SetAlpha(1)
	else
		self.textFrame:SetAlpha(0.5)
	end
	self:SetEnabled(enabled)
end

-- create checkbox
function Dta.ui.createCheckbox(name, parent, x, y, text, checked, fontColor, checkChangedCallback)
	local checkbox = UI.CreateFrame("RiftCheckbox", name, parent)
	checkbox:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
	if checked ~= nil then checkbox:SetChecked(checked) end

	checkbox.textFrame = Dta.ui.createText(name .. "TextFrame", checkbox, 15, -2, text, 14, fontColor)
	checkbox.CBSetEnabled = Dta.ui.checkboxSetEnabled

	function checkbox.textFrame.Event:LeftClick()
		if checkbox:GetEnabled() then
			checkbox:SetChecked(not checkbox:GetChecked())
		end
	end

	if type(checkChangedCallback) == "function" then
		checkbox:EventAttach(Event.UI.Checkbox.Change, checkChangedCallback, name .. "_changed")
	end
	return checkbox
end

-- Create a frame with a set height and width
function Dta.ui.createFrame(name, parent, x, y, width, height, color)
	local frame = UI.CreateFrame("Frame", name, parent)
	frame:SetHeight(height)
	frame:SetWidth(width)
	frame:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
	if color ~= nil then frame:SetBackgroundColor(color[1], color[2], color[3], color[4]) end
	return frame
end

function Dta.ui.clickCallback(frame, hEvent)
	-- remove key-focus of any other frame by temporarily claiming it
	frame:SetKeyFocus(true)
	frame:SetKeyFocus(false)
end

-- create button
function Dta.ui.createButton(name, parent, x, y, width, height, text, skin, clickCallback)
	local button = UI.CreateFrame("RiftButton", name, parent)

	if skin ~= nil and skin == "close" then
		button:SetSkin("close")
	else
		if text ~= nil then button:SetText(text) end
	end
	if height ~= nil then button:SetHeight(height) end
	if width ~= nil then button:SetWidth(width) end

	button:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)

	if type(clickCallback) == "function" then
		button:EventAttach(Event.UI.Input.Mouse.Left.Click, clickCallback, name .. "_left_click")
	end
	return button
end

-- create drop-down
function Dta.ui.createDropdown(name, parent, x, y, width)
	local dropdown = UI.CreateFrame("SimpleSelect", name, parent)
	dropdown:SetBackgroundColor(0.07, 0.05, 0.01, 0.85)
	dropdown:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
	if width then dropdown:SetWidth(width) end
	return dropdown
end

-------------------------------
-- BUILD THE MAINWINDOW TOGGLE BUTTON
-------------------------------

local MainButtonSettings = {
	POS_X = "MainbuttonPosX",
	POS_Y = "MainbuttonPosY"
}

function Dta.ui.showMainButton()
	if not Dta.ui.buttonMainToggle then
		Dta.ui.buttonMainToggle = Dta.ui.Button.Create("UI_Toggle_Button", Dta.ui.context,
			function(self, h) Dta.ui.toggleMainWindow() end,
			"btn_dimensions_top_edit_(normal).png.dds",
			"btn_dimensions_top_edit_(over).png.dds",
			"btn_dimensions_top_edit_(click).png.dds",
			"btn_dimensions_top_edit_(disabled).png.dds"
			)
		Dta.ui.buttonMainToggle.settings = MainButtonSettings
		Dta.ui.buttonMainToggle:SetWidth(48)
		Dta.ui.buttonMainToggle:SetHeight(48)
		Dta.ui.buttonMainToggle:SetLayer(-1)
		Dta.ui.buttonMainToggle:SetPoint("TOPLEFT", UIParent, "TOPLEFT", Dta.settings.get("MainbuttonPosX"), Dta.settings.get("MainbuttonPosY"))
		Dta.ui.DraggableFrame.Setup(Dta.ui.buttonMainToggle, Dta.ui.buttonMainToggle, Dta.ui.WindowMoved, "Right")
	end
	Dta.ui.buttonMainToggle:SetVisible(true)
end

function Dta.ui.hideMainButton()
	if Dta.ui.buttonMainToggle then
		Dta.ui.buttonMainToggle:SetVisible(false)
	end
end
-------------------------------
-- BUILD THE DIMENSIONTOOLS MAINWINDOW
-------------------------------

local MainWindowSettings = {
	WIDTH = 325,
	HEIGHT = 255,
	CLOSABLE = true,
	MOVABLE = true,
	POS_X = "MainwindowPosX",
	POS_Y = "MainwindowPosY"
}
local BGwidth, BGheight = 313, 125
local BGpath = {	{x = 0, y = 10},
					{x = 10, y = 0, xControl = 0, yControl = 0},
					{x = BGwidth - 10, y = 0 },
					{x = BGwidth, y = 10, xControl = BGwidth, yControl = 0},
					{x = BGwidth, y = BGheight - 10},
					{x = BGwidth - 10, y = BGheight, xControl = BGwidth, yControl = BGheight},
					{x = 10, y = BGheight },
					{x = 0, y = BGheight - 10, xControl = 0, yControl = BGheight},
					{x = 0, y = 10} }

function Dta.ui.buildMainWindow()
	local x = Dta.settings.get("MainwindowPosX")
	local y = Dta.settings.get("MainwindowPosY")
	--Mainwindow = Dta.ui.createWindow("MainWindow",
	local newWindow = Dta.ui.Window.Create("MainWindowNew",
							Dta.ui.context,
							Dta.Locale.Titles.Main,
							MainWindowSettings.WIDTH,
							MainWindowSettings.HEIGHT,
							x, y,
							MainWindowSettings.CLOSABLE,
							MainWindowSettings.MOVABLE,
							Dta.ui.MainWindowClosed,
							Dta.ui.WindowMoved
							)
	newWindow.settings = MainWindowSettings
	newWindow.versionText = Dta.ui.createText("versionText", newWindow, 20, 16, Dta.Version, 12, {0.3, 0.6, 0.6, 1})
	newWindow.versionText:SetLayer(15)
	local Mainwindow = newWindow.content

	Mainwindow.detailsBG = UI.CreateFrame("Canvas", "ItemDetailsBackground", Mainwindow)
	Mainwindow.detailsBG:SetPoint("TOPLEFT", Mainwindow, "TOPLEFT", 5, 3)
	Mainwindow.detailsBG:SetShape(BGpath, {type = "solid", r=0.07, g=0.01, b=0, a=0.6}, {r=0, g=0, b=0, a=0.4, thickness=3})
	-------------------------------
	--ITEM DETAILS
	-------------------------------

	Mainwindow.itemDetails = Dta.ui.createFrame("itemDetails", Mainwindow, 10, 13, Mainwindow:GetWidth()-20, 120)
	Mainwindow.itemDetails:SetLayer(30)
	--Mainwindow.itemDetails:SetBackgroundColor(1, 0, 0, 0.5) --Debug

	Mainwindow.itemDetails.icon = Dta.ui.createTexture("itemDetailsIcon", Mainwindow.itemDetails, nil, nil, 0, 0, 25, 25)
	Mainwindow.itemDetails.icon:SetLayer(35)
	Mainwindow.itemDetails.name = Dta.ui.createText("itemDetailsName", Mainwindow.itemDetails, 30, 0, Dta.Locale.Text.NothingSelected, 16)
	Mainwindow.itemDetails.name:SetWidth(270)
	Mainwindow.itemDetails.name:SetWordwrap(true)
	Mainwindow.itemDetails.name:ClearPoint("TOPLEFT")
	Mainwindow.itemDetails.name:SetPoint("CENTERLEFT", Mainwindow.itemDetails, "TOPLEFT", 41, 12)
	Mainwindow.itemDetails.name:SetEffectGlow({offsetX=1, offsetY=1, strength=2})
	Mainwindow.itemDetails.icon:EventAttach(Event.UI.Input.Mouse.Right.Click,
		function(self, h)
			if Dta.selectionCount > 0 then Command.Map.Waypoint.Set(Dta.selectionCenter.x, Dta.selectionCenter.z) end
		end,
		"Waypoint Marker")
	-- clear selection button
	Mainwindow.itemDetails.clearSelection = Dta.ui.createButton("clearSelection", Mainwindow.itemDetails, 20, -7, 18, 18, nil, "close", Dta.ui.clearSelectionButtonClicked)
	Mainwindow.itemDetails.clearSelection:SetLayer(40)
	Mainwindow.itemDetails.clearSelection:SetVisible(false)

	Mainwindow.itemDetails.xLabel = Dta.ui.createText("itemDetailsXLabel", Mainwindow.itemDetails, 0, 30, "X", 14, {1, 0, 0, 1})
	Mainwindow.itemDetails.yLabel = Dta.ui.createText("itemDetailsYLabel", Mainwindow.itemDetails, 0, 50, "Y", 14, {0, 1, 0, 1})
	Mainwindow.itemDetails.zLabel = Dta.ui.createText("itemDetailsZLabel", Mainwindow.itemDetails, 0, 70, "Z", 14, {0, 1, 1, 1})

	Mainwindow.itemDetails.x = Dta.ui.createText("itemDetailsX", Mainwindow.itemDetails, 25, 30, "-", 14)
	Mainwindow.itemDetails.y = Dta.ui.createText("itemDetailsY", Mainwindow.itemDetails, 25, 50, "-", 14)
	Mainwindow.itemDetails.z = Dta.ui.createText("itemDetailsZ", Mainwindow.itemDetails, 25, 70, "-", 14)

	Mainwindow.itemDetails.pitchLabel = Dta.ui.createText("itemDetailsPitchLabel", Mainwindow.itemDetails, 125, 30, Dta.Locale.Text.Pitch, 14, {1, 0, 0, 1})
	Mainwindow.itemDetails.yawLabel = Dta.ui.createText("itemDetailsYawLabel", Mainwindow.itemDetails, 125, 50, Dta.Locale.Text.Yaw, 14, {0, 1, 0, 1})
	Mainwindow.itemDetails.rollLabel = Dta.ui.createText("itemDetailsRollLabel", Mainwindow.itemDetails, 125, 70, Dta.Locale.Text.Roll, 14, {0, 1, 1, 1})

	Mainwindow.itemDetails.pitch = Dta.ui.createText("itemDetailsPitch", Mainwindow.itemDetails, 175, 30, "-", 14)
	Mainwindow.itemDetails.yaw = Dta.ui.createText("itemDetailsYaw", Mainwindow.itemDetails, 175, 50, "-", 14)
	Mainwindow.itemDetails.roll = Dta.ui.createText("itemDetailsRoll", Mainwindow.itemDetails, 175, 70, "-", 14)

	Mainwindow.itemDetails.scaleLabel = Dta.ui.createText("itemDetailsScaleLabel", Mainwindow.itemDetails, 0, 90, Dta.Locale.Text.Scale, 14)
	Mainwindow.itemDetails.scale = Dta.ui.createText("itemDetailsScale", Mainwindow.itemDetails, 50, 90, "-", 14)

	-- Tool Buttons
	Mainwindow.MoveBtn = Dta.ui.createButton("itemDetailMoveBtn", Mainwindow, 8, 133, 160, nil, Dta.Locale.Buttons.MoveWindow, nil, Dta.Tools.Move.Toggle)
	Mainwindow.RotateBtn = Dta.ui.createButton("itemDetailRotateBtn", Mainwindow, 157, 133, 160, nil, Dta.Locale.Buttons.RotateWindow, nil, Dta.Tools.Rotate.Toggle)
	Mainwindow.ScaleBtn = Dta.ui.createButton("mitemDetailScaleBtn", Mainwindow, 8, 160, 160, nil, Dta.Locale.Buttons.ScaleWindow, nil, Dta.Tools.Scale.Toggle)
	Mainwindow.Measurements = Dta.ui.createButton("itemDetailMeasurementsBtn", Mainwindow, 157, 160, 160, nil, Dta.Locale.Buttons.OffsetCalc, nil, Dta.Tools.Offset.Toggle)
	Mainwindow.CoPaBtn = Dta.ui.createButton("itemDetailCoPaBtn", Mainwindow, 8, 187, 160, nil, Dta.Locale.Buttons.CopyPaste, nil, Dta.Tools.CoPa.Toggle)
	Mainwindow.SaveBtn = Dta.ui.createButton("itemDetailSaveBtn", Mainwindow, 157, 187, 160, nil, Dta.Locale.Buttons.LoadSave, nil, Dta.Tools.LoSa.Toggle)
	--Mainwindow.itemDetails.ImpExpBtn = Dta.ui.createButton("itemDetailImpExpBtn", Mainwindow.itemDetails, 290, 150, 160, nil, Dta.Locale.Buttons.ImportExport, nil, Dta.Tools.ExpImp.Toggle)
	Mainwindow.DFlying = Dta.ui.createButton("itemDetailDFlyingBtn", Mainwindow, 8, 214, 160, nil, Dta.Locale.Buttons.TribalMagic, nil, Dta.Tools.Flying.Toggle)
	Mainwindow.MoreBtn = Dta.ui.createButton("itemDetailMoreBtn", Mainwindow, 157, 214, 160, nil, Dta.Locale.Buttons.More, nil, Dta.ui.moreBtnClicked)
	-- Expanded: see Dta.ui.moreBtnClicked()

	-- help button
	newWindow.help = Dta.ui.Button.Create("mainwindow_help", newWindow, Dta.help_ui.toggleHelpWindow,
		"btn_dimensions_top_help_(normal).png.dds",
		"btn_dimensions_top_help_(over).png.dds",
		"btn_dimensions_top_help_(click).png.dds")
	newWindow.help:SetPoint("TOPRIGHT", newWindow.closeBtn, "TOPLEFT", 0, -1)
	newWindow.help:SetWidth(36)
	newWindow.help:SetHeight(36)
	newWindow.help:SetLayer(11)
	if Dta.ui.activeHelp then
		newWindow.help:Toggle(true)
	end

	-- TODO: temp fix for new window hierarchy
	newWindow.itemDetails = Mainwindow.itemDetails

	return newWindow
end

-- Show the Main window
function Dta.ui.showMainWindow()
	Dta.constructionsdefaults = Dta.settings.get_defaults("SavedSets") --or {}
	Dta.constructionstbx = tbx_import.get("savedConstructions")
	Dta.ExportImport_Sets = Dta_export.get("ExportImport")--or {}
	--Dta.alphabet.Fonts = Dta.settings.get_alphabetFonts("SavedAlphabets")
	--Dta.Replacement.Skins = Dta.settings.get_Skins("SavedSkins")
	if Dta.ui.windowtest == nil then
		Dta.ui.windowtest = Dta.ui.buildMainWindow()
	else
		Dta.ui.windowtest:SetVisible(true)
	end
	Dta.ui.active = true
	Dta.items.updateItemDetails()
	if Dta.settings.get("RestoreTools") then
		for name, active in pairs(Dta.ui.restore) do
			if active then
				Dta.Tools[name]:Toggle()
			end
		end
	end
end

-- Hide the Main window
function Dta.ui.hideMainWindow()
	Dta.ui.windowtest:SetVisible(false)
--	Dta.ui.windowtest = nil
	Dta.ui.active = false
	for name, tool in pairs(Dta.Tools) do
		local active = tool:IsActive()
		if active then
			tool.Toggle()
		end
		Dta.ui.restore[name] = active
	end
	if Dta.ui.activeHelp then Dta.help_ui.hideHelpWindow() end
end

-- Toggle the Main window
function Dta.ui.toggleMainWindow()
	if Dta.ui.active then Dta.ui.hideMainWindow()
	else Dta.ui.showMainWindow() end
end

--Called when the window has been moved
function Dta.ui.WindowMoved(self)
	Dta.settings.set(self.settings.POS_X, self:GetLeft())
	Dta.settings.set(self.settings.POS_Y, self:GetTop())
end

--Called when the window has been closed
function Dta.ui.MainWindowClosed()
	Dta.ui.hideMainWindow()
end

-------------------------------
-- CALLBACKS FOR WINDOW BUTTONS
-------------------------------

function Dta.ui.moreBtnClicked()
	local mainWindow = Dta.ui.windowtest.content
	mainWindow.MoreBtn:SetVisible(false)
	if not mainWindow.Alphabet then
		mainWindow.Alphabet = Dta.ui.createButton("itemDetailAlphabetBtn", mainWindow, 157, 214, 160, nil, "Alfiebet", nil, Dta.Tools.Alfiebet.Toggle)
		mainWindow.ReskinBtn = Dta.ui.createButton("itemDetailReskinBtn", mainWindow, 8, 241, 160, nil, Dta.Locale.Buttons.Reskin, nil, Dta.Tools.Reskin.Toggle)
		mainWindow.SelectionsBtn = Dta.ui.createButton("itemDetailSelectionBtn", mainWindow, 157, 241, 160, nil, Dta.Locale.Buttons.Selection, nil, Dta.Tools.Select.Toggle)
		mainWindow.ConnectorBtn = Dta.ui.createButton("itemDetailConnectorBtn", mainWindow, 8, 268, 160, nil, "<Connector>", nil, Dta.Tools.Connector.Toggle)
		mainWindow.LessBtn = Dta.ui.createButton("itemDetailLessBtn", mainWindow, 157, 268, 160, nil, Dta.Locale.Buttons.Less, nil, Dta.ui.lessBtnClicked)
	else
		mainWindow.Alphabet:SetVisible(true)
		mainWindow.ReskinBtn:SetVisible(true)
		mainWindow.SelectionsBtn:SetVisible(true)
		mainWindow.ConnectorBtn:SetVisible(true)
		mainWindow.LessBtn:SetVisible(true)
	end
	Dta.ui.windowtest:SetContentHeight(MainWindowSettings.HEIGHT + 2*27)
end

function Dta.ui.lessBtnClicked()
	local mainWindow = Dta.ui.windowtest.content
	mainWindow.Alphabet:SetVisible(false)
	mainWindow.ReskinBtn:SetVisible(false)
	mainWindow.SelectionsBtn:SetVisible(false)
	mainWindow.ConnectorBtn:SetVisible(false)
	mainWindow.LessBtn:SetVisible(false)
	mainWindow.MoreBtn:SetVisible(true)
	Dta.ui.windowtest:SetContentHeight(MainWindowSettings.HEIGHT)
end

function Dta.ui.clearSelectionButtonClicked()
	-- NOTE: in contrast to Dta.items.DeselectAll(), this function doesn't verify
	-- current selection state, and clears IDs from selection regardless of their validity.
	-- We want to recover from any selection state bugs here
	for id,Details in pairs(Dta.selectedItems) do
		local detail = Inspect.Dimension.Layout.Detail(Details.id)
		if detail ~= nil then
			Dta.items.QueueDeselection(Details.id)
		end
		-- already nil it here, item updates are not reliable when we lost sync unfortunately
		Dta.selectedItems[id] = nil
	end
	Dta.selectionChanged = Dta.selectionCount ~= 0
	Dta.selectionCount = 0
	Dta.items.updateItemDetails()
end

-------------------------------
-- NOTIFICATION WINDOW
-------------------------------

function Dta.ui.buildNotificationWindow()
	local newWindow = Dta.ui.Window.CreatePopup("NotificationWindow",
							Dta.ui.context_top,
							500, -- width
							110, -- height
							100, 100, -- x, y
							true) -- movable

	newWindow.Message = Dta.ui.createText("confirmationDialogueMessage", newWindow, 10, 0, "-", 16)
	newWindow.Message:ClearPoint("TOPLEFT")
	newWindow.Message:SetPoint("TOPCENTER", newWindow, "TOPCENTER", 0, 10)
	newWindow.Message2 = Dta.ui.createText("confirmationDialogueMessage", newWindow, 10, 0, "-", 16)
	newWindow.Message2:ClearPoint("TOPLEFT")
	newWindow.Message2:SetPoint("TOPCENTER", newWindow.Message, "BOTTOMCENTER")
	newWindow.YesBtn = Dta.ui.createButton("errorBtn_Yes", newWindow, 80, 70, 160, nil, Dta.Locale.Buttons.Yes, nil, Dta.ui.notificationWindowButtonClicked)
	newWindow.NoBtn = Dta.ui.createButton("errorBtn_No", newWindow, 260, 70, 160, nil, Dta.Locale.Buttons.No, nil, Dta.ui.notificationWindowButtonClicked)
	return newWindow
end

-- if btn<n>_callcack is a function, it will be called with userdata as argument on button press,
-- else if userdata is a coroutine, the coroutine will be resumed with btn<n>_callback as argument
function Dta.ui.showNotification(message, btn1_callback, btn2_callback, userdata, btn1_text, btn2_text)
	if Dta.ui.notificationWindow == nil then
		Dta.ui.notificationWindow = Dta.ui.buildNotificationWindow()
	end
	local newline = message:find("\n")
	if newline then
		Dta.ui.notificationWindow.Message:SetText(message:sub(1, newline-1))
		Dta.ui.notificationWindow.Message2:SetText(message:sub(newline+1))
	else
		Dta.ui.notificationWindow.Message:SetText(message)
		Dta.ui.notificationWindow.Message2:SetText("")
	end
	Dta.ui.notificationWindow.YesBtn:SetText(btn1_text or Dta.Locale.Buttons.Yes)
	Dta.ui.notificationWindow.NoBtn:SetText(btn2_text or Dta.Locale.Buttons.No)
	Dta.ui.notificationWindow.YesBtn.click_callback = btn1_callback
	Dta.ui.notificationWindow.NoBtn.click_callback = btn2_callback
	Dta.ui.notificationWindow.user_data = userdata
	local x = (UIParent:GetWidth() - Dta.ui.notificationWindow:GetWidth())/2
	local y = (UIParent:GetHeight() - Dta.ui.notificationWindow:GetHeight())/2
	Dta.ui.notificationWindow:SetPoint("TOPLEFT", UIParent, "TOPLEFT", x, y)
	Dta.ui.notificationWindow:SetVisible(true)
end

function Dta.ui.showConfirmation(message, btn1_callback, btn2_callback, userdata)
	Dta.ui.showNotification(message, btn1_callback, btn2_callback, userdata,
							Dta.Locale.Buttons.OK, Dta.Locale.Buttons.Cancel)
end

function Dta.ui.notificationWindowButtonClicked(self, event)
	Dta.ui.notificationWindow:SetVisible(false)
	if type(self.click_callback) == "function" then
		self.click_callback(Dta.ui.notificationWindow.user_data)
	elseif type(Dta.ui.notificationWindow.user_data) == "thread" then
		coroutine.resume(Dta.ui.notificationWindow.user_data, self.click_callback)
	end
end


text:
[![Stories in Ready](https://badge.waffle.io/mumuki/mumuki-text-runner.png?label=ready&title=Ready)](https://waffle.io/mumuki/mumuki-text-runner)
[![Build Status](https://travis-ci.org/mumuki/mumuki-text-runner.svg?branch=master)](https://travis-ci.org/mumuki/mumuki-text-runner)
[![Code Climate](https://codeclimate.com/github/mumuki/mumuki-text-runner/badges/gpa.svg)](https://codeclimate.com/github/mumuki/mumuki-text-runner)
[![Test Coverage](https://codeclimate.com/github/mumuki/mumuki-text-runner/badges/coverage.svg)](https://codeclimate.com/github/mumuki/mumuki-text-runner/coverage)

# mumuki-text-runner
> Sinatra server for validating text exercises within [Mumuki](http://github.com/mumuki)

#Prerequisites
  Install rbenv:

>You can install rbenv following the instructions of this [Link](http://uqbar-wiki.org/index.php?title=Gu%C3%ADa_de_Instalaci%C3%B3n_de_Ruby)

#Setup
 Open  the Terminal Console, located in this project's
 directory, run the following commands:

  bundle install

#RUN TESTS

Note: When running tests you may recieve a Warning like this one:

` "[2015-07-16T11:03:48.197981 #2823]  INFO -- : Not reporting  to Code Climate because ENV'CODECLIMATE_REPO_TOKEN'] is not set."`

  Don't worry about that, it doesn't mean that test is not working.

If you want to run tests by console you can do the following steps:
  Open the Terminal console and inside the Project's directory    run the following commands:

    bundle exec rspec

(that should run the expectation tests)

Also you can all the tests running the following command:

    bundle exec rake

If you want to run the test using rubymine just look for the "spec"     folder inside mumuki-text-runner project, right click on the      prevously mention folder and click on "Run all Specs..." option.

If you have done the steps correctly both ways of running test should do it successfully.


text:
biitstrap
=========

biitstrap is my in house front-end framework.


text:
package com.rao.loveyou.ui.fragment;

import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;

import com.rao.loveyou.R;
import com.rao.loveyou.ui.adapter.desiger.DesigerAdapter;
import com.rao.loveyou.ui.adapter.desiger.DesigerManager01;
import com.rao.loveyou.ui.base.BaseFragment;

import butterknife.BindView;

/**
 * @auther rjl
 * @time 2017/8/29.
 * @descr
 */

public class DesigerFragment extends BaseFragment {
    private static final String TAG = "DesigerFragment";

    /**
     * UI
     */
    @BindView(R.id.recyview_desiger_fragment)
    RecyclerView mRecyclerView;

    /**
     * data
     */
    private DesigerAdapter mDesigerAdapter;
    private ItemTouchHelper mItemTouchHelper;

    @Override
    protected void initPresenter() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_desiger;
    }

    @Override
    protected void initData() {
        super.initData();
        mDesigerAdapter = new DesigerAdapter(mActivity, null);
        //mRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        mRecyclerView.setLayoutManager(new DesigerManager01());
       /* mItemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP| ItemTouchHelper.DOWN|ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT,
                ItemTouchHelper.UP| ItemTouchHelper.DOWN| ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                Log.i(TAG, "onMove: ");
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                Log.i(TAG, "onSwiped: ");
            }

            @Override
            public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
                Log.i(TAG, "onChildDraw: ");
            }
        });*/
       // mItemTouchHelper.attachToRecyclerView(mRecyclerView);
        mRecyclerView.setAdapter(mDesigerAdapter);
    }
}


text:
<?php

namespace Tests\Notification\SNS;

class MessageListProcessorTest {
    const CLASS_NAME = __CLASS__;
}


text:
"""
Shapeshift API Python
EvanM / September 21 2017
"""

import json
import requests

class ShapeShift:
    def __init__(self):
        self.baseurl = "https://shapeshift.io/"
        self.api_doc = "https://info.shapeshift.io/api/"

    def __str__(self):
        return "Python implementation for Shapeshift.io \n" \
               "Documentation can be found here: {}" \
               " \nVersion 1 ".format(self.api_doc)

    def __get(self, url, param):  # Get Request (Low Level API call)
        page = requests.get(url, param)
        return page.text

    def __post(self, url, param):  # Post Request (Low Level API call)
        page = requests.post(url, data=param)
        return page.text

    def __apicall_get(self, endpoint, param={}, arg=''):
        url = self.baseurl + "{}".format(endpoint)
        if arg != '':
            url = url + "/{}".format(arg)
        answer = self.__get(url, param)
        return json.loads(answer)

    def __api_call_post(self, endpoint, param={}, arg=''):
        url = self.baseurl + "{}".format(endpoint)
        if arg != '':
            url = url + "/{}".format(arg)
        answer = self.__post(url, param)
        return json.loads(answer)

    def rate(self, pair):
        """
        Gets the current rate offered by Shapeshift. This is an estimate because the rate can
        occasionally change rapidly depending on the markets. The rate is also a 'use-able' rate
        not a direct market rate. Meaning multiplying your input coin amount times the rate should
        give you a close approximation of what will be sent out. This rate does not include the
        transaction (miner) fee taken off every transaction.

        :param pair: is any valid coin pair such as btc_ltc or ltc_btc
        :return: json object

        url: shapeshift.io/limit/[pair]
        method: GET

        """
        return self.__apicall_get(endpoint='limit', param={}, arg=pair)

    def marketinfo(self, pair=''):
        """
        This gets the market info (pair, rate, limit, minimum limit, miner fee)

        :param pair: (OPTIONAL) is any valid coin pair such as btc_ltc or ltc_btc.
        The pair is not required and if not specified will return an array of all market infos.
        :return: json object

        url: shapeshift.io/marketinfo/[pair]
        method: GET
        """

        return self.__apicall_get(endpoint='marketinfo', param={}, arg=pair)

    def recenttx(self, maxtx=5):
        """
        Get a list of the most recent transactions.

        :param maxtx: is an optional maximum number of transactions to return. If [maxtx] is not
        specified this will return 5 transactions.Also, [maxtx] must be a number between 1
        and 50 (inclusive).
        :return: json object

        url: shapeshift.io/recenttx/[maxtx]
        method: GET
        """
        if maxtx > 50:
            raise ValueError('error maxtx over 50')
        return self.__apicall_get(endpoint='recenttx', param={}, arg=str(maxtx))

    def txstat(self, address):
        """
        This returns the status of the most recent deposit transaction to the address.

        :param address: is the deposit address to look up
        :return: (various depending on status)

        url: shapeshift.io/txStat/[address]
        method: GET
        """
        return self.__apicall_get(endpoint='txstat', param={}, arg=address)

    def timeremaining(self, address):
        """
        When a transaction is created with a fixed amount requested there is a 10 minute window for
        the deposit. After the 10 minute window if the deposit has not been received the transaction
        expires and a new one must be created. This api call returns how many seconds are left before
        the transaction expires. Please note that if the address is a ripple address, it will include
        the "?dt=destTagNUM" appended on the end, and you will need to use the URIEncodeComponent()
        function on the address before sending it in as a param, to get a successful response.
        If the status is expired then seconds_remaining will show 0.

        :param address: is the deposit address to look up
        :return: json object

        url: shapeshift.io/timeremaining/[address]
        method: GET
        """
        return self.__apicall_get(endpoint='timeremaining', param={}, arg=address)

    def onlinecoins(self):
        """
        This endpoint will return the ticker of all available coins.

        url: shapeshift.io/onlinecoins
        method: GET
        """
        return self.__apicall_get(endpoint="onlinecoins",param={})

    def offlinecoins(self):
        """
        This endpoint will return the ticker of all available coins.

        url: shapeshift.io/onlinecoins
        method: GET
        """
        return self.__apicall_get(endpoint="offlinecoins",param={})

    def validpairs(self):
        """
        This endpoint will return all valid coin pairs available on ShapeShift.
        """
        return self.__apicall_get(endpoint="validpairs",param={})

    def getcoins(self):
        """
        Allows anyone to get a list of all the currencies that Shapeshift currently supports at any
        given time. The list will include the name, symbol, availability status, and an icon link for
        each.
        :return: json object

        url: shapeshift.io/getcoins
        method: GET
        """
        return self.__apicall_get(endpoint='getcoins', param={})

    def txbyapikey(self, apikey):
        """
        Allows vendors to get a list of all transactions that have ever been done using a
        specific API key. Transactions are created with an affilliate PUBLIC KEY, but they
        are looked up using the linked PRIVATE KEY, to protect the privacy of our affiliates'
        account details.

        :param apikey: is the affiliate's PRIVATE api key.
        :return:

        url: shapeshift.io/txbyapikey/[apiKey]
        method: GET
        """
        return self.__apicall_get(endpoint='txbyapikey', param={}, arg=apikey)

    def txbyaddress(self, address, apikey):
        """
        Allows vendors to get a list of all transactions that have ever been sent to one of
        their addresses. The affilliate's PRIVATE KEY must be provided, and will only return
        transactions that were sent to output address AND were created using / linked to the
        affiliate's PUBLIC KEY. Please note that if the address is a ripple address and it
        includes the "?dt=destTagNUM" appended on the end, you will need to use the
        URIEncodeComponent() function on the address before sending it in as a param, to get
        a successful response.

        :param address: the address that output coin was sent to for the shift
        :param apikey:  is the affiliate's PRIVATE api key.

        :return: json object

        url: shapeshift.io/txbyaddress/[address]/[apiKey]
        method: GET
        """
        return self.__apicall_get(endpoint='txbyaddress', param={},
                                  arg="{}/{}".format(address, apikey))

    def validateaddress(self, address, coinSymbol):
        """
        Allows user to verify that their receiving address is a valid address according to a
        given wallet daemon. If isvalid returns true, this address is valid according to the
         coin daemon indicated by the currency symbol.

        :param address: the address that the user wishes to validate
        :param coinSymbol: the currency symbol of the coin
        :return: json object

        url: shapeshift.io/validateAddress/[address]/[coinSymbol]
        method: GET
        """
        return self.__apicall_get(endpoint='validateAddress', param={},
                                  arg="{}/{}".format(address, coinSymbol))

    def shift(self, pair, returnAddress=None,
              destTag=None, rsAddress=None, apiKey=None):
        """
        This is the primary data input into ShapeShift.

        :param withdrawal: the address for resulting coin to be sent to
        :param pair: what coins are being exchanged in the form [input coin]_[output coin]  ie btc_ltc
        :param returnAddress: (Optional) address to return deposit to if anything goes wrong with exchange
        :param destTag: (Optional) Destination tag that you want appended to a Ripple payment to you
        :param rsAddress: (Optional) For new NXT accounts to be funded, you supply this on NXT payment to you
        :param apiKey: (Optional) Your affiliate PUBLIC KEY, for volume tracking, affiliate payments, split-shifts, etc...
        :return: json object

        url:  shapeshift.io/shift
        method: POST
        data type: JSON

        example data: {"withdrawal":"AAAAAAAAAAAAA", "pair":"btc_ltc", returnAddress:"BBBBBBBBBBB"}
        """
        payload = {
            'withdrawal'   : withdrawal,
            'pair'         : pair,
            'returnAddress': returnAddress,
            'destTag'      : destTag,
            'rsAddress'    : rsAddress,
            'apiKey'       : apiKey}

        payload = {k: v for k, v in payload.items() if v is not None}  # filter empty values

        return self.__api_call_post(endpoint='shift', param=payload)

    def mail(self, email, txid):
        """
        This call requests a receipt for a transaction. The email address will be added to the
        conduit associated with that transaction as well. (Soon it will also send receipts to
        subsequent transactions on that conduit)

        :param email: the address for receipt email to be sent to
        :param txid: the transaction id of the transaction TO the user (ie the txid for the
                     withdrawal NOT the deposit)
        :return: json object

        url:  shapeshift.io/mail
        method: POST
        data type: JSON
        data required:

        example data {"email":"mail@example.com", "txid":"123ABC"}
        """
        payload = {
            'email': email,
            'txid' : txid}

        return self.__api_call_post(endpoint='mail', param=payload)

    def sendamount(self, amount, pair,withdrawal,
                   returnAddress=None, destTag=None, rsAddress=None,
                   apiKey=None):
        """
        This call allows you to request a fixed amount to be sent to the withdrawal address.
        You provide a withdrawal address and the amount you want sent to it. We return the amount
        to deposit and the address to deposit to. This allows you to use shapeshift as a payment
        mechanism. This call also allows you to request a quoted price on the amount of a
        transaction without a withdrawal address.

        :param amount: the amount to be sent to the withdrawal address
        :param withdrawal: the address for coin to be sent to
        :param pair: what coins are being exchanged in the form [input coin]_[output coin]
        ie ltc_btc
        :param returnAddress: (Optional) address to return deposit to if anything goes wrong with
        exchange
        :param destTag: (Optional) Destination tag that you want appended to a Ripple payment to you
        :param rsAddress: (Optional) For new NXT accounts to be funded, supply this on NXT payment
        to you
        :param apiKey: (Optional) Your affiliate PUBLIC KEY, for volume tracking, affiliate
        payments, split-shifts, etc...
        :return: json object

        url: shapeshift.io/sendamount
        method: POST
        data type: JSON

        //1. Send amount request
          Data required:
        example data {"amount":123, "withdrawal":"123ABC", "pair":"ltc_btc", returnAddress:"BBBBBBB"}

        //2. Quoted Price request
        //Note :  This request will only return information about a quoted rate
        //         This request will NOT generate the deposit address.

          Data required:

        amount  = the amount to be sent to the withdrawal address
        pair    = what coins are being exchanged in the form [input coin]_[output coin]  ie ltc_btc

        example data {"amount":123, "pair":"ltc_btc"}

        """
        payload = {
            'amount'       : pair,
            'withdrawal'   : withdrawal,
            'pair'         : pair,
            'returnAddress': returnAddress,
            'destTag'      : destTag,
            'rsAddress'    : rsAddress,
            'apiKey'       : apiKey}

        payload = {k: v for k, v in payload.items() if v is not None}  # filter empty values

        return self.__api_call_post(endpoint='sendamount', param=payload)

    def cancelpending(self, adddress):
        """
        This call allows you to request for canceling a pending transaction by the deposit address.
        If there is fund sent to the deposit address, this pending transaction cannot be canceled.
        :param adddress: The deposit address associated with the pending transaction
        :return: json object

        url: shapeshift.io/cancelpending
        method: POST
        data type: JSON

        Example data : {address : "1HB5XMLmzFVj8ALj6mfBsbifRoD4miY36v"}
        """

        return self.__api_call_post(endpoint='cancelpending', param={'address': adddress})

    def orderinfo(self,order_id):
        """
        This endpoint will return information related to the Order ID in question, including status, withdraw address, deposit addresses, incoming coin, outgoing coin, all transaction hashes, all URLs, and time-based information.
        :param order_id: The order id returned in the response of a transaction
        :return: json object

        url: shapeshift.io/orderInfo/[order_id]
        method: GET
        data type: JSON
        """

        return self.__apicall_get(endpoint='orderInfo', param={}, arg=order_id)


text:
package main

import (
	"github.com/russmack/cloudsigma"
	"github.com/russmack/replizer"
	"github.com/russmack/statemachiner"
)

type CommandLocations struct {
	channels *replizer.Channels
}

func NewLocations() *CommandLocations {
	return &CommandLocations{}
}

func (m *CommandLocations) Start(channels *replizer.Channels) {
	m.channels = channels
	stateMachine := &statemachiner.StateMachine{}
	stateMachine.StartState = m.getLocations
	cargo := CommandLocations{}
	stateMachine.Start(cargo)
}

func (m *CommandLocations) getLocations(cargo interface{}) statemachiner.StateFn {
	o := cloudsigma.NewLocations()
	args := o.NewList()
	args.Location = session.Location
	_ = sendRequest(m.channels, args)
	return nil
}


text:
CREATE TABLE {$NAMESPACE}_phortune.phortune_merchant (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  phid VARCHAR(64) NOT NULL COLLATE utf8_bin,
  name VARCHAR(255) NOT NULL COLLATE utf8_bin,
  viewPolicy VARCHAR(64) NOT NULL COLLATE utf8_bin,
  editPolicy VARCHAR(64) NOT NULL COLLATE utf8_bin,
  dateCreated INT UNSIGNED NOT NULL,
  dateModified INT UNSIGNED NOT NULL,
  UNIQUE KEY `key_phid` (phid)
) ENGINE=InnoDB, COLLATE=utf8_bin;


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <parent>
        <artifactId>dcm4chee-web</artifactId>
        <groupId>dcm4che.dcm4chee</groupId>
        <version>3.0.1</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <groupId>dcm4che.dcm4chee</groupId>
    <artifactId>dcm4chee-web-urlprovider</artifactId>
    <packaging>jar</packaging>
    <version>3.0.1</version>
    <name>Url provider for dcm4chee-web</name>
    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.1</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.5</source>
                    <target>1.5</target>
                </configuration>
            </plugin>
	</plugins>
    </build>
</project>


text:
<?php
/**
 * Functions
 *
 * @author Yithemes
 * @package YITH WooCommerce Ajax Search
 * @version 1.1.1
 */

if ( !defined( 'YITH_WCAS' ) ) { exit; } // Exit if accessed directly


text:
package org.onosproject.yangutils.translator.tojava.javamodel;

import org.onosproject.yangutils.datamodel.YangType;
import org.onosproject.yangutils.translator.exception.TranslatorException;
import org.onosproject.yangutils.translator.tojava.JavaQualifiedTypeInfo;
import org.onosproject.yangutils.translator.tojava.utils.AttributesJavaDataType;

/**
 * Represents java information corresponding to the YANG type.
 *
 * @param <T> generic parameter for YANG java type
 */
public class YangJavaType<T>
        extends YangType<T>
        implements JavaQualifiedTypeResolver {

    private JavaQualifiedTypeInfo javaQualifiedAccess;

    /**
     * Create a YANG leaf object with java qualified access details.
     */
    public YangJavaType() {
        super();
        setJavaQualifiedInfo(new JavaQualifiedTypeInfo());
    }

    @Override
    public void updateJavaQualifiedInfo() {
        JavaQualifiedTypeInfo importInfo = getJavaQualifiedInfo();

        /*
         * Type is added as an attribute in the class.
         */
        String className = AttributesJavaDataType.getJavaImportClass(this, false);
        if (className != null) {
            /*
             * Corresponding to the attribute type a class needs to be imported,
             * since it can be a derived type or a usage of wrapper classes.
             */
            importInfo.setClassInfo(className);
            String classPkg = AttributesJavaDataType.getJavaImportPackage(this,
                    false, className);
            if (classPkg == null) {
                throw new TranslatorException("import package cannot be null when the class is used");
            }
            importInfo.setPkgInfo(classPkg);
        } else {
            /*
             * The attribute does not need a class to be imported, for example
             * built in java types.
             */
            String dataTypeName = AttributesJavaDataType.getJavaDataType(this);
            if (dataTypeName == null) {
                throw new TranslatorException("not supported data type");
            }
            importInfo.setClassInfo(dataTypeName);
        }
        setJavaQualifiedInfo(importInfo);
    }

    @Override
    public JavaQualifiedTypeInfo getJavaQualifiedInfo() {
        return javaQualifiedAccess;
    }

    @Override
    public void setJavaQualifiedInfo(JavaQualifiedTypeInfo typeInfo) {
        javaQualifiedAccess = typeInfo;
    }
}


text:
file(REMOVE_RECURSE
  "CMakeFiles/RemoveDuplicatesFromSortedArrayII.dir/main.cpp.o"
  "RemoveDuplicatesFromSortedArrayII.pdb"
  "RemoveDuplicatesFromSortedArrayII"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/RemoveDuplicatesFromSortedArrayII.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()


text:
#include "container_tests.hpp"
#include <boost/static_assert.hpp>

std::map<int, int> const build_map()
{
    typedef std::map<int, int> int_map;
    typedef std::vector<int> int_vector;

    int_map result;
    int_vector const data = build_vector();
    int_vector::const_iterator it = data.begin();
    int_vector::const_iterator const end = data.end();
    for (; it != end; ++it) {
      int const value = *it;
      result[value] = 100 * value;
    }
    return result;
}

std::vector<int> const init_vector()
{
    typedef std::vector<int> int_vector;
    int const data[] = { -4, -3, -2, -1, 0 };
    int_vector::size_type const data_size = sizeof(data) / sizeof(data[0]);
    return int_vector(data, data + data_size);
}

std::vector<int> const build_vector()
{
    typedef std::vector<int> int_vector;
    static int_vector data = init_vector();
    int_vector::size_type const size = data.size();
    int_vector::iterator it = data.begin();
    int_vector::iterator const end = data.end();
    for (; it != end; ++it)
        *it += size;
    return data;
}

int
main()
{
    BOOST_STATIC_ASSERT((phx::stl::has_mapped_type<std::map<int, int> >::value));
    BOOST_STATIC_ASSERT((phx::stl::has_key_type<std::map<int, int> >::value));

    std::map<int, int> const data = build_map();
    test_map_insert(data);
    test_key_comp(data);
    test_max_size(data);
    test_rbegin(data);
    test_rend(data);
    test_size(data);
    test_value_comp(data);
    return boost::report_errors();
}


text:
namespace cor
{
    namespace mruby_interface
    {

          void BasicBind_bind_func_0(mruby_interface::MrubyState& mrb);
          void BasicBind_bind_func_1(mruby_interface::MrubyState& mrb);
          void BasicBind_bind_func_2(mruby_interface::MrubyState& mrb);
          void BasicBind_bind_func_3(mruby_interface::MrubyState& mrb);
          void BasicBind_bind_func_4(mruby_interface::MrubyState& mrb);
          void BasicBind_bind_func_5(mruby_interface::MrubyState& mrb);
          void BasicBind_bind_func_6(mruby_interface::MrubyState& mrb);
          void BasicBind_bind_func_7(mruby_interface::MrubyState& mrb);
          void BasicBind_bind_func_8(mruby_interface::MrubyState& mrb);
          void BasicBind_bind_func_9(mruby_interface::MrubyState& mrb);
          void BasicBind_bind_func_10(mruby_interface::MrubyState& mrb);
          void BasicBind_bind_func_11(mruby_interface::MrubyState& mrb);
          void BasicBind_bind_func_12(mruby_interface::MrubyState& mrb);
          void BasicBind_bind_func_13(mruby_interface::MrubyState& mrb);

    }
}


text:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.function.Predicate;

class NumbersOperationsAfter {
    public static void main(String[] args) {
        List<Integer> userNumbers = getNumbersFromUser();
        int positiveNumbersSum = getSum(userNumbers, x -> x >= 0);
        int negativeNumbersSum = getSum(userNumbers, x -> x < 0);
        printResults(positiveNumbersSum, negativeNumbersSum);
    }

    private static int getSum(List<Integer> numbers, Predicate<Integer> predicate) {
        return numbers.stream()
                .filter(predicate)
                .mapToInt(Integer::intValue)
                .sum();
    }

    private static void printResults(int positiveNumbersSum, int negativeNumbersSum) {
        System.out.println("Suma wprowadzonych liczb dodatnich: " + positiveNumbersSum);
        System.out.println("Suma wprowadzonych liczb ujemnych: " + negativeNumbersSum);
    }

    private static List<Integer> getNumbersFromUser() {
        Scanner scanner = new Scanner(System.in);
        List<Integer> userNumbers = new ArrayList<>();
        System.out.println("Ile liczb wczytać?");
        int numberOfNumbers = scanner.nextInt();
        for (int i = 0; i < numberOfNumbers; i++) {
            System.out.println("Podaj kolejną liczbę:");
            userNumbers.add(scanner.nextInt());
        }
        return userNumbers;
    }
}


text:
class GameAwardPlayer < ApplicationRecord
  belongs_to :game_round , required: true
  belongs_to :game_player, required: true
  belongs_to :game_award, required: true

  delegate :nickname, :avatar, to: :game_player
end


text:
class t_ppf_V;
class t_ppf_WL;
class t_ppf_WR;
class t_ppf_W;
class t_ppf_WMBL;
class t_ppf_WMBR;
class t_ppf_WMB;
class t_ppf_W_mhi;
class t_ppf_V_mhe;

class t_spf_array; // For determining scaling factors for each nucleotide.
class t_seq_man; // Sequence manager to interface with sequence data.
class t_frag_aln_enum_array;
class t_ppf_cli;
class t_ppf_loops;

// http://www.cprogramming.com/tutorial/floating_point/understanding_floating_point_representation.html
#define MAX_ARRAY_VALUE_LIMIT (pow(10.0, 280)) // This max limit is the limit of rescaling, when values reach this limit, a rescaling is needed to avoid overflow.
#define MIN_ARRAY_VALUE_LIMIT (pow(10.0, -280)) // This min limit is the limit of rescaling, when values reach this limit, a rescaling is needed to avoid overflow.
#define DEFAULT_PER_NUCLEOTIDE_RESCALE_INCREMENT (1.2) // Rescaling factor of each nucleotide.

class t_ppf_scale
{
	// Those should be inaccessible to other classes.
public:
	t_seq_man* seq_man;
	t_ppf_cli* ppf_cli;
	t_ppf_loops* ppf_loops;

	//double rescale_factor; // Initial rescale factor.
	double rescaling_increment_factor_per_nucleotide;

	double* seq1_scales; // Scaling factors of each nucleotide in 1st sequence.
	double* seq2_scales; // Scaling factors of each nucleotide in 2nd sequence.

	t_ppf_scale(t_ppf_loops* ppf_loops);
	t_ppf_scale(t_ppf_loops* ppf_loops, double init_rescale_factor);

	// Calculate scaling factor for each nucleotide using spf interface.
	void scaling_factor_by_nuc();

	// Rescale check function, calls each array to rescale if going out of precision for
	// one of the arrays.
	bool check_pp_ppf_array_rescale(int i, int j, int k, int l);
	bool check_pp_ppf_external_array_rescale(int i, int j, int k, int l);

	bool check_back_frag_array_rescale(int i, int j, int k, int l,
								t_frag_aln_enum_array* back_frag_array);

	// Read scaler values by nucleotide index and
	// i1 is nucleotide index of sequence 1 and i2 is ...
	double get_scale_value(int i1, int i2);

	double get_partial_scale_factor(int s1, int e1, int s2, int e2);
	double get_log_partial_scale_factor(int s1, int e1, int s2, int e2);

	double cumulative_rescale_external_factor(int i, int j, int k, int l);

	// Following function returns log value of an array value, which is calculated in
	// linear space. Since calculated in linear space, array value contains a partial scaling factor.
	// This function is good for dumping values of arrays.
	double get_unscaled_log_value_by_indices(int i, int j, int k, int l, double scaled_value);

	void copy_scales_to_spf_by_id(int id, double* spf_scales);

	double cumulative_rescale_factor(int i, int j, int k, int l);
	double cumulative_rescale_factor_exc_ik(int i, int j, int k, int l);
	void increment_scales_by_rescale(bool up_scale);

	~t_ppf_scale();
};

#endif // _PPF_SCALE_


text:
BUILD_DIR=${SRC_DIR}
EXECUTABLES="src/lua src/luac"

NACLPORTS_CPPFLAGS+=" -Dmain=nacl_main"
NACLPORTS_LDFLAGS+=" ${NACL_CLI_MAIN_LIB}"

if [ "${NACL_LIBC}" = "glibc" ]; then
  PLAT=nacl-glibc
else
  PLAT=nacl-newlib
fi

BuildStep() {
  LogExecute make PLAT=${PLAT} clean
  set -x
  make EXTRA_LIBS="${NACLPORTS_LDFLAGS}" EXTRA_CFLAGS="${NACLPORTS_CPPFLAGS}" \
       AR="${NACLAR} rcu" RANLIB="${NACLRANLIB}" \
       CC="${NACLCC}" PLAT=${PLAT} INSTALL_TOP="${DESTDIR}" -j${OS_JOBS}
  set +x
}

InstallStep() {
  LogExecute make "CC=${NACLCC}" "PLAT=generic" \
                  "INSTALL_TOP=${DESTDIR}/${PREFIX}" install
  ChangeDir src
  if [ "${NACL_ARCH}" = pnacl ]; then
    # Just do the x86-64 version for now.
    TranslateAndWriteLauncherScript lua x86-64 lua.x86-64.nexe lua.sh
    TranslateAndWriteLauncherScript luac x86-64 luac.x86-64.nexe luac.sh
  fi
}

PublishStep() {
  PublishByArchForDevEnv
}


text:
@interface JKReactiveSearchThrottleViewController : UIViewController

@end


text:
package com.guideapp.backend.util;

public final class StringUtil {
    private StringUtil() {
    }

    public static String trim(String s) {
        if (s == null) {
            return "";
        }

        return s.trim();
    }
}


text:
'use strict';
/*eslint-env node */
/*eslint-disable */

// Based on
// https://github.com/martinmicunda/employee-scheduling-ui/blob/master/gulpfile.js

//=============================================
//            PLUGIN REFERENCES
//=============================================
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
var karma = require('karma').server;
var path = require('path');
var babel = require("gulp-babel");
var runSequence = require('run-sequence');
var exec = require('child_process').exec;
var argv = require('minimist')(process.argv.slice(2));
var COLORS = require('ansi-colors');
var log = require('fancy-log');
//=============================================
//            DECLARE VARIABLES
//=============================================

/**
 * Declare variables that are use in gulpfile.js or angular app
 */
var WATCH =  !!argv.watch ? argv.watch : false;
var BROWSERS = 'Chrome';
var REPORTERS = 'mocha';

//=============================================
//            DECLARE PATHS
//=============================================

var paths = {
  /**
   * The 'gulpfile' file is where our run tasks are held.
   */
  gulpfile: 'gulpfile.js',

  /**
   * This is a collection of file patterns that refer to our app unit and e2e tests code.
   *
   * 'config'       contains karma and protractor config files
   * 'testReports'  contains unit and e2e test reports
   * 'unit'         contains all project unit test code
   * 'e2e'          contains all project e2e test code
   */
  test: {
    basePath: '/',
    config: {
      karma: 'karma.conf.js',
    },
    mock: '*.mock.js',
    unit: '*.test.js',
  },
};

//---------------------------------------------
//               TEST TASKS
//---------------------------------------------

/**
 * The 'test:unit' task to run karma unit tests
 */
gulp.task('test:unit', function(cb) {
  // run the karma test
  karma.start({
    configFile: path.join(__dirname, paths.test.config.karma),
    browsers: [BROWSERS],
    reporters: [REPORTERS],
    singleRun: !WATCH,
    autoWatch: WATCH
  }, function(code) {
    // make sure failed karma tests cause gulp to exit non-zero
    if (code === 1) {
      log(COLORS.red('Error: unit test failed '));
      return process.exit(1);
    }
    cb();
  });
});

gulp.task("bundleDirective", function () {
  return gulp.src("src/*-directive.js")
      .pipe(babel())
      .pipe(gulp.dest("dist"));
});

gulp.task("bundleModule", function () {
  return gulp.src("src/*-module.js")
      .pipe(babel())
      .pipe(gulp.dest("dist"));
});

gulp.task("bundleTemplate", function () {
  return gulp.src("src/*.html")
      .pipe(gulp.dest("dist"));
});

gulp.task('build:jspmconfig', function (cb) {
  exec("node ./node_modules/jspm/jspm.js config registries.github.timeouts.lookup 360", function(err, stdout, stderr) {
    log(stdout);
    log.error(stderr);
    cb(err);
  });
});

gulp.task('build:jspminstall', ['build:jspmconfig'], function (cb) {
  exec("node ./node_modules/jspm/jspm.js install", function(err, stdout, stderr) {
      log(stdout);
      log.error(stderr);
      cb(err);
  });
});

gulp.task('build:fixjspmconfig', function (cb) {
  exec("node ./node_modules/eslint/bin/eslint.js --config ./.eslintrc --fix ./config.js", function(err, stdout, stderr) {
      log(stdout);
      log.error(stderr);
      cb(err);
  });
});

gulp.task('build:jspm', function(cb){
  runSequence(
    ['build:jspminstall'],['build:fixjspmconfig'],
    cb
  );
})

gulp.task('install', function (cb) {
  exec("yarn", function(err, stdout, stderr) {
      log(stdout);
      log.error(stderr);
      cb(err);
  });
});

gulp.task("compile", function () {
    runSequence(['bundleDirective', 'bundleModule', 'bundleTemplate']);
});