text:
package org.apache.asterix.om.types.hierachy;

import java.io.DataOutput;
import java.io.IOException;
import java.util.Arrays;
import java.util.BitSet;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;

import org.apache.asterix.common.exceptions.ErrorCode;
import org.apache.asterix.common.exceptions.RuntimeDataException;
import org.apache.asterix.om.base.ADouble;
import org.apache.asterix.om.base.AFloat;
import org.apache.asterix.om.base.IAObject;
import org.apache.asterix.om.constants.AsterixConstantValue;
import org.apache.asterix.om.types.ATypeTag;
import org.apache.asterix.om.types.EnumDeserializer;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.data.std.primitive.DoublePointable;
import org.apache.hyracks.data.std.primitive.IntegerPointable;
import org.apache.hyracks.data.std.primitive.LongPointable;

public class ATypeHierarchy {

    private static final BitSet typePromotionHierachyMap = new BitSet(ATypeTag.TYPE_COUNT * ATypeTag.TYPE_COUNT);
    private static final BitSet typeDemotionHierachyMap = new BitSet(ATypeTag.TYPE_COUNT * ATypeTag.TYPE_COUNT);
    private static final Map<Integer, ITypeConvertComputer> promoteComputerMap = new HashMap<>();
    private static final Map<Integer, Pair<ITypeConvertComputer, ITypeConvertComputer>> demoteComputerMap =
            new HashMap<>();
    private static Map<ATypeTag, Domain> hierarchyDomains = new EnumMap<>(ATypeTag.class);

    // allow type promotion or demotion to the type itself
    static {
        for (int i = 0; i < ATypeTag.TYPE_COUNT; i++) {
            typePromotionHierachyMap.set(i * ATypeTag.TYPE_COUNT + i);
            typeDemotionHierachyMap.set(i * ATypeTag.TYPE_COUNT + i);
        }
    }

    // add default type promotion rules
    static {
        // Promotion (widening): TINYINT -> SMALLINT -> INTEGER -> BIGINT -> FLOAT -> DOUBLE
        // No precision and range loss
        addPromotionRule(ATypeTag.TINYINT, ATypeTag.SMALLINT, IntegerToInt16TypeConvertComputer.getInstance(true));
        addPromotionRule(ATypeTag.TINYINT, ATypeTag.INTEGER, IntegerToInt32TypeConvertComputer.getInstance(true));
        addPromotionRule(ATypeTag.TINYINT, ATypeTag.BIGINT, IntegerToInt64TypeConvertComputer.getInstance());
        addPromotionRule(ATypeTag.SMALLINT, ATypeTag.INTEGER, IntegerToInt32TypeConvertComputer.getInstance(true));
        addPromotionRule(ATypeTag.SMALLINT, ATypeTag.BIGINT, IntegerToInt64TypeConvertComputer.getInstance());
        addPromotionRule(ATypeTag.INTEGER, ATypeTag.BIGINT, IntegerToInt64TypeConvertComputer.getInstance());
        addPromotionRule(ATypeTag.TINYINT, ATypeTag.DOUBLE, IntegerToDoubleTypeConvertComputer.getInstance());
        addPromotionRule(ATypeTag.SMALLINT, ATypeTag.DOUBLE, IntegerToDoubleTypeConvertComputer.getInstance());
        addPromotionRule(ATypeTag.INTEGER, ATypeTag.DOUBLE, IntegerToDoubleTypeConvertComputer.getInstance());
        addPromotionRule(ATypeTag.BIGINT, ATypeTag.DOUBLE, IntegerToDoubleTypeConvertComputer.getInstance());
        addPromotionRule(ATypeTag.FLOAT, ATypeTag.DOUBLE, FloatToDoubleTypeConvertComputer.getInstance());
        addPromotionRule(ATypeTag.TINYINT, ATypeTag.FLOAT, IntegerToFloatTypeConvertComputer.getInstance());
        addPromotionRule(ATypeTag.SMALLINT, ATypeTag.FLOAT, IntegerToFloatTypeConvertComputer.getInstance());
        addPromotionRule(ATypeTag.INTEGER, ATypeTag.FLOAT, IntegerToFloatTypeConvertComputer.getInstance());
        addPromotionRule(ATypeTag.BIGINT, ATypeTag.FLOAT, IntegerToFloatTypeConvertComputer.getInstance());
    }

    static {
        // Demotion (narrowing): DOUBLE -> FLOAT -> BIGINT -> INTEGER -> SMALLINT -> TINYINT
        // Possible precision loss (e.g., FLOAT to INT)
        // 'strict' mode produces an exception if source value is greater than target.MAX or less than target.MIN
        // 'lax' mode does not fail. it returns target.MAX/target.MIN if source value is out of range
        addDemotionRule(ATypeTag.SMALLINT, ATypeTag.TINYINT, IntegerToInt8TypeConvertComputer.getInstance(true),
                IntegerToInt8TypeConvertComputer.getInstance(false));
        addDemotionRule(ATypeTag.INTEGER, ATypeTag.TINYINT, IntegerToInt8TypeConvertComputer.getInstance(true),
                IntegerToInt8TypeConvertComputer.getInstance(false));
        addDemotionRule(ATypeTag.BIGINT, ATypeTag.TINYINT, IntegerToInt8TypeConvertComputer.getInstance(true),
                IntegerToInt8TypeConvertComputer.getInstance(false));
        addDemotionRule(ATypeTag.INTEGER, ATypeTag.SMALLINT, IntegerToInt16TypeConvertComputer.getInstance(true),
                IntegerToInt16TypeConvertComputer.getInstance(false));
        addDemotionRule(ATypeTag.BIGINT, ATypeTag.SMALLINT, IntegerToInt16TypeConvertComputer.getInstance(true),
                IntegerToInt16TypeConvertComputer.getInstance(false));
        addDemotionRule(ATypeTag.BIGINT, ATypeTag.INTEGER, IntegerToInt32TypeConvertComputer.getInstance(true),
                IntegerToInt32TypeConvertComputer.getInstance(false));
        addDemotionRule(ATypeTag.FLOAT, ATypeTag.TINYINT, FloatToInt8TypeConvertComputer.getInstance(true),
                FloatToInt8TypeConvertComputer.getInstance(false));
        addDemotionRule(ATypeTag.FLOAT, ATypeTag.SMALLINT, FloatToInt16TypeConvertComputer.getInstance(true),
                FloatToInt16TypeConvertComputer.getInstance(false));
        addDemotionRule(ATypeTag.FLOAT, ATypeTag.INTEGER, FloatToInt32TypeConvertComputer.getInstance(true),
                FloatToInt32TypeConvertComputer.getInstance(false));
        addDemotionRule(ATypeTag.FLOAT, ATypeTag.BIGINT, FloatToInt64TypeConvertComputer.getInstance(true),
                FloatToInt64TypeConvertComputer.getInstance(false));
        addDemotionRule(ATypeTag.DOUBLE, ATypeTag.TINYINT, DoubleToInt8TypeConvertComputer.getInstance(true),
                DoubleToInt8TypeConvertComputer.getInstance(false));
        addDemotionRule(ATypeTag.DOUBLE, ATypeTag.SMALLINT, DoubleToInt16TypeConvertComputer.getInstance(true),
                DoubleToInt16TypeConvertComputer.getInstance(false));
        addDemotionRule(ATypeTag.DOUBLE, ATypeTag.INTEGER, DoubleToInt32TypeConvertComputer.getInstance(true),
                DoubleToInt32TypeConvertComputer.getInstance(false));
        addDemotionRule(ATypeTag.DOUBLE, ATypeTag.BIGINT, DoubleToInt64TypeConvertComputer.getInstance(true),
                DoubleToInt64TypeConvertComputer.getInstance(false));
        addDemotionRule(ATypeTag.DOUBLE, ATypeTag.FLOAT, DoubleToFloatTypeConvertComputer.getInstance(true),
                DoubleToFloatTypeConvertComputer.getInstance(false));
    }

    static {
        hierarchyDomains.put(ATypeTag.POINT, Domain.SPATIAL);
        hierarchyDomains.put(ATypeTag.LINE, Domain.SPATIAL);
        hierarchyDomains.put(ATypeTag.CIRCLE, Domain.SPATIAL);
        hierarchyDomains.put(ATypeTag.POLYGON, Domain.SPATIAL);
        hierarchyDomains.put(ATypeTag.RECTANGLE, Domain.SPATIAL);
        hierarchyDomains.put(ATypeTag.TINYINT, Domain.NUMERIC);
        hierarchyDomains.put(ATypeTag.SMALLINT, Domain.NUMERIC);
        hierarchyDomains.put(ATypeTag.INTEGER, Domain.NUMERIC);
        hierarchyDomains.put(ATypeTag.BIGINT, Domain.NUMERIC);
        hierarchyDomains.put(ATypeTag.FLOAT, Domain.NUMERIC);
        hierarchyDomains.put(ATypeTag.DOUBLE, Domain.NUMERIC);
        hierarchyDomains.put(ATypeTag.ARRAY, Domain.LIST);
        hierarchyDomains.put(ATypeTag.MULTISET, Domain.LIST);
    }

    public static Domain getTypeDomain(ATypeTag tag) {
        return hierarchyDomains.get(tag);
    }

    public static boolean isSameTypeDomain(ATypeTag tag1, ATypeTag tag2, boolean useListDomain) {
        Domain tagHierarchy1 = hierarchyDomains.get(tag1);
        Domain tagHierarchy2 = hierarchyDomains.get(tag2);
        if (tagHierarchy1 == null || tagHierarchy2 == null) {
            return false;
        }
        if (useListDomain && tagHierarchy1 == Domain.LIST && tagHierarchy2 == Domain.LIST) {
            return true;
        }
        return tagHierarchy1.equals(tagHierarchy2) && !useListDomain;
    }

    private static void addPromotionRule(ATypeTag type1, ATypeTag type2, ITypeConvertComputer promoteComputer) {
        int index = type1.ordinal() * ATypeTag.TYPE_COUNT + type2.ordinal();
        typePromotionHierachyMap.set(index);
        promoteComputerMap.put(index, promoteComputer);
    }

    private static void addDemotionRule(ATypeTag type1, ATypeTag type2, ITypeConvertComputer demoteStrictComputer,
            ITypeConvertComputer demoteLenientComputer) {
        int index = type1.ordinal() * ATypeTag.TYPE_COUNT + type2.ordinal();
        typeDemotionHierachyMap.set(index);
        demoteComputerMap.put(index, Pair.of(demoteStrictComputer, demoteLenientComputer));
    }

    public static ITypeConvertComputer getTypePromoteComputer(ATypeTag type1, ATypeTag type2) {
        if (canPromote(type1, type2)) {
            return promoteComputerMap.get(type1.ordinal() * ATypeTag.TYPE_COUNT + type2.ordinal());
        }
        return null;
    }

    public static ITypeConvertComputer getTypeDemoteComputer(ATypeTag type1, ATypeTag type2, boolean strict) {
        if (canDemote(type1, type2)) {
            Pair<ITypeConvertComputer, ITypeConvertComputer> pair =
                    demoteComputerMap.get(type1.ordinal() * ATypeTag.TYPE_COUNT + type2.ordinal());
            return strict ? pair.getLeft() : pair.getRight();
        }
        return null;
    }

    public static boolean canPromote(ATypeTag type1, ATypeTag type2) {
        return typePromotionHierachyMap.get(type1.ordinal() * ATypeTag.TYPE_COUNT + type2.ordinal());
    }

    public static boolean canDemote(ATypeTag type1, ATypeTag type2) {
        return typeDemotionHierachyMap.get(type1.ordinal() * ATypeTag.TYPE_COUNT + type2.ordinal());
    }

    public static boolean isCompatible(ATypeTag type1, ATypeTag type2) {
        // The type tag ANY is only used at compile time to represent all possibilities.
        // There is no runtime data model instance that has a type tag ANY.
        // If we encounter type tag ANY, we should let it pass at compile time and defer erring to the runtime.
        // Therefore, "type1 == ATypeTag.ANY || type2 == ATypeTag.ANY" works for both compiler and runtime.
        return type1 == ATypeTag.ANY || type2 == ATypeTag.ANY || canPromote(type1, type2) || canPromote(type2, type1);
    }

    // Get an AsterixConstantValue from a source Object
    public static AsterixConstantValue getAsterixConstantValueFromNumericTypeObject(IAObject sourceObject,
            ATypeTag targetTypeTag) throws HyracksDataException {
        return getAsterixConstantValueFromNumericTypeObject(sourceObject, targetTypeTag, false,
                TypeCastingMathFunctionType.NONE);
    }

    // Get an AsterixConstantValue from a source Object
    public static AsterixConstantValue getAsterixConstantValueFromNumericTypeObject(IAObject sourceObject,
            ATypeTag targetTypeTag, boolean strictDemote, TypeCastingMathFunctionType mathFunction)
            throws HyracksDataException {
        ATypeTag sourceTypeTag = sourceObject.getType().getTypeTag();
        if (sourceTypeTag == targetTypeTag) {
            return new AsterixConstantValue(sourceObject);
        }

        // if the constant type and target type does not match, we do a type conversion
        ITypeConvertComputer convertComputer = null;
        if (canPromote(sourceTypeTag, targetTypeTag)) {
            convertComputer = ATypeHierarchy.getTypePromoteComputer(sourceTypeTag, targetTypeTag);
        } else if (canDemote(sourceTypeTag, targetTypeTag)) {
            convertComputer = ATypeHierarchy.getTypeDemoteComputer(sourceTypeTag, targetTypeTag, strictDemote);
        }
        if (convertComputer == null) {
            return null;
        }

        IAObject targetObject = convertComputer.convertType(sourceObject, mathFunction);
        return new AsterixConstantValue(targetObject);
    }

    // Type Casting from source Object to an Object with Target type
    public static IAObject convertNumericTypeObject(IAObject sourceObject, ATypeTag targetTypeTag)
            throws HyracksDataException {
        return convertNumericTypeObject(sourceObject, targetTypeTag, false, TypeCastingMathFunctionType.NONE);
    }

    // Type Casting from source Object to an Object with Target type
    public static IAObject convertNumericTypeObject(IAObject sourceObject, ATypeTag targetTypeTag, boolean strictDemote,
            TypeCastingMathFunctionType mathFunction) throws HyracksDataException {
        ATypeTag sourceTypeTag = sourceObject.getType().getTypeTag();
        if (sourceTypeTag == targetTypeTag) {
            return sourceObject;
        }

        ITypeConvertComputer convertComputer = null;
        if (canPromote(sourceTypeTag, targetTypeTag)) {
            convertComputer = ATypeHierarchy.getTypePromoteComputer(sourceTypeTag, targetTypeTag);
        } else if (canDemote(sourceTypeTag, targetTypeTag)) {
            convertComputer = ATypeHierarchy.getTypeDemoteComputer(sourceTypeTag, targetTypeTag, strictDemote);
        }
        if (convertComputer == null) {
            throw new RuntimeDataException(ErrorCode.TYPE_CONVERT, sourceTypeTag, targetTypeTag);
        }

        return convertComputer.convertType(sourceObject, mathFunction);
    }

    // convert a numeric value in a byte array to the target type value
    public static void convertNumericTypeByteArray(byte[] sourceByteArray, int s1, int l1, ATypeTag targetTypeTag,
            DataOutput out) throws IOException {
        convertNumericTypeByteArray(sourceByteArray, s1, l1, targetTypeTag, out, false);
    }

    // convert a numeric value in a byte array to the target type value
    public static void convertNumericTypeByteArray(byte[] sourceByteArray, int s1, int l1, ATypeTag targetTypeTag,
            DataOutput out, boolean strictDemote) throws IOException {
        ATypeTag sourceTypeTag = EnumDeserializer.ATYPETAGDESERIALIZER.deserialize(sourceByteArray[s1]);

        if (sourceTypeTag != targetTypeTag) {
            // source tag can be promoted to target tag (e.g. tag1: SMALLINT, tag2: INTEGER)
            if (canPromote(sourceTypeTag, targetTypeTag)) {
                ITypeConvertComputer convertComputer =
                        ATypeHierarchy.getTypePromoteComputer(sourceTypeTag, targetTypeTag);
                convertComputer.convertType(sourceByteArray, s1 + 1, l1 - 1, out);
                // source tag can be demoted to target tag
            } else if (canDemote(sourceTypeTag, targetTypeTag)) {
                ITypeConvertComputer convertComputer =
                        ATypeHierarchy.getTypeDemoteComputer(sourceTypeTag, targetTypeTag, strictDemote);
                convertComputer.convertType(sourceByteArray, s1 + 1, l1 - 1, out);
            } else {
                throw new RuntimeDataException(ErrorCode.TYPE_CONVERT, sourceTypeTag, targetTypeTag);
            }
        }
    }

    // Get an INT value from numeric types array. We assume the first byte contains the type tag.
    public static int getIntegerValue(String name, int argIndex, byte[] bytes, int offset) throws HyracksDataException {
        return getIntegerValue(name, argIndex, bytes, offset, false);
    }

    // Get an INT value from numeric types array. We assume the first byte contains the type tag.
    public static int getIntegerValue(String name, int argIndex, byte[] bytes, int offset, boolean strictDemote)
            throws HyracksDataException {
        return getIntegerValueWithDifferentTypeTagPosition(name, argIndex, bytes, offset + 1, offset, strictDemote);
    }

    // Get an INT value from numeric types array. We assume the specific location of a byte array contains the type tag.
    public static int getIntegerValueWithDifferentTypeTagPosition(String name, int argIndex, byte[] bytes, int offset,
            int typeTagPosition) throws HyracksDataException {
        return getIntegerValueWithDifferentTypeTagPosition(name, argIndex, bytes, offset, typeTagPosition, false);
    }

    // Get an INT value from numeric types array. We assume the specific location of a byte array contains the type tag.
    public static int getIntegerValueWithDifferentTypeTagPosition(String name, int argIndex, byte[] bytes, int offset,
            int typeTagPosition, boolean strictDemote) throws HyracksDataException {
        ATypeTag sourceTypeTag = ATypeTag.VALUE_TYPE_MAPPING[bytes[typeTagPosition]];
        if (sourceTypeTag == null) {
            throw new RuntimeDataException(ErrorCode.INVALID_FORMAT, name, argIndex);
        }
        switch (sourceTypeTag) {
            case INTEGER:
                return IntegerPointable.getInteger(bytes, offset);
            case TINYINT:
            case SMALLINT:
            case BIGINT:
                return (int) IntegerToInt32TypeConvertComputer.getInstance(strictDemote).convertIntegerType(bytes,
                        offset, sourceTypeTag, ATypeTag.INTEGER);
            case FLOAT:
                return FloatToInt32TypeConvertComputer.getInstance(strictDemote).convertType(bytes, offset);
            case DOUBLE:
                return DoubleToInt32TypeConvertComputer.getInstance(strictDemote).convertType(bytes, offset);
            default:
                throw new RuntimeDataException(ErrorCode.TYPE_MISMATCH_FUNCTION, name, argIndex,
                        Arrays.toString(new Object[] { ATypeTag.TINYINT, ATypeTag.SMALLINT, ATypeTag.INTEGER,
                                ATypeTag.BIGINT, ATypeTag.FLOAT, ATypeTag.DOUBLE }),
                        sourceTypeTag);
        }
    }

    // Get a LONG (bigint) value from numeric types array. We assume the first byte contains the type tag.
    public static long getLongValue(String name, int argIndex, byte[] bytes, int offset) throws HyracksDataException {
        return getLongValue(name, argIndex, bytes, offset, false);
    }

    // Get a LONG (bigint) value from numeric types array. We assume the first byte contains the type tag.
    public static long getLongValue(String name, int argIndex, byte[] bytes, int offset, boolean strictDemote)
            throws HyracksDataException {
        return getLongValueWithDifferentTypeTagPosition(name, argIndex, bytes, offset + 1, offset, strictDemote);
    }

    // Get a LONG (bigint) value from numeric types array. We assume the specific location of a byte array
    // contains the type tag.
    private static long getLongValueWithDifferentTypeTagPosition(String name, int argIndex, byte[] bytes, int offset,
            int typeTagPosition, boolean strictDemote) throws HyracksDataException {
        ATypeTag sourceTypeTag = ATypeTag.VALUE_TYPE_MAPPING[bytes[typeTagPosition]];
        if (sourceTypeTag == null) {
            throw new RuntimeDataException(ErrorCode.INVALID_FORMAT, name, argIndex);
        }
        switch (sourceTypeTag) {
            case BIGINT:
                return LongPointable.getLong(bytes, offset);
            case TINYINT:
            case SMALLINT:
            case INTEGER:
                return IntegerToInt64TypeConvertComputer.getInstance().convertIntegerType(bytes, offset, sourceTypeTag,
                        ATypeTag.BIGINT);
            case FLOAT:
                return FloatToInt64TypeConvertComputer.getInstance(strictDemote).convertType(bytes, offset);
            case DOUBLE:
                return DoubleToInt64TypeConvertComputer.getInstance(strictDemote).convertType(bytes, offset);
            default:
                throw new RuntimeDataException(ErrorCode.TYPE_MISMATCH_FUNCTION, name, argIndex,
                        Arrays.toString(new Object[] { ATypeTag.TINYINT, ATypeTag.SMALLINT, ATypeTag.INTEGER,
                                ATypeTag.BIGINT, ATypeTag.FLOAT, ATypeTag.DOUBLE }),
                        sourceTypeTag);
        }
    }

    // Get a DOUBLE value from numeric types array. We assume the first byte contains the type tag.
    public static double getDoubleValue(String name, int argIndex, byte[] bytes, int offset)
            throws HyracksDataException {
        return getDoubleValueWithDifferentTypeTagPosition(name, argIndex, bytes, offset + 1, offset);
    }

    // Get a DOUBLE value from numeric types array. We assume the specific location of a byte array contains the type tag.
    private static double getDoubleValueWithDifferentTypeTagPosition(String name, int argIndex, byte[] bytes,
            int offset, int typeTagPosition) throws HyracksDataException {
        ATypeTag sourceTypeTag = ATypeTag.VALUE_TYPE_MAPPING[bytes[typeTagPosition]];
        if (sourceTypeTag == null) {
            throw new RuntimeDataException(ErrorCode.INVALID_FORMAT, name, argIndex);
        }
        switch (sourceTypeTag) {
            case DOUBLE:
                return DoublePointable.getDouble(bytes, offset);
            case FLOAT:
                return FloatToDoubleTypeConvertComputer.getInstance().convertType(bytes, offset);
            case TINYINT:
            case SMALLINT:
            case INTEGER:
            case BIGINT:
                return IntegerToDoubleTypeConvertComputer.getInstance().convertType(bytes, offset, sourceTypeTag);
            default:
                throw new RuntimeDataException(ErrorCode.TYPE_MISMATCH_FUNCTION, name, argIndex,
                        Arrays.toString(new ATypeTag[] { ATypeTag.TINYINT, ATypeTag.SMALLINT, ATypeTag.INTEGER,
                                ATypeTag.BIGINT, ATypeTag.FLOAT, ATypeTag.DOUBLE }),
                        sourceTypeTag);
        }
    }

    /**
     * Applies certain math function (e.g., ceil or floor) to a double value and returns that value.
     */
    public static double applyMathFunctionToDoubleValue(IAObject sourceObject, TypeCastingMathFunctionType mathFunction)
            throws RuntimeDataException {
        switch (mathFunction) {
            case CEIL:
                return Math.ceil(((ADouble) sourceObject).getDoubleValue());
            case FLOOR:
                return Math.floor(((ADouble) sourceObject).getDoubleValue());
            default:
                return ((ADouble) sourceObject).getDoubleValue();
        }
    }

    /**
     * Applies certain math function (e.g., ceil or floor) to a float value and returns that value.
     */
    public static float applyMathFunctionToFloatValue(IAObject sourceObject, TypeCastingMathFunctionType mathFunction) {
        switch (mathFunction) {
            case CEIL:
                return (float) Math.ceil(((AFloat) sourceObject).getFloatValue());
            case FLOOR:
                return (float) Math.floor(((AFloat) sourceObject).getFloatValue());
            default:
                return ((AFloat) sourceObject).getFloatValue();
        }
    }

    public enum Domain {
        SPATIAL,
        NUMERIC,
        LIST,
        ANY
    }

    // Type-casting mathFunction that will be used to type-cast a FLOAT or a DOUBLE value into an INTEGER value.
    public enum TypeCastingMathFunctionType {
        CEIL,
        FLOOR,
        NONE
    }
}


text:
USE [DCustomer]
GO

/****** Object: Table [dbo].[Contact] Script Date: 5/18/2014 9:01:59 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

DROP TABLE IF EXISTS [dbo].[Contact]
GO

CREATE TABLE [dbo].[Contact] (
    [Id]         INT             IDENTITY (1, 1) NOT NULL,
    [FirstName]  NVARCHAR (25)   NOT NULL,
    [LastName]   NVARCHAR (30)   NOT NULL,
    [Address1]   NVARCHAR (40)   NULL,
    [Address2]   NVARCHAR (30)   NULL,
    [Notes]      NVARCHAR (150)  NULL,
    [ZipCode]    NVARCHAR (10)   NULL,
    [HomePhone]  NVARCHAR (10)   NULL,
    [WorkPhone]  NVARCHAR (10)   NULL,
    [CellPhone]  NVARCHAR (10)   NULL,
    [EMail]      NVARCHAR (4000) NULL,
    [CityId]     INT             NOT NULL,
    [Active]     BIT             NOT NULL,
    [ModifiedUtcDt] DATETIME        NOT NULL,
    [CreateUtcDt]   DATETIME        NOT NULL,
	CONSTRAINT [PK_Contact] PRIMARY KEY CLUSTERED (	[Id] ASC)
) ON [PRIMARY]

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Id', @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Contact', @level2type=N'COLUMN',@level2name=N'Id'
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'First Name', @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Contact', @level2type=N'COLUMN',@level2name=N'FirstName'
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Last Name', @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Contact', @level2type=N'COLUMN',@level2name=N'LastName'
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Address 1', @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Contact', @level2type=N'COLUMN',@level2name=N'Address1'
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Address 2', @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Contact', @level2type=N'COLUMN',@level2name=N'Address2'
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Notes', @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Contact', @level2type=N'COLUMN',@level2name=N'Notes'
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Zip Code', @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Contact', @level2type=N'COLUMN',@level2name=N'ZipCode'
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Home Phone', @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Contact', @level2type=N'COLUMN',@level2name=N'HomePhone'
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Work Phone', @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Contact', @level2type=N'COLUMN',@level2name=N'WorkPhone'
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Cell Phone', @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Contact', @level2type=N'COLUMN',@level2name=N'CellPhone'
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'E-mail', @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Contact', @level2type=N'COLUMN',@level2name=N'EMail'
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'City Id', @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Contact', @level2type=N'COLUMN',@level2name=N'CityId'
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Active', @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Contact', @level2type=N'COLUMN',@level2name=N'Active'
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Modified Date', @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Contact', @level2type=N'COLUMN',@level2name=N'ModifiedUtcDt'
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Create Date', @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Contact', @level2type=N'COLUMN',@level2name=N'CreateUtcDt'

redpajama_set_name: RedPajamaGithub


text:
import * as vscode from 'vscode';
export default class ProtocolCodeAction extends vscode.CodeAction {
    readonly data: unknown | undefined;
    constructor(title: string, data: unknown | undefined);
}


text:
=======
Credits
=======

Development Lead
----------------

* Alex Weeks <alex.weeks@rackspace.com>

Contributors
------------

None yet. Why not be the first?


text:
import os.path
import time

from wptserve.utils import isomorphic_encode

def main(request, response):
    name = request.GET.first(b"name")
    sleepTime = float(request.GET.first(b"sleep")) / 1E3
    numInitial = int(request.GET.first(b"numInitial"))

    path = os.path.join(os.path.dirname(isomorphic_encode(__file__)), name)
    body = open(path, u"rb").read()

    response.headers.set(b"Content-Type", b"image")
    response.headers.set(b"Content-Length", len(body))
    response.headers.set(b"Cache-control", b"no-cache, must-revalidate")
    response.write_status_headers()

    # Read from the beginning, |numInitial| bytes.
    first = body[:numInitial]
    response.writer.write_content(first)

    time.sleep(sleepTime)

    # Read the remainder after having slept.
    second = body[numInitial:]
    response.writer.write_content(second)


text:
const WebDriverTodoList = require('./WebDriverTodoList')
const browserstack = require('browserstack-local')

module.exports = class BrowserStackTodoList extends WebDriverTodoList {
  buildDriver(builder) {
    return builder
      .usingServer('http://hub-cloud.browserstack.com/wd/hub')
      .withCapabilities({
        'browserName': 'firefox',
        'browserstack.user': process.env.BROWSERSTACK_USER,
        'browserstack.key': process.env.BROWSERSTACK_KEY,
        'browserstack.local': 'true'
      })
  }

  async start() {
    this.browserstackLocal = new browserstack.Local()
    await new Promise((resolve, reject) => {
      this.browserstackLocal.start({ key: process.env.BROWSERSTACK_KEY }, () => {
        resolve()
      })
    })
    await super.start()
  }

  async stop() {
    await super.stop()
    await new Promise((resolve, reject) => {
      this.browserstackLocal.stop(() => {
        resolve()
      })
    })
  }
}


text:
package com.amazonaws.services.cloudfront.model;

import javax.annotation.Generated;

/**
 * <p>
 * This operation is not supported in this region.
 * </p>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UnsupportedOperationException extends com.amazonaws.services.cloudfront.model.AmazonCloudFrontException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new UnsupportedOperationException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public UnsupportedOperationException(String message) {
        super(message);
    }

}


text:
/**
 http://www.w3.org/TR/2000/REC-DOM-Level-2-Style-20001113/css.html#CSS-CSSRule

 interface CSSRule {

 // RuleType
 const unsigned short      UNKNOWN_RULE                   = 0;
 const unsigned short      STYLE_RULE                     = 1;
 const unsigned short      CHARSET_RULE                   = 2;
 const unsigned short      IMPORT_RULE                    = 3;
 const unsigned short      MEDIA_RULE                     = 4;
 const unsigned short      FONT_FACE_RULE                 = 5;
 const unsigned short      PAGE_RULE                      = 6;

 readonly attribute unsigned short   type;
 attribute DOMString        cssText;
 // raises(DOMException) on setting

 readonly attribute CSSStyleSheet    parentStyleSheet;
 readonly attribute CSSRule          parentRule;
 */
#import <Foundation/Foundation.h>

@class SVGKCSSStyleSheet;

typedef NS_ENUM(unsigned short, CSSRuleType)
{
	UNKNOWN_RULE                   = 0,
	STYLE_RULE                     = 1,
	CHARSET_RULE                   = 2,
	IMPORT_RULE                    = 3,
	MEDIA_RULE                     = 4,
	FONT_FACE_RULE                 = 5,
	PAGE_RULE                      = 6
};

@interface SVGKCSSRule : NSObject

@property(nonatomic) CSSRuleType type;
@property(nonatomic,copy) NSString* cssText;

@property(nonatomic,strong) SVGKCSSStyleSheet* parentStyleSheet;
@property(nonatomic,strong) SVGKCSSRule* parentRule;

@end


text:
package com.st.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.st.domain.salesforce.Profile;
import com.st.repository.ProfileRepository;

@RestController
public class ProfileController {

	@Autowired
	private ProfileRepository profileRepository;

	@RequestMapping(value = "/api/profiles", method = RequestMethod.GET)
	public List<Profile> findAllProfiles() {
		return profileRepository.findAll();
	}
}


text:
require 'middleman-core'

::Middleman::Extensions.register(:github_api) do
  require 'middleman-github_api/extension'
  ::Middleman::GithubApi::Extension
end


text:
Creates a kafka .deb file via [fpm](https://github.com/jordansissel/fpm/wiki).

### Usage

    ./build.py [OPTIONS]

    Options:

     REQUIRED [-r, --release] <kafka version>  create a deb named as this version

     REQUIRED [-l, --link] <kafka url> download/unpack source release (assumes a tgz)

     REQUIRED [-m, --maintainer] <package> package maintainer

     REQUIRED [-v, --vendor] <vendor> package vendor

     OPTIONAL [-p, --package-release] <package version>  package release version (default is 1)

     OPTIONAL [-s, --source-folder] <folder name>  name of unpacked source (default takes from downloaded file)

### Example

    ./build.py -r 0.7.2-incubating -l http://www.eu.apache.org/dist/incubator/kafka/kafka-0.7.2-incubating/kafka-0.7.2-incubating-src.tgz -m bobfisch@example.org -v Example


text:
require 'spec_helper'

describe "GraphQL::Relay::MongoRelationConnection" do
  def get_names(result)
    ships = result["data"]["federation"]["bases"]["edges"]
    ships.map { |e| e["node"]["name"] }
  end

  def get_residents(ship)
    ship["residents"]["edges"].map { |e| e["node"]["name"] }
  end

  def get_ships_residents(result)
    ships = result["data"]["federation"]["bases"]["edges"]
    Hash[ships.map { |e| [e["node"]["name"], get_residents(e["node"])] }]
  end

  def get_page_info(result)
    result["data"]["federation"]["bases"]["pageInfo"]
  end

  def get_first_cursor(result)
    result["data"]["federation"]["bases"]["edges"].first["cursor"]
  end

  def get_last_cursor(result)
    result["data"]["federation"]["bases"]["edges"].last["cursor"]
  end

  describe "results" do
    let(:query_string) {%|
      query getShips($first: Int, $after: String, $last: Int, $before: String,  $nameIncludes: String){
        federation {
          bases(first: $first, after: $after, last: $last, before: $before, nameIncludes: $nameIncludes) {
            ... basesConnection
          }
        }
      }

      fragment basesConnection on BasesConnectionWithTotalCount {
        totalCount,
        edges {
          cursor
          node {
            name
          }
        },
        pageInfo {
          hasNextPage
          hasPreviousPage
          startCursor
          endCursor
        }
      }
    |}

    it 'limits the result' do
      result = star_trek_query(query_string, { "first" => 2 })
      assert_equal(2, get_names(result).length)
      assert_equal(true, get_page_info(result)["hasNextPage"])
      assert_equal(false, get_page_info(result)["hasPreviousPage"])
      assert_equal("MQ", get_page_info(result)["startCursor"])
      assert_equal("Mg", get_page_info(result)["endCursor"])
      assert_equal("MQ", get_first_cursor(result))
      assert_equal("Mg", get_last_cursor(result))

      result = star_trek_query(query_string, { "first" => 3 })
      assert_equal(3, get_names(result).length)
      assert_equal(false, get_page_info(result)["hasNextPage"])
      assert_equal(false, get_page_info(result)["hasPreviousPage"])
      assert_equal("MQ", get_page_info(result)["startCursor"])
      assert_equal("Mw", get_page_info(result)["endCursor"])
      assert_equal("MQ", get_first_cursor(result))
      assert_equal("Mw", get_last_cursor(result))
    end

    it 'provides custom fields on the connection type' do
      result = star_trek_query(query_string, { "first" => 2 })
      assert_equal(
        StarTrek::Base.where(faction_id: 1).count,
        result["data"]["federation"]["bases"]["totalCount"]
      )
    end

    it "provides bidirectional_pagination by default" do
      result = star_trek_query(query_string, { "first" => 1 })
      last_cursor = get_last_cursor(result)

      result = star_trek_query(query_string, { "first" => 1, "after" => last_cursor })
      assert_equal true, get_page_info(result)["hasNextPage"]
      assert_equal true, get_page_info(result)["hasPreviousPage"]

      last_cursor = get_last_cursor(result)
      result =  star_trek_query(query_string, { "last" => 1, "before" => last_cursor })
      assert_equal true, get_page_info(result)["hasNextPage"]
      assert_equal false, get_page_info(result)["hasPreviousPage"]

      result = star_trek_query(query_string, { "first" => 100 })
      last_cursor = get_last_cursor(result)

      result = star_trek_query(query_string, { "last" => 1, "before" => last_cursor })
      assert_equal true, get_page_info(result)["hasNextPage"]
      assert_equal true, get_page_info(result)["hasPreviousPage"]
    end

    it 'slices the result' do
      result = star_trek_query(query_string, { "first" => 2 })
      assert_equal(["Deep Space Station K-7", "Regula I"], get_names(result))

      # After the last result, find the next 2:
      last_cursor = get_last_cursor(result)

      result = star_trek_query(query_string, { "after" => last_cursor, "first" => 2 })
      assert_equal(["Deep Space Nine"], get_names(result))

      last_cursor = get_last_cursor(result)

      result = star_trek_query(query_string, { "before" => last_cursor, "last" => 1 })
      assert_equal(["Regula I"], get_names(result))

      result = star_trek_query(query_string, { "before" => last_cursor, "last" => 2 })
      assert_equal(["Deep Space Station K-7", "Regula I"], get_names(result))

      result = star_trek_query(query_string, { "before" => last_cursor, "last" => 10 })
      assert_equal(["Deep Space Station K-7", "Regula I"], get_names(result))

      result = star_trek_query(query_string, { "last" => 2 })
      assert_equal(["Regula I", "Deep Space Nine"], get_names(result))

      result = star_trek_query(query_string, { "last" => 10 })
      assert_equal(["Deep Space Station K-7", "Regula I", "Deep Space Nine"], get_names(result))
      assert_equal(false, result["data"]["federation"]["bases"]["pageInfo"]["hasNextPage"])
      assert_equal(false, result["data"]["federation"]["bases"]["pageInfo"]["hasPreviousPage"])
    end

    it 'works with before and after specified together' do
      result = star_trek_query(query_string, { "first" => 2 })
      assert_equal(["Deep Space Station K-7", "Regula I"], get_names(result))

      first_cursor = get_last_cursor(result)

      # There is no records between before and after if they point to the same cursor
      result = star_trek_query(query_string, { "before" => first_cursor, "after" => first_cursor, "last" => 2 })
      assert_equal([], get_names(result))

      result = star_trek_query(query_string, { "after" => first_cursor, "first" => 2 })
      assert_equal(["Deep Space Nine"], get_names(result))

      second_cursor = get_last_cursor(result)

      result = star_trek_query(query_string, { "after" => first_cursor, "before" => second_cursor, "first" => 3 })
      assert_equal([], get_names(result)) # TODO: test fails. fixme
    end

    it 'handles cursors above the bounds of the array' do
      overreaching_cursor = Base64.strict_encode64("100")
      result = star_trek_query(query_string, { "after" => overreaching_cursor, "first" => 2 })
      assert_equal([], get_names(result))
    end

    it 'handles cursors below the bounds of the array' do
      underreaching_cursor = Base64.strict_encode64("1")
      result = star_trek_query(query_string, { "before" => underreaching_cursor, "first" => 2 })
      assert_equal([], get_names(result))
    end

    it 'handles grouped connections with only last argument' do
      grouped_conn_query = <<-GRAPHQL
      query {
        newestBasesGroupedByFaction(last: 2) {
          edges {
            node {
              name
            }
          }
        }
      }
      GRAPHQL

      result = star_trek_query(grouped_conn_query)
      names = result['data']['newestBasesGroupedByFaction']['edges'].map { |edge| edge['node']['name'] }
      assert_equal(['Ganalda Space Station', 'Deep Space Nine'], names)
    end

    it "applies custom arguments" do
      result = star_trek_query(query_string, { "first" => 1, "nameIncludes" => "eep" })
      assert_equal(["Deep Space Station K-7"], get_names(result))

      after = get_last_cursor(result)

      result = star_trek_query(query_string, { "first" => 2, "nameIncludes" => "eep", "after" => after  })
      assert_equal(["Deep Space Nine"], get_names(result))
      before = get_last_cursor(result)

      result = star_trek_query(query_string, { "last" => 1, "nameIncludes" => "eep", "before" => before })
      assert_equal(["Deep Space Station K-7"], get_names(result))
    end

    it 'works without first/last/after/before' do
      result = star_trek_query(query_string)

      assert_equal(3, result["data"]["federation"]["bases"]["edges"].length)
    end

    describe "applying max_page_size" do
      let(:query_string) {%|
        query getBases($first: Int, $after: String, $last: Int, $before: String){
          federation {
            bases: basesWithMaxLimitRelation(first: $first, after: $after, last: $last, before: $before) {
              ... basesConnection
            }
          }
        }

        fragment basesConnection on BaseConnection {
          edges {
            cursor
            node {
              name
            }
          },
          pageInfo {
            hasNextPage
            hasPreviousPage
            startCursor
            endCursor
          }
        }
      |}

      it "applies to queries by `first`" do
        result = star_trek_query(query_string, { "first" => 100 })
        assert_equal(2, result["data"]["federation"]["bases"]["edges"].size)
        assert_equal(true, result["data"]["federation"]["bases"]["pageInfo"]["hasNextPage"])

        # Max page size is applied _without_ `first`, also
        result = star_trek_query(query_string)
        assert_equal(2, result["data"]["federation"]["bases"]["edges"].size)
        assert_equal(true, result["data"]["federation"]["bases"]["pageInfo"]["hasNextPage"], "hasNextPage is true when first is not specified")
      end

      it "applies to queries by `last`" do
        second_to_last_two_names = ["Firebase P'ok", "Ganalda Space Station"]
        first_and_second_names = ["Deep Space Station K-7", "Regula I"]

        last_cursor = "Ng=="
        result = star_trek_query(query_string, { "last" => 100, "before" => last_cursor })
        assert_equal(second_to_last_two_names, get_names(result))
        assert_equal(true, result["data"]["federation"]["bases"]["pageInfo"]["hasPreviousPage"])

        result = star_trek_query(query_string, { "before" => last_cursor })
        assert_equal(first_and_second_names, get_names(result))
        assert_equal(false, result["data"]["federation"]["bases"]["pageInfo"]["hasPreviousPage"], "hasPreviousPage is false when last is not specified")

        third_cursor = "Mw"
        result = star_trek_query(query_string, { "last" => 100, "before" => third_cursor })
        assert_equal(first_and_second_names, get_names(result))

        result = star_trek_query(query_string, { "before" => third_cursor })
        assert_equal(first_and_second_names, get_names(result))
      end
    end

    describe "applying default_max_page_size" do
      let(:query_string) {%|
        query getBases($first: Int, $after: String, $last: Int, $before: String){
          federation {
            bases: basesWithDefaultMaxLimitRelation(first: $first, after: $after, last: $last, before: $before) {
              ... basesConnection
            }
          }
        }

        fragment basesConnection on BaseConnection {
          edges {
            cursor
            node {
              name
            }
          },
          pageInfo {
            hasNextPage
            hasPreviousPage
            startCursor
            endCursor
          }
        }
        |}

      it "applies to queries by `first`" do
        result = star_trek_query(query_string, { "first" => 100 })
        assert_equal(3, result["data"]["federation"]["bases"]["edges"].size)
        assert_equal(true, result["data"]["federation"]["bases"]["pageInfo"]["hasNextPage"])

        # Max page size is applied _without_ `first`, also
        result = star_trek_query(query_string)
        assert_equal(3, result["data"]["federation"]["bases"]["edges"].size)
        assert_equal(true, result["data"]["federation"]["bases"]["pageInfo"]["hasNextPage"], "hasNextPage is true when first is not specified")
      end

      it "applies to queries by `last`" do
        second_to_last_three_names = ["Deep Space Nine", "Firebase P'ok", "Ganalda Space Station"]
        first_second_and_third_names = ["Deep Space Station K-7", "Regula I", "Deep Space Nine"]

        last_cursor = "Ng=="
        result = star_trek_query(query_string, { "last" => 100, "before" => last_cursor })
        assert_equal(second_to_last_three_names, get_names(result))
        assert_equal(true, result["data"]["federation"]["bases"]["pageInfo"]["hasPreviousPage"])

        result = star_trek_query(query_string, { "before" => last_cursor })
        assert_equal(first_second_and_third_names, get_names(result))
        assert_equal(false, result["data"]["federation"]["bases"]["pageInfo"]["hasPreviousPage"], "hasPreviousPage is false when last is not specified")

        fourth_cursor = "NA=="
        result = star_trek_query(query_string, { "last" => 100, "before" => fourth_cursor })
        assert_equal(first_second_and_third_names, get_names(result))

        result = star_trek_query(query_string, { "before" => fourth_cursor })
        assert_equal(first_second_and_third_names, get_names(result))
      end
    end
  end

  describe "applying a max_page_size bigger than the results" do
    let(:query_string) {%|
      query getBases($first: Int, $after: String, $last: Int, $before: String){
        federation {
          bases: basesWithLargeMaxLimitRelation(first: $first, after: $after, last: $last, before: $before) {
            ... basesConnection
          }
        }
      }

      fragment basesConnection on BaseConnection {
        edges {
          cursor
          node {
            name
          }
        },
        pageInfo {
          hasNextPage
          hasPreviousPage
          startCursor
          endCursor
        }
      }
      |}

    it "applies to queries by `first`" do
      result = star_trek_query(query_string, { "first" => 100 })
      assert_equal(6, result["data"]["federation"]["bases"]["edges"].size)
      assert_equal(false, result["data"]["federation"]["bases"]["pageInfo"]["hasNextPage"])

      # Max page size is applied _without_ `first`, also
      result = star_trek_query(query_string)
      assert_equal(6, result["data"]["federation"]["bases"]["edges"].size)
      assert_equal(false, result["data"]["federation"]["bases"]["pageInfo"]["hasNextPage"], "hasNextPage is false when first is not specified")
    end

    it "applies to queries by `last`" do
      all_names = ["Deep Space Station K-7", "Regula I", "Deep Space Nine", "Firebase P'ok", "Ganalda Space Station", "Rh'Ihho Station"]

      last_cursor = "Ng=="
      result = star_trek_query(query_string, { "last" => 100, "before" => last_cursor })
      assert_equal(all_names[0..4], get_names(result))
      assert_equal(false, result["data"]["federation"]["bases"]["pageInfo"]["hasPreviousPage"])

      result = star_trek_query(query_string, { "last" => 100 })
      assert_equal(all_names, get_names(result))
      assert_equal(false, result["data"]["federation"]["bases"]["pageInfo"]["hasPreviousPage"])

      result = star_trek_query(query_string, { "before" => last_cursor })
      assert_equal(all_names[0..4], get_names(result))
      assert_equal(false, result["data"]["federation"]["bases"]["pageInfo"]["hasPreviousPage"], "hasPreviousPage is false when last is not specified")

      fourth_cursor = "NA=="
      result = star_trek_query(query_string, { "last" => 100, "before" => fourth_cursor })
      assert_equal(all_names[0..2], get_names(result))

      result = star_trek_query(query_string, { "before" => fourth_cursor })
      assert_equal(all_names[0..2], get_names(result))
    end
  end

  describe "without a block" do
    let(:query_string) {%|
      {
        federation {
          basesClone(first: 10) {
            edges {
              node {
                name
              }
            }
          }
        }
    }|}
    it "uses default resolve" do
      result = star_trek_query(query_string)
      bases = result["data"]["federation"]["basesClone"]["edges"]
      assert_equal(3, bases.length)
    end
  end

  describe "custom ordering" do
    let(:query_string) {%|
      query getBases {
        federation {
          basesByName(first: 30) { ... basesFields }
          bases(first: 30) { ... basesFields2 }
        }
      }
      fragment basesFields on BaseConnection {
        edges {
          node {
            name
          }
        }
      }
      fragment basesFields2 on BasesConnectionWithTotalCount {
        edges {
          node {
            name
          }
        }
      }
    |}

    def get_names(result, field_name)
      bases = result["data"]["federation"][field_name]["edges"]
      bases.map { |b| b["node"]["name"] }
    end

    it "applies the default value" do
      result = star_trek_query(query_string)
      bases_by_id   = ["Deep Space Station K-7", "Regula I", "Deep Space Nine"]
      bases_by_name = ["Deep Space Nine", "Deep Space Station K-7", "Regula I"]

      assert_equal(bases_by_id, get_names(result, "bases"))
      assert_equal(bases_by_name, get_names(result, "basesByName"))
    end
  end

  describe "relations" do
    let(:query_string) {%|
      query getShips {
        federation {
          bases {
            ... basesConnection
          }
        }
      }

      fragment basesConnection on BasesConnectionWithTotalCount {
        edges {
          cursor
          node {
            name
            residents {
              edges {
                node {
                  name
                }
              }
            }
          }
        }
      }
    |}

    it "Mongoid::Association::Referenced::HasMany::Targets::Enumerable" do
      result = star_trek_query(query_string)
      assert_equal get_ships_residents(result), {
        "Deep Space Station K-7" => [
          "Shir th'Talias",
          "Lurry",
          "Mackenzie Calhoun"
        ],
        "Regula I" => [
          "V. Madison",
          "D. March",
          "C. Marcus"
        ],
        "Deep Space Nine" => []
      }
    end
  end
end


text:
package com.sdwfqin.sample.camera;

import android.hardware.Camera;
import android.os.Build;

/**
 * 描述:相机工具类
 *
 * @author 张钦
 * @date 2018/12/11
 */
public class CameraUtils {

    private static boolean checkCameraFacing(final int facing) {
        final int cameraCount = Camera.getNumberOfCameras();
        Camera.CameraInfo info = new Camera.CameraInfo();
        for (int i = 0; i < cameraCount; i++) {
            Camera.getCameraInfo(i, info);
            if (facing == info.facing) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查设备是否有摄像头
     *
     * @return
     */
    public static boolean hasCamera() {
        return hasBackFacingCamera() || hasFrontFacingCamera();
    }

    /**
     * 检查设备是否有后置摄像头
     *
     * @return
     */
    public static boolean hasBackFacingCamera() {
        final int CAMERA_FACING_BACK = 0;
        return checkCameraFacing(CAMERA_FACING_BACK);
    }

    /**
     * 检查设备是否有前置摄像头
     *
     * @return
     */
    public static boolean hasFrontFacingCamera() {
        final int CAMERA_FACING_BACK = 1;
        return checkCameraFacing(CAMERA_FACING_BACK);
    }
}


text:
#include "DataType.h"
#include "tiny_log.h"
#include "tiny_str_equal.h"

#define TAG                     "ObjectType"

#define	TYPE_UI1                "ui1"
#define	TYPE_UI2                "ui2"
#define	TYPE_UI4                "ui4"
#define	TYPE_I1                 "i1"
#define	TYPE_I2                 "i2"
#define	TYPE_I4                 "i4"
#define	TYPE_INT                "int"
#define	TYPE_R4                 "r4"
#define	TYPE_R8                 "r8"
#define	TYPE_NUMBER             "number"
#define	TYPE_FIXED_14_4         "fixed.14.4"
#define	TYPE_FLOAT              "float"
#define	TYPE_CHAR               "char"
#define	TYPE_STRING             "string"
#define	TYPE_DATE               "date"
#define	TYPE_DATETIME           "dateTime"
#define	TYPE_DATETIME_TZ        "dateTime.tz"
#define	TYPE_TIME               "time"
#define	TYPE_TIME_TZ            "time.tz"
#define	TYPE_BOOLEAN            "boolean"
#define	TYPE_BIN_BASE64         "bin.base64"
#define	TYPE_BIN_HEX            "bin.hex"
#define	TYPE_URI                "uri"
#define	TYPE_UUID               "uuid"

/**
*  Byte                 i1
*  Word                 ui1, i2
*  Integer              ui2, i4, int
*  Long                 ui4, time, time.tz
*  Float                r4, float
*  Double               r8, number, fixed.14.4
*  Character            char
*  String               string, uri, uuid, bin.base64, bin.hex, date, dateTime, dateTime.tz
*  Boolean              boolean
*/
static InternalType InternalType_RetrieveType(const char *typeName)
{
    InternalType t = INTERNAL_INTEGER;

    do
    {
        if (STR_EQUAL(typeName, TYPE_I1))
        {
            t = INTERNAL_BYTE;
            break;
        }

        if (STR_EQUAL(typeName, TYPE_UI1) || STR_EQUAL(typeName, TYPE_I2))
        {
            t = INTERNAL_WORD;
            break;
        }

        if (STR_EQUAL(typeName, TYPE_UI2) || STR_EQUAL(typeName, TYPE_I4) || STR_EQUAL(typeName, TYPE_INT))
        {
            t = INTERNAL_INTEGER;
            break;
        }

        if (STR_EQUAL(typeName, TYPE_UI4) || STR_EQUAL(typeName, TYPE_TIME) || STR_EQUAL(typeName, TYPE_TIME_TZ))
        {
            t = INTERNAL_LONG;
            break;
        }

        if (STR_EQUAL(typeName, TYPE_R4) || STR_EQUAL(typeName, TYPE_FLOAT))
        {
            t = INTERNAL_FLOAT;
            break;
        }

        if (STR_EQUAL(typeName, TYPE_R8) || STR_EQUAL(typeName, TYPE_NUMBER) || STR_EQUAL(typeName, TYPE_FIXED_14_4))
        {
            t = INTERNAL_DOUBLE;
            break;
        }

        if (STR_EQUAL(typeName, TYPE_CHAR))
        {
            t = INTERNAL_CHAR;
            break;
        }

        if (STR_EQUAL(typeName, TYPE_BOOLEAN))
        {
            t = INTERNAL_BOOLEAN;
            break;
        }

        if (STR_EQUAL(typeName, TYPE_STRING)
            || STR_EQUAL(typeName, TYPE_URI)
            || STR_EQUAL(typeName, TYPE_UUID)
            || STR_EQUAL(typeName, TYPE_BIN_BASE64)
            || STR_EQUAL(typeName, TYPE_BIN_HEX)
            || STR_EQUAL(typeName, TYPE_DATE)
            || STR_EQUAL(typeName, TYPE_DATETIME)
            || STR_EQUAL(typeName, TYPE_DATETIME_TZ))
        {
            t = INTERNAL_STRING;
            break;
        }

    } while (0);

    return t;
}

static const char * InternalType_GetName(InternalType type)
{
    const char * t = NULL;

    switch (type)
    {
    case INTERNAL_BYTE:
        t = TYPE_CHAR;
        break;

    case INTERNAL_WORD:
        t = TYPE_I2;
        break;

    case INTERNAL_INTEGER:
        t = TYPE_I4;
        break;

    case INTERNAL_LONG:
        t = TYPE_UI4;
        break;

    case INTERNAL_FLOAT:
        t = TYPE_FLOAT;
        break;

    case INTERNAL_DOUBLE:
        t = TYPE_NUMBER;
        break;

    case INTERNAL_BOOLEAN:
        t = TYPE_BOOLEAN;
        break;

    case INTERNAL_CHAR:
        t = TYPE_CHAR;
        break;

    case INTERNAL_STRING:
        t = TYPE_STRING;
        break;

    default:
        break;
    }

    return t;
}

void DataType_Construct(DataType *thiz)
{
    RETURN_IF_FAIL(thiz);

    memset(thiz, 0, sizeof(DataType));
}

void DataType_Dispose(DataType *thiz)
{
    RETURN_IF_FAIL(thiz);

    memset(thiz, 0, sizeof(DataType));
}

void DataType_Copy(DataType *dst, DataType *src)
{
    RETURN_IF_FAIL(dst);
    RETURN_IF_FAIL(src);

    if (dst != src)
    {
        DataType_Dispose(dst);

        dst->internalType = src->internalType;
        strncpy(dst->name, src->name, DATA_TYPE_NAME_LEN);
    }
}

void DataType_SetName(DataType *thiz, const char *name)
{
    RETURN_IF_FAIL(thiz);
    RETURN_IF_FAIL(name);

    strncpy(thiz->name, name, DATA_TYPE_NAME_LEN);
    thiz->internalType = InternalType_RetrieveType(name);
}

void DataType_SetType(DataType *thiz, InternalType type)
{
    RETURN_IF_FAIL(thiz);

    thiz->internalType = type;
    strncpy(thiz->name, InternalType_GetName(type), DATA_TYPE_NAME_LEN);
}

bool DataType_StringToBoolean(const char *string)
{
    RETURN_VAL_IF_FAIL(string, false);

    if (STR_EQUAL("1", string) || str_equal("YES", string, true) || str_equal("TRUE", string, true))
    {
        return true;
    }

    if (STR_EQUAL("0", string) || str_equal("NO", string, true) || str_equal("FALSE", string, true))
    {
        return false;
    }

    LOG_W(TAG, "invalid boolean value: %s", string);

    return false;
}

const char * DataType_BooleanToString(bool b)
{
    return b ? "1" : "0";
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Hysterium berberidis Schltdl.

### Remarks
null


text:
INSTALL_DIR=$(mktemp -d testinstall.XXXXXXXX)
MONGO_DATA_DIR=$(mktemp -d testmongodata.XXXXXXXX)

MONGO_VERSION=3.4.17
MONGO_DIR_NAME=mongodb-linux-x86_64-rhel70-$MONGO_VERSION
MONGO_TAR_NAME=$MONGO_DIR_NAME.tgz
MONGO_URL=https://fastdl.mongodb.org/linux/$MONGO_TAR_NAME

NODE_DIR_NAME=node-v8.12.0-linux-x64
NODE_TAR_NAME=$NODE_DIR_NAME.tar.xz
NODE_URL=https://nodejs.org/dist/v8.12.0/$NODE_TAR_NAME

# Install dependencies
cd $INSTALL_DIR

# MongoDB
wget -q $MONGO_URL
tar -xf $MONGO_TAR_NAME
export PATH=$PWD/$MONGO_DIR_NAME/bin:$PATH

# Node
wget -q $NODE_URL
tar -xf $NODE_TAR_NAME
export PATH=$PWD/$NODE_DIR_NAME/bin:$PATH

cd ..

# Start Mongo
mongod --dbpath $PWD/$MONGO_DATA_DIR > /dev/null &
MONGO_PROC=$!

# Removing node_modules and reinstalling ensures mongo has plenty of time to start up
rm -rf node_modules
npm install

# Grunt is used to run the tests
npm install grunt-cli

# Run the tests
cp .env.example .env.test
./node_modules/grunt-cli/bin/grunt test

# Cleanup
kill $MONGO_PROC
rm -rf $INSTALL_DIR $MONGO_DATA_DIR node_modules


text:
<?php declare(strict_types=1);

namespace Gos\Bundle\WebSocketBundle\Event;

use Ratchet\ConnectionInterface;
use Symfony\Contracts\EventDispatcher\Event;

abstract class ClientEvent extends Event
{
    protected ConnectionInterface $connection;

    public function __construct(ConnectionInterface $connection)
    {
        $this->connection = $connection;
    }

    public function getConnection(): ConnectionInterface
    {
        return $this->connection;
    }
}


text:
@interface MOBProjectionEPSG6069 : MOBProjection

@end


text:
/**
 *
 */
package math.util;

import static org.junit.Assert.*;

import org.junit.Assert;
import org.junit.Test;

/**
 * @author debmalyajash
 *
 */
public class MathUtilTest {

	/**
	 * Test method for {@link math.util.MathUtil#PerfectSquare(int)}.
	 */
	@Test
	public final void testPerfectSquare() {
		for (int i = 0; i < 1000; i++) {
			if (MathUtil.isPerfectSquare(i)){
//				System.out.println(i);
			}
		}
	}

	@Test
	public final void testGoodNumbers() {
		String[] r = new String[]{"1","2","3"};
		int[] actuals = MathUtil.getGoodNumbers(r);
		int[] expecteds = new int[]{1,2,3};
		Assert.assertArrayEquals(expecteds, actuals);

		r = new String[]{"1","2","3","4"};
		actuals = MathUtil.getGoodNumbers(r);
		expecteds = new int[]{1,2,3,5};
		Assert.assertArrayEquals(expecteds, actuals);

		r = new String[]{"1","2","3","4","5"};
		actuals = MathUtil.getGoodNumbers(r);
		expecteds = new int[]{1,2,3,5,8};
		Assert.assertArrayEquals(expecteds, actuals);
	}

}


text:
:mod:`lockfile` --- Platform-independent file locking
=====================================================

.. module:: lockfile
   :synopsis: Platform-independent file locking
.. moduleauthor:: Skip Montanaro <skip@pobox.com>
.. sectionauthor:: Skip Montanaro <skip@pobox.com>

.. note::

   This module is alpha software.  It is quite possible that the API and
   implementation will change in important ways as people test it and
   provide feedback and bug fixes.  In particular, if the mkdir-based
   locking scheme is sufficient for both Windows and Unix platforms, the
   link-based scheme may be deleted so that only a single locking scheme is
   used, providing cross-platform lockfile cooperation.

.. note::

   The implementation uses the :keyword:`with` statement, both in the
   tests and in the main code, so will only work out-of-the-box with Python
   2.5 or later.  However, the use of the :keyword:`with` statement is
   minimal, so if you apply the patch in the included 2.4.diff file you can
   use it with Python 2.4.  It's possible that it will work in Python 2.3
   with that patch applied as well, though the doctest code relies on APIs
   new in 2.4, so will have to be rewritten somewhat to allow testing on
   2.3.  As they say, patches welcome. ``;-)``

The :mod:`lockfile` module exports a :class:`FileLock` class which provides
a simple API for locking files.  Unlike the Windows :func:`msvcrt.locking`
function, the Unix :func:`fcntl.flock`, :func:`fcntl.lockf` and the
deprecated :mod:`posixfile` module, the API is identical across both Unix
(including Linux and Mac) and Windows platforms.  The lock mechanism relies
on the atomic nature of the :func:`link` (on Unix) and :func:`mkdir` (On
Windows) system calls.

.. note::

   The current implementation uses :func:`os.link` on Unix, but since that
   function is unavailable on Windows it uses :func:`os.mkdir` there.  At
   this point it's not clear that using the :func:`os.mkdir` method would be
   insufficient on Unix systems.  If it proves to be adequate on Unix then
   the implementation could be simplified and truly cross-platform locking
   would be possible.

.. note::

   The current implementation doesn't provide for shared vs. exclusive
   locks.  It should be possible for multiple reader processes to hold the
   lock at the same time.

The module defines the following exceptions:

.. exception:: Error

   This is the base class for all exceptions raised by the :class:`LockFile`
   class.

.. exception:: LockError

   This is the base class for all exceptions raised when attempting to lock
   a file.

.. exception:: UnlockError

   This is the base class for all exceptions raised when attempting to
   unlock a file.

.. exception:: LockTimeout

   This exception is raised if the :func:`LockFile.acquire` method is
   called with a timeout which expires before an existing lock is released.

.. exception:: AlreadyLocked

   This exception is raised if the :func:`LockFile.acquire` detects a
   file is already locked when in non-blocking mode.

.. exception:: LockFailed

   This exception is raised if the :func:`LockFile.acquire` detects some
   other condition (such as a non-writable directory) which prevents it from
   creating its lock file.

.. exception:: NotLocked

   This exception is raised if the file is not locked when
   :func:`LockFile.release` is called.

.. exception:: NotMyLock

   This exception is raised if the file is locked by another thread or
   process when :func:`LockFile.release` is called.

The following classes are provided:

.. class:: LinkFileLock(path, threaded=True)

   This class uses the :func:`link(2)` system call as the basic lock
   mechanism.  *path* is an object in the file system to be locked.  It need
   not exist, but its directory must exist and be writable at the time the
   :func:`acquire` and :func:`release` methods are called.  *threaded* is
   optional, but when set to :const:`True` locks will be distinguished
   between threads in the same process.

.. class:: MkdirFileLock(path, threaded=True)

   This class uses the :func:`mkdir(2)` system call as the basic lock
   mechanism.  The parameters have the same meaning as for the
   :class:`LinkFileLock` class.

.. class:: SQLiteFileLock(path, threaded=True)

   This class uses the :mod:`sqlite3` module to implement the lock
   mechanism.  The parameters have the same meaning as for the
   :class:`LinkFileLock` class.

By default, the :const:`FileLock` object refers to the
:class:`MkdirFileLock` class on Windows.  On all other platforms it refers
to the :class:`LinkFileLock` class.

When locking a file the :class:`LinkFileLock` class creates a uniquely named
hard link to an empty lock file.  That hard link contains the hostname,
process id, and if locks between threads are distinguished, the thread
identifier.  For example, if you want to lock access to a file named
"README", the lock file is named "README.lock".  With per-thread locks
enabled the hard link is named HOSTNAME-THREADID-PID.  With only per-process
locks enabled the hard link is named HOSTNAME--PID.

When using the :class:`MkdirFileLock` class the lock file is a directory.
Referring to the example above, README.lock will be a directory and
HOSTNAME-THREADID-PID will be an empty file within that directory.

.. seealso::

   Module :mod:`msvcrt`
      Provides the :func:`locking` function, the standard Windows way of
      locking (parts of) a file.

   Module :mod:`posixfile`
      The deprecated (since Python 1.5) way of locking files on Posix systems.

   Module :mod:`fcntl`
      Provides the current best way to lock files on Unix systems
      (:func:`lockf` and :func:`flock`).

Implementing Other Locking Schemes
----------------------------------

There is a :class:`LockBase` base class which can be used as the foundation
for other locking schemes.  For example, if shared filesystems are not
available, :class:`LockBase` could be subclassed to provide locking via an
SQL database.

FileLock Objects
----------------

:class:`FileLock` objects support the :term:`context manager` protocol used
by the statement:`with` statement.  The timeout option is not supported when
used in this fashion.  While support for timeouts could be implemented,
there is no support for handling the eventual :exc:`Timeout` exceptions
raised by the :func:`__enter__` method, so you would have to protect the
:keyword:`with` statement with a :keyword:`try` statement.  The resulting
construct would not be much simpler than just using a :keyword:`try` statement
in the first place.

:class:`FileLock` has the following user-visible methods:

.. method:: FileLock.acquire(timeout=None)

   Lock the file associated with the :class:`FileLock` object.  If the
   *timeout* is omitted or :const:`None` the caller will block until the
   file is unlocked by the object currently holding the lock.  If the
   *timeout* is zero or a negative number the :exc:`AlreadyLocked` exception
   will be raised if the file is currently locked by another process or
   thread.  If the *timeout* is positive, the caller will block for that
   many seconds waiting for the lock to be released.  If the lock is not
   released within that period the :exc:`LockTimeout` exception will be
   raised.

.. method:: FileLock.release()

   Unlock the file associated with the :class:`FileLock` object.  If the
   file is not currently locked, the :exc:`NotLocked` exception is raised.
   If the file is locked by another thread or process the :exc:`NotMyLock`
   exception is raised.

.. method:: is_locked()

   Return the status of the lock on the current file.  If any process or
   thread (including the current one) is locking the file, :const:`True` is
   returned, otherwise :const:`False` is returned.

.. method:: break_lock()

   If the file is currently locked, break it.

Examples
--------

This example is the "hello world" for the :mod:`lockfile` module::

    lock = FileLock("/some/file/or/other")
    with lock:
        print lock.path, 'is locked.'

To use this with Python 2.4, you can execute::

    lock = FileLock("/some/file/or/other")
    lock.acquire()
    print lock.path, 'is locked.'
    lock.release()

If you don't want to wait forever, you might try::

    lock = FileLock("/some/file/or/other")
    while not lock.i_am_locking():
	try:
	    lock.acquire(timeout=60)    # wait up to 60 seconds
	except LockTimeout:
	    lock.break_lock()
	    lock.acquire()
    print "I locked", lock.path
    lock.release()

Other Libraries
---------------

The idea of implementing advisory locking with a standard API is not new
with :mod:`lockfile`.  There are a number of other libraries available:

* locknix - http://pypi.python.org/pypi/locknix - Unix only
* mx.MiscLockFile - from Marc André Lemburg, part of the mx.Base
  distribution - cross-platform.
* Twisted - http://twistedmatrix.com/trac/browser/trunk/twisted/python/lockfile.py
* zc.lockfile - http://pypi.python.org/pypi/zc.lockfile

Contacting the Author
---------------------

If you encounter any problems with ``lockfile``, would like help or want to
submit a patch, contact me directly: Skip Montanaro (skip@pobox.com).


text:
package fr.brouillard.oss.jgitver.metadata;

public interface MetadataRegistrar {
    public void registerMetadata(Metadatas meta, String value);
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>WPILIB: ErrorBase.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css">
<link href="doxygen.css" rel="stylesheet" type="text/css">

Main Page

Related Pages

Classes

Files

File List

File Members

ErrorBase.h File Reference
#include "Base.h"

#include "ChipObject.h"

#include "Error.h"

#include <semLib.h>

#include <vxWorks.h>

Go to the source code of this file.

Classes

class  	ErrorBase

Defines

#define 	wpi_setError(errorBase, code)   ((errorBase).SetError((code), __FILE__, __LINE__))

 	Use this macro to set the error.

Define Documentation

          #define wpi_setError
          (
          errorBase,

          code

           )
             ((errorBase).SetError((code), __FILE__, __LINE__))

Use this macro to set the error.

Definition at line 17 of file ErrorBase.h.

<address style="text-align: right;">Generated on Wed Feb 9 11:20:44 2011 for WPILIB by

 1.5.8 </address>


text:
/*
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * Copyright (C) 2006 University of Waikato, Hamilton, New Zealand
 */

package weka.filters.unsupervised.attribute;

import weka.core.Instances;
import weka.filters.AbstractFilterTest;
import weka.filters.Filter;

import junit.framework.Test;
import junit.framework.TestSuite;

/**
 * Tests NumericCleaner. Run from the command line with: <p/>
 * java weka.filters.unsupervised.attribute.NumericCleanerTest
 *
 * @author FracPete (fracpete at waikato dot ac dot nz)
 * @version $Revision: 8034 $
 */
public class NumericCleanerTest
  extends AbstractFilterTest {

  public NumericCleanerTest(String name) {
    super(name);
  }

  /** Creates a default NumericCleaner */
  public Filter getFilter() {
    return new NumericCleaner();
  }

  /**
   * runs a simple test
   */
  public void testTypical() {
    Instances icopy = new Instances(m_Instances);
    Instances result = null;
    try {
      m_Filter.setInputFormat(icopy);
    }
    catch (Exception ex) {
      ex.printStackTrace();
      fail("Exception thrown on setInputFormat(): \n" + ex.getMessage());
    }
    try {
      result = Filter.useFilter(icopy, m_Filter);
      assertNotNull(result);
    }
    catch (Exception ex) {
      ex.printStackTrace();
      fail("Exception thrown on useFilter(): \n" + ex.getMessage());
    }

    assertEquals(icopy.numAttributes(), result.numAttributes());
    assertEquals(icopy.numInstances(), result.numInstances());
  }

  public static Test suite() {
    return new TestSuite(NumericCleanerTest.class);
  }

  public static void main(String[] args){
    junit.textui.TestRunner.run(suite());
  }
}


text:
package devenv

import "os/exec"

func init() {
	var err error
	shPath, err = exec.LookPath("sh")
	if err != nil {
		return
	}
	shExists = true
}


text:
<?php

namespace Chamilo\Core\User\Service;

use Chamilo\Core\Group\Service\GroupService;
use Chamilo\Core\Group\Storage\DataClass\Group;
use Chamilo\Core\User\Component\AcceptInviteComponent;
use Chamilo\Core\User\Domain\UserInvite\Exceptions\UserAlreadyExistsException;
use Chamilo\Core\User\Storage\DataClass\User;
use Chamilo\Core\User\Storage\DataClass\UserInvite;
use Chamilo\Libraries\Architecture\Application\Application;
use Chamilo\Libraries\File\Redirect;
use Chamilo\Libraries\Mail\ValueObject\Mail;
use Chamilo\Libraries\Utilities\DatetimeUtilities;

/**
 * @package Chamilo\Core\User\Service
 * @author Sven Vanpoucke - Hogeschool Gent
 */
class UserInviteService
{
    /**
     * @var \Chamilo\Core\User\Storage\Repository\UserInviteRepository
     */
    protected $userInviteRepository;

    /**
     * @var \Chamilo\Core\User\Service\UserService
     */
    protected $userService;

    /**
     * @var \Twig\Environment
     */
    protected $twig;

    /**
     * @var \Chamilo\Libraries\Mail\Mailer\MailerInterface
     */
    protected $mailer;

    /**
     * @var \Symfony\Component\Translation\Translator
     */
    protected $translator;

    /**
     * @var \Chamilo\Libraries\File\PathBuilder
     */
    protected $pathBuilder;

    /**
     * @var \Chamilo\Configuration\Service\ConfigurationConsulter
     */
    protected $configurationConsulter;

    /**
     * @var \Chamilo\Core\Group\Service\GroupService
     */
    protected $groupService;

    /**
     * UserInviteService constructor.
     *
     * @param \Chamilo\Core\User\Storage\Repository\UserInviteRepository $userInviteRepository
     * @param \Chamilo\Core\User\Service\UserService $userService
     * @param \Twig\Environment $twig
     * @param \Chamilo\Libraries\Mail\Mailer\MailerInterface $mailer
     * @param \Symfony\Component\Translation\Translator $translator
     * @param \Chamilo\Libraries\File\PathBuilder $pathBuilder
     * @param \Chamilo\Configuration\Service\ConfigurationConsulter $configurationConsulter
     * @param \Chamilo\Core\Group\Service\GroupService $groupService
     */
    public function __construct(
        \Chamilo\Core\User\Storage\Repository\UserInviteRepository $userInviteRepository,
        \Chamilo\Core\User\Service\UserService $userService, \Twig\Environment $twig,
        \Chamilo\Libraries\Mail\Mailer\MailerInterface $mailer, \Symfony\Component\Translation\Translator $translator,
        \Chamilo\Libraries\File\PathBuilder $pathBuilder,
        \Chamilo\Configuration\Service\ConfigurationConsulter $configurationConsulter,
        GroupService $groupService
    )
    {
        $this->userInviteRepository = $userInviteRepository;
        $this->userService = $userService;
        $this->twig = $twig;
        $this->mailer = $mailer;
        $this->translator = $translator;
        $this->pathBuilder = $pathBuilder;
        $this->configurationConsulter = $configurationConsulter;
        $this->groupService = $groupService;
    }

    /**
     * This method creates a new inactive user into the database and creates an invite for the user. The invitation is
     * then sent to the user by email. This method returns the created user so it can automatically be used to set
     * rights for that external user in the context.
     *
     * @param \Chamilo\Core\User\Storage\DataClass\User $invitedByUser
     * @param string $userEmail
     *
     * @param \DateTime $expirationDate
     *
     * @param string|null $personalMessage
     *
     * @return \Chamilo\Core\User\Storage\DataClass\User
     * @throws UserAlreadyExistsException
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     * @throws \Exception
     */
    public function inviteUser(
        User $invitedByUser, string $userEmail, \DateTime $expirationDate, string $personalMessage = null
    )
    {
        $this->validateUserEmail($userEmail);
        $user = $this->createUserByEmail($userEmail, $expirationDate);
        $userInvite = $this->createUserInvite($invitedByUser, $user);
//        $user = $this->userService->findUserByIdentifier(2);
//        $userInvite = $this->userInviteRepository->getUserInviteBySecurityKey(
//            '59f7b3e215c0497ba75588c71990635a7f31e27b267fe19aa341077c815e65ca'
//        );
        $this->addUserToExternalGroup($user);
        $this->sendInvitationEmail($invitedByUser, $user, $userInvite, $personalMessage);

        return $user;
    }

    /**
     * @param User $invitedByUser
     * @param UserInvite $userInvite
     *
     * @return UserInvite
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     */
    public function extendUserInvite(User $invitedByUser, UserInvite $userInvite)
    {
        $currentDate = new \DateTime();
        $validUntil = $currentDate->add(new \DateInterval('P7D'));

        $userInvite->setValidUntil($validUntil);
        $userInvite->setStatus(UserInvite::STATUS_INVITED);

        if (!$this->userInviteRepository->updateUserInvite($userInvite))
        {
            throw new \InvalidArgumentException('Could not extend the user invite with id ' . $userInvite->getId());
        }

        $invitedUser = $this->userService->findUserByIdentifier($userInvite->getUserId());
        if(!$invitedUser instanceof User)
        {
            throw new \RuntimeException(sprintf('Invited user with id %s not found', $userInvite->getUserId()));
        }

        $this->sendInvitationEmail($invitedByUser, $invitedUser, $userInvite);

        return $userInvite;
    }

    /**
     * @param string|null $securityKey
     *
     * @return UserInvite
     * @throws \Exception
     */
    public function getUserInviteBySecurityKey(string $securityKey = null)
    {
        if (empty($securityKey))
        {
            throw new \InvalidArgumentException('The given security key can not be empty');
        }

        $userInvite = $this->userInviteRepository->getUserInviteBySecurityKey($securityKey);
        if ($userInvite->isOpen())
        {
            return $userInvite;
        }

        return null;
    }

    /**
     * @param int $userInviteId
     *
     * @return UserInvite
     */
    public function getUserInviteById(int $userInviteId)
    {
        return $this->userInviteRepository->getUserInviteById($userInviteId);
    }

    /**
     * @param \Chamilo\Core\User\Storage\DataClass\UserInvite|null $userInvite
     *
     * @return string
     */
    public function getDefaultEmailFromUserInvite(UserInvite $userInvite = null)
    {
        if (!$userInvite instanceof UserInvite)
        {
            return null;
        }

        $user = $this->userService->findUserByIdentifier($userInvite->getUserId());
        if ($user instanceof User)
        {
            return $user->get_email();
        }

        return null;
    }

    /**
     * @param \Chamilo\Core\User\Storage\DataClass\UserInvite $userInvite
     * @param string $firstName
     * @param string $lastName
     * @param string $password
     *
     * @return \Chamilo\Core\User\Storage\DataClass\User
     * @throws \Exception
     */
    public function acceptInvitation(
        UserInvite $userInvite, string $firstName, string $lastName, string $password
    )
    {
        if (!$userInvite->isOpen())
        {
            throw new \RuntimeException(
                sprintf(
                    'The given user invite with id %s is no longer valid and should not be accepted',
                    $userInvite->getId()
                )
            );
        }
        $user = $this->userService->findUserByIdentifier($userInvite->getUserId());
        if (!$user instanceof User)
        {
            throw new \RuntimeException(
                'The given user with id %s could not be found. The invitation can not be completed'
            );
        }

        $this->userService->updateUserByValues(
            $user, $firstName, $lastName, null, null, null, $password, null, true
        );

        $userInvite->setStatus(UserInvite::STATUS_ACCEPTED);
        if (!$this->userInviteRepository->updateUserInvite($userInvite))
        {
            throw new \InvalidArgumentException(
                'Could not change the status of the user invite ' . $userInvite->getId()
            );
        }

        return $user;
    }

    /**
     * Returns the invites made by the given user
     *
     * @param \Chamilo\Core\User\Storage\DataClass\User $user
     *
     * @return \Chamilo\Libraries\Storage\Iterator\RecordIterator
     */
    public function getInvitesFromUser(User $user)
    {
        $invites = $this->userInviteRepository->getUserInvitesFromUser($user);

        foreach ($invites as $index => $existingInvite)
        {
            if ($existingInvite['status'] == UserInvite::STATUS_INVITED)
            {
                if ($existingInvite['valid_until'] < time())
                {
                    $invites[$index]['status'] = UserInvite::STATUS_EXPIRED;
                }
            }

            $invites[$index]['valid_until'] =
                DatetimeUtilities::format_locale_date(null, $existingInvite['valid_until']);
        }

        return $invites;
    }

    /**
     * @param string $userEmail
     *
     * @throws \Chamilo\Core\User\Domain\UserInvite\Exceptions\UserAlreadyExistsException
     */
    protected function validateUserEmail(string $userEmail)
    {
        if (!$this->isStringValidEmail($userEmail))
        {
            throw new \InvalidArgumentException(sprintf('The given email %s is invalid', $userEmail));
        }

        $userByEmail = $this->userService->getUserByUsernameOrEmail($userEmail);
        if ($userByEmail instanceof User)
        {
            throw new UserAlreadyExistsException();
        }
    }

    /**
     * @param string $userEmail
     *
     * @return bool
     */
    protected function isStringValidEmail(string $userEmail)
    {
        return preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $userEmail);
    }

    /**
     * @param string $userEmail
     * @param \DateTime|null $expirationDate
     *
     * @return \Chamilo\Core\User\Storage\DataClass\User
     */
    protected function createUserByEmail(string $userEmail, \DateTime $expirationDate):
    \Chamilo\Core\User\Storage\DataClass\User
    {
        $officialCode = $this->userService->generateUniqueUsername();

        $user = $this->userService->createUser(
            'Invited User', 'Invited User', $userEmail, $officialCode, $userEmail, null, 'Platform', true,
            $expirationDate
        );

        if (!$user instanceof User)
        {
            throw new \RuntimeException('The invited user could not be created for email ' . $userEmail);
        }

        return $user;
    }

    /**
     * @param \Chamilo\Core\User\Storage\DataClass\User $invitedByUser
     * @param \Chamilo\Core\User\Storage\DataClass\User $invitedUser
     *
     * @return \Chamilo\Core\User\Storage\DataClass\UserInvite
     * @throws \Exception
     */
    protected function createUserInvite(User $invitedByUser, User $invitedUser)
    {
        $currentDate = new \DateTime();
        $validUntil = $currentDate->add(new \DateInterval('P7D'));

        $invite = new UserInvite();
        $invite->setUserId($invitedUser->getId());
        $invite->setInvitedByUserId($invitedByUser->getId());
        $invite->setSecurityKey(hash('sha256', uniqid() . $invitedUser->getId() . uniqid()));
        $invite->setValidUntil($validUntil);
        $invite->setStatus(UserInvite::STATUS_INVITED);

        if (!$this->userInviteRepository->createUserInvite($invite))
        {
            throw new \InvalidArgumentException('Could not create a new user invite for user ' . $invitedUser->getId());
        }

        return $invite;
    }

    /**
     * @param \Chamilo\Core\User\Storage\DataClass\User $user
     */
    protected function addUserToExternalGroup(User $user)
    {
        $externalUsersGroupId =
            $this->configurationConsulter->getSetting(['Chamilo\Core\User', 'external_users_group_id']);

        if (empty($externalUsersGroupId))
        {
            return;
        }

        $externalUsersGroup = $this->groupService->getGroupByIdentifier($externalUsersGroupId);
        if (!$externalUsersGroup instanceof Group)
        {
            return;
        }

        $this->groupService->subscribeUserToGroup($externalUsersGroup, $user);
    }

    /**
     * @param \Chamilo\Core\User\Storage\DataClass\User $invitedByUser
     * @param \Chamilo\Core\User\Storage\DataClass\User $invitedUser
     * @param UserInvite|null $userInvite
     * @param string|null $personalMessage
     *
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     */
    protected function sendInvitationEmail(
        User $invitedByUser, User $invitedUser, UserInvite $userInvite = null, string $personalMessage = null
    )
    {
        $siteUrl = $this->pathBuilder->getBasePath(true);
        $subject = $this->translator->trans('InviteUserMailSubject', ['{SITE_URL}' => $siteUrl], 'Chamilo\Core\User');

        $redirect = new Redirect(
            [
                Application::PARAM_CONTEXT => \Chamilo\Core\User\Manager::context(),
                Application::PARAM_ACTION => \Chamilo\Core\User\Manager::ACTION_ACCEPT_INVITE,
                AcceptInviteComponent::PARAM_SECURITY_KEY => $userInvite->getSecurityKey()
            ]
        );

        $inviteUrl = $redirect->getUrl();

        $content = $this->twig->render(
            'Chamilo\Core\User:InviteUser.eml.html.twig',
            [
                'INVITED_USER' => $invitedUser, 'INVITED_BY_USER' => $invitedByUser, 'USER_INVITE' => $userInvite,
                'SITE_URL' => $siteUrl, 'SUBJECT' => $subject,
                'PERSONAL_MESSAGE' => $personalMessage,
                'LOGO' => $this->configurationConsulter->getSetting(['Chamilo\Core\Menu', 'brand_image']),
                'ACCEPT_INVITE_URL' => $inviteUrl
            ]
        );

//        echo $content;

        $mail = new Mail(
            $subject, $content, [$invitedUser->get_email()], true, [], [], $invitedByUser->get_fullname(),
            $invitedByUser->get_email()
        );

        $this->mailer->sendMail($mail);
    }

}


text: Command-line tool for reading data out of iPhoto '11.  Written in Python 3.x.


text:
/***********************************************************************************************************************
 *
 * FixBro - an open source FIX broker (sell side) simulator
 * =========================================================
 *
 * https://github.com/embosfer
 *
 ***********************************************************************************************************************
 *
 * 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 com.embosfer.fixbro.controller.er.processor;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.embosfer.fixbro.controller.er.observer.ExecutionReportObservable;
import com.embosfer.fixbro.controller.er.observer.ExecutionReportObserver;
import com.embosfer.fixbro.model.messages.ExecutionReport;

/**
 * Distributes the {@link ExecutionReport}s produced by FIXBro to all
 * {@link ExecutionReportObserver}s
 *
 * @author embosfer
 *
 */
public class ExecutionReportProcessorImpl implements ExecutionReportProcessor, ExecutionReportObservable {

	private final Logger log = LoggerFactory.getLogger(ExecutionReportProcessorImpl.class);

	private final List<ExecutionReportObserver> erObserverList;
	private final ExecutorService executorService;

	public ExecutionReportProcessorImpl(List<ExecutionReportObserver> observers) {
		erObserverList = new CopyOnWriteArrayList<>(observers);
		executorService = Executors.newCachedThreadPool();
	}

	@Override
	public void process(ExecutionReport er) {
		erObserverList.forEach(observer -> {
			log.info("Sending {}", er);
			executorService.execute(() -> observer.onExecutionReport(er));
		});
	}

	@Override
	public void registerExecutionReportObservable(ExecutionReportObserver observer) {
		erObserverList.add(observer);
	}

	@Override
	public void unRegisterExecutionReportObservable(ExecutionReportObserver observer) {
		Iterator<ExecutionReportObserver> it = erObserverList.iterator();
		while (it.hasNext()) {
			ExecutionReportObserver o = it.next();
			if (o.equals(observer)) {
				it.remove();
				return;
			}
		}
	}

}


text:
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">
                Toggle navigation

            </button>

 02344 452656 / 433656 / 431656

 02344 452656 / 433656 / 431656

La Empresa

Productos y Servicios

Preguntas Frecuentes

Links de Interés

Contacto


text:
package com.twitter.finatra.tests.utils

import com.twitter.finatra.utils.AutoClosable
import com.twitter.inject.Test
import com.twitter.util.logging.Logger

class AutoClosableTest extends Test {

  test("AutoClosable#close") {
    val closable = new AutoClosableObject()

    AutoClosable.tryWith(closable) { closable =>
      closable.doSomething()
    }

    closable.isClosed should be(true)
  }

}

private object AutoClosableObject {
  val logger: Logger = Logger(AutoClosableObject.getClass)
}

class AutoClosableObject extends AutoCloseable {
  import AutoClosableObject._

  private var closed = false

  def isClosed: Boolean = {
    closed
  }

  def doSomething(): Unit = {
    logger.info("Performing auto-closable function.")
  }

  override def close(): Unit = {
    closed = true
  }
}


text:
package org.springframework.boot.autoconfigure.logging;

import java.util.function.Supplier;

import org.springframework.boot.autoconfigure.condition.ConditionEvaluationReport;
import org.springframework.boot.context.event.ApplicationFailedEvent;
import org.springframework.boot.logging.LogLevel;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.ResolvableType;
import org.springframework.util.Assert;

/**
 * {@link ApplicationContextInitializer} that writes the {@link ConditionEvaluationReport}
 * to the log. Reports are logged at the {@link LogLevel#DEBUG DEBUG} level. A crash
 * report triggers an info output suggesting the user runs again with debug enabled to
 * display the report.
 * <p>
 * This initializer is not intended to be shared across multiple application context
 * instances.
 *
 * @author Greg Turnquist
 * @author Dave Syer
 * @author Phillip Webb
 * @author Andy Wilkinson
 * @author Madhura Bhave
 * @since 2.0.0
 */
public class ConditionEvaluationReportLoggingListener
		implements ApplicationContextInitializer<ConfigurableApplicationContext> {

	private final LogLevel logLevelForReport;

	public ConditionEvaluationReportLoggingListener() {
		this(LogLevel.DEBUG);
	}

	private ConditionEvaluationReportLoggingListener(LogLevel logLevelForReport) {
		Assert.isTrue(isInfoOrDebug(logLevelForReport), "LogLevel must be INFO or DEBUG");
		this.logLevelForReport = logLevelForReport;
	}

	private boolean isInfoOrDebug(LogLevel logLevelForReport) {
		return LogLevel.INFO.equals(logLevelForReport) || LogLevel.DEBUG.equals(logLevelForReport);
	}

	/**
	 * Static factory method that creates a
	 * {@link ConditionEvaluationReportLoggingListener} which logs the report at the
	 * specified log level.
	 * @param logLevelForReport the log level to log the report at
	 * @return a {@link ConditionEvaluationReportLoggingListener} instance.
	 * @since 3.0.0
	 */
	public static ConditionEvaluationReportLoggingListener forLogLevel(LogLevel logLevelForReport) {
		return new ConditionEvaluationReportLoggingListener(logLevelForReport);
	}

	@Override
	public void initialize(ConfigurableApplicationContext applicationContext) {
		applicationContext.addApplicationListener(new ConditionEvaluationReportListener(applicationContext));
	}

	private final class ConditionEvaluationReportListener implements GenericApplicationListener {

		private final ConfigurableApplicationContext context;

		private final ConditionEvaluationReportLogger logger;

		private ConditionEvaluationReportListener(ConfigurableApplicationContext context) {
			this.context = context;
			Supplier<ConditionEvaluationReport> reportSupplier;
			if (context instanceof GenericApplicationContext) {
				// Get the report early when the context allows early access to the bean
				// factory in case the context subsequently fails to load
				ConditionEvaluationReport report = getReport();
				reportSupplier = () -> report;
			}
			else {
				reportSupplier = this::getReport;
			}
			this.logger = new ConditionEvaluationReportLogger(
					ConditionEvaluationReportLoggingListener.this.logLevelForReport, reportSupplier);
		}

		private ConditionEvaluationReport getReport() {
			return ConditionEvaluationReport.get(this.context.getBeanFactory());
		}

		@Override
		public int getOrder() {
			return Ordered.LOWEST_PRECEDENCE;
		}

		@Override
		public boolean supportsEventType(ResolvableType resolvableType) {
			Class<?> type = resolvableType.getRawClass();
			if (type == null) {
				return false;
			}
			return ContextRefreshedEvent.class.isAssignableFrom(type)
					|| ApplicationFailedEvent.class.isAssignableFrom(type);
		}

		@Override
		public boolean supportsSourceType(Class<?> sourceType) {
			return true;
		}

		@Override
		public void onApplicationEvent(ApplicationEvent event) {
			if (event instanceof ContextRefreshedEvent contextRefreshedEvent) {
				if (contextRefreshedEvent.getApplicationContext() == this.context) {
					this.logger.logReport(false);
				}
			}
			else if (event instanceof ApplicationFailedEvent applicationFailedEvent
					&& applicationFailedEvent.getApplicationContext() == this.context) {
				this.logger.logReport(true);
			}
		}

	}

}


text:
from module_kits.vtk_kit.mixins import SimpleVTKClassModuleBase
import vtk

class vtkTessellatorFilter(SimpleVTKClassModuleBase):
    def __init__(self, module_manager):
        SimpleVTKClassModuleBase.__init__(
            self, module_manager,
            vtk.vtkTessellatorFilter(), 'Processing.',
            ('vtkDataSet',), ('vtkUnstructuredGrid',),
            replaceDoc=True,
            inputFunctions=None, outputFunctions=None)