text:
package org.netbeans.jpa.source;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Types;
import org.netbeans.api.java.source.CompilationController;
import org.netbeans.api.java.source.WorkingCopy;
import org.openide.filesystems.FileLock;
import org.openide.filesystems.FileObject;
import org.openide.util.Utilities;

/**
 *
 * @author Gaurav Gupta
 */
public class JavaSourceParserUtil {

    public static String simpleClassName(String fqn) {
        int lastDot = fqn.lastIndexOf('.');
        return lastDot > 0 ? fqn.substring(lastDot + 1) : fqn;
    }

    public static String readResource(InputStream is, String encoding) throws IOException {
        // read the config from resource first
        StringBuilder sbuffer = new StringBuilder();
        String lineSep = System.getProperty("line.separator");//NOI18N
        BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding));
        String line = br.readLine();
        while (line != null) {
            sbuffer.append(line);
            sbuffer.append(lineSep);
            line = br.readLine();
        }
        br.close();
        return sbuffer.toString();
    }

    public static void createFile(FileObject target, String content, String encoding) throws IOException {
        FileLock lock = target.lock();
        try {
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(target.getOutputStream(lock), encoding));
            bw.write(content);
            bw.close();

        } finally {
            lock.releaseLock();
        }
    }

    public static boolean isFieldAccess(TypeElement clazz) {
        boolean fieldAccess = false;
        boolean accessTypeDetected = false;
        TypeElement typeElement = clazz;
        Name qualifiedName = typeElement.getQualifiedName();
        whileloop:
        while (typeElement != null) {
            if (isAnnotatedWith(typeElement, "javax.persistence.Entity") || isAnnotatedWith(typeElement, "javax.persistence.MappedSuperclass")) { // NOI18N
                for (Element element : typeElement.getEnclosedElements()) {
                    if (isAnnotatedWith(element, "javax.persistence.Id") || isAnnotatedWith(element, "javax.persistence.EmbeddedId") || isAnnotatedWith(element, "javax.persistence.Embedded")
                            || isAnnotatedWith(element, "javax.persistence.Basic") || isAnnotatedWith(element, "javax.persistence.Transient")
                            || isAnnotatedWith(element, "javax.persistence.Version") || isAnnotatedWith(element, "javax.persistence.ElementCollection")
                            || isAnnotatedWith(element, "javax.persistence.OneToMany") || isAnnotatedWith(element, "javax.persistence.ManyToMany")
                            || isAnnotatedWith(element, "javax.persistence.OneToOne") || isAnnotatedWith(element, "javax.persistence.ManyToOne")) {
                        if (ElementKind.FIELD == element.getKind()) {
                            fieldAccess = true;
                        }
                        accessTypeDetected = true;
                        break whileloop;
                    }
                }
            }
            typeElement = getSuperclassTypeElement(typeElement);
        }
        if (!accessTypeDetected) {
            Logger.getLogger(JavaSourceParserUtil.class.getName()).log(Level.WARNING, "Failed to detect correct access type for class: {0}", qualifiedName); // NOI18N
        }
        return fieldAccess;
    }

    public static boolean isAnnotatedWith(Element element, String annotationFqn) {
        return findAnnotation(element, annotationFqn) != null;
    }

    public static AnnotationMirror getAnnotation(Element element, String annotationFqn) {//temp replica
        return findAnnotation(element, annotationFqn);
    }

    public static AnnotationMirror findAnnotation(Element element, String annotationFqn) {
        for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) {
            String annotationQualifiedName = getAnnotationQualifiedName(annotationMirror);
            if (annotationQualifiedName.equals(annotationFqn)) {
                return annotationMirror;
            }
        }
        return null;
    }

    public static String getAnnotationQualifiedName(AnnotationMirror annotationMirror) {
//     Iterator<Entry<? extends ExecutableElement, ? extends AnnotationValue>> elementValuesItr =  annotationMirror.getElementValues().entrySet().iterator();
        DeclaredType annotationDeclaredType = annotationMirror.getAnnotationType();
        TypeElement annotationTypeElement = (TypeElement) annotationDeclaredType.asElement();
        Name name = annotationTypeElement.getQualifiedName();
        return name.toString();
    }

    public static TypeElement getSuperclassTypeElement(TypeElement typeElement) {
        TypeElement superclass = null;
        TypeMirror superclassMirror = typeElement.getSuperclass();
        if (superclassMirror.getKind() == TypeKind.DECLARED) {
            DeclaredType superclassDeclaredType = (DeclaredType) superclassMirror;
            Element superclassElement = superclassDeclaredType.asElement();
            if (superclassElement.getKind() == ElementKind.CLASS && (superclassElement instanceof TypeElement)) {
                superclass = (TypeElement) superclassElement;
            }
        }
        return superclass;
    }

    public static TypeElement getAttributeTypeElement(VariableElement variableElement) {
        TypeElement attribute = null;
        TypeMirror attributeMirror = variableElement.asType();
        if (attributeMirror.getKind() == TypeKind.DECLARED) {
            DeclaredType attributeDeclaredType = (DeclaredType) attributeMirror;
            Element attributeElement = attributeDeclaredType.asElement();
            if (attributeElement.getKind() == ElementKind.CLASS && (attributeElement instanceof TypeElement)) {
                attribute = (TypeElement) attributeElement;
            }
        }
        return attribute;
    }

    public static String findAnnotationValueAsString(AnnotationMirror annotation, String annotationKey) {
        String value = null;
        Map<? extends ExecutableElement, ? extends AnnotationValue> annotationMap = annotation.getElementValues();
        for (ExecutableElement key : annotationMap.keySet()) {
            if (annotationKey.equals(key.getSimpleName().toString())) {
                AnnotationValue annotationValue = annotationMap.get(key);
                value = annotationValue.getValue().toString();
                break;
            }
        }
        return value;
    }

    public static Object findAnnotationValue(AnnotationMirror annotation, String annotationKey) {
        Object value = null;
        Map<? extends ExecutableElement, ? extends AnnotationValue> annotationMap = annotation.getElementValues();
        for (ExecutableElement key : annotationMap.keySet()) {
            if (annotationKey.equals(key.getSimpleName().toString())) {
                AnnotationValue annotationValue = annotationMap.get(key);
                value = annotationValue.getValue();
                break;
            }
        }
        return value;
    }

    public static List<AnnotationMirror> findNestedAnnotations(AnnotationMirror annotationMirror, String annotationFqn) {
        List<AnnotationMirror> result = new ArrayList<AnnotationMirror>();
        findNestedAnnotationsInternal(annotationMirror, annotationFqn, result);
        return result;
    }

    private static void findNestedAnnotationsInternal(Object object, String annotationFqn, List<AnnotationMirror> result) {
        Collection<? extends AnnotationValue> annotationValueCollection = null;
        if (object instanceof AnnotationMirror) {
            AnnotationMirror annotationMirror = (AnnotationMirror) object;
            String annotationQualifiedName = getAnnotationQualifiedName(annotationMirror);
            if (annotationQualifiedName.equals(annotationFqn)) {
                result.add(annotationMirror);
            } else {
                //prepare to recurse
                Map<? extends ExecutableElement, ? extends AnnotationValue> annotationMap = annotationMirror.getElementValues();
                annotationValueCollection = annotationMap.values();
            }
        } else if (object instanceof List) {
            //prepare to recurse
            annotationValueCollection = (Collection<? extends AnnotationValue>) object;
        }

        //recurse
        if (annotationValueCollection != null) {
            for (AnnotationValue annotationValue : annotationValueCollection) {
                Object value = annotationValue.getValue();
                findNestedAnnotationsInternal(value, annotationFqn, result);
            }
        }
    }

    public static String fieldFromClassName(String className) {
        boolean makeFirstLower = className.length() == 1 || (!Character.isUpperCase(className.charAt(1)));
        String candidate = makeFirstLower ? className.substring(0, 1).toLowerCase() + className.substring(1) : className;
        if (!Utilities.isJavaIdentifier(candidate)) {
            candidate += "1"; //NOI18N
        }
        return candidate;
    }

    public static String getPropNameFromMethod(String name) {
        //getABcd should be converted to ABcd, getFooBar should become fooBar
        //getA1 is "a1", getA_ is a_, getAB is AB
        //in case method doesn't start with "get" return name with brackets
        if (!name.startsWith("get") && !name.startsWith("set")) {  //NOI18N
            return name + "()";   //NOI18n
        }
        boolean makeFirstLower = name.length() < 5 || (!Character.isUpperCase(name.charAt(4)));
        return makeFirstLower ? name.substring(3, 4).toLowerCase() + name.substring(4) : name.substring(3);
    }

    public static boolean isEmbeddableClass(Element typeElement) {//TypeElement
        if (JavaSourceParserUtil.isAnnotatedWith(typeElement, "javax.persistence.Embeddable")) {
            return true;
        }
        return false;
    }

    public static boolean isMappedSuperClass(Element typeElement) {//TypeElement
        if (JavaSourceParserUtil.isAnnotatedWith(typeElement, "javax.persistence.MappedSuperclass")) {
            return true;
        }
        return false;
    }

    public static boolean isEntityClass(Element typeElement) {//TypeElement
        if (JavaSourceParserUtil.isAnnotatedWith(typeElement, "javax.persistence.Entity")) {
            return true;
        }
        return false;
    }

    public static boolean isNonEntityClass(TypeElement typeElement) {
        if (!isEntityClass(typeElement) && !isMappedSuperClass(typeElement) && !isEmbeddableClass(typeElement)) {
            return true;
        }
        return false;
    }

    public static int isRelationship(ExecutableElement method, boolean isFieldAccess) {
        Element element = isFieldAccess ? JavaSourceParserUtil.guessField(method) : method;
        if (element != null) {
            if (JavaSourceParserUtil.isAnnotatedWith(element, "javax.persistence.OneToOne") || JavaSourceParserUtil.isAnnotatedWith(element, "javax.persistence.ManyToOne")) {
                return REL_TO_ONE;
            }
            if (JavaSourceParserUtil.isAnnotatedWith(element, "javax.persistence.OneToMany") || JavaSourceParserUtil.isAnnotatedWith(element, "javax.persistence.ManyToMany")) {
                return REL_TO_MANY;
            }
        }
        return REL_NONE;
    }

    public static ExecutableElement getOtherSideOfRelation(CompilationController controller, ExecutableElement executableElement, boolean isFieldAccess) {
        TypeMirror passedReturnType = executableElement.getReturnType();
        if (TypeKind.DECLARED != passedReturnType.getKind() || !(passedReturnType instanceof DeclaredType)) {
            return null;
        }
        Types types = controller.getTypes();
        TypeMirror passedReturnTypeStripped = stripCollection((DeclaredType) passedReturnType, types);
        if (passedReturnTypeStripped == null) {
            return null;
        }
        TypeElement passedReturnTypeStrippedElement = (TypeElement) types.asElement(passedReturnTypeStripped);

        //try to find a mappedBy annotation element on the possiblyAnnotatedElement
        Element possiblyAnnotatedElement = isFieldAccess ? JavaSourceParserUtil.guessField(executableElement) : executableElement;
        String mappedBy = null;
        AnnotationMirror persistenceAnnotation = JavaSourceParserUtil.findAnnotation(possiblyAnnotatedElement, "javax.persistence.OneToOne");  //NOI18N"
        if (persistenceAnnotation == null) {
            persistenceAnnotation = JavaSourceParserUtil.findAnnotation(possiblyAnnotatedElement, "javax.persistence.OneToMany");  //NOI18N"
        }
        if (persistenceAnnotation == null) {
            persistenceAnnotation = JavaSourceParserUtil.findAnnotation(possiblyAnnotatedElement, "javax.persistence.ManyToOne");  //NOI18N"
        }
        if (persistenceAnnotation == null) {
            persistenceAnnotation = JavaSourceParserUtil.findAnnotation(possiblyAnnotatedElement, "javax.persistence.ManyToMany");  //NOI18N"
        }
        if (persistenceAnnotation != null) {
            mappedBy = JavaSourceParserUtil.findAnnotationValueAsString(persistenceAnnotation, "mappedBy");  //NOI18N
        }
        for (ExecutableElement method : JavaSourceParserUtil.getMethods(passedReturnTypeStrippedElement)) {
            if (mappedBy != null && mappedBy.length() > 0) {
                String tail = mappedBy.length() > 1 ? mappedBy.substring(1) : "";
                String getterName = "get" + mappedBy.substring(0, 1).toUpperCase() + tail;
                if (getterName.equals(method.getSimpleName().toString())) {
                    return method;
                }
            } else {
                TypeMirror iteratedReturnType = method.getReturnType();
                iteratedReturnType = stripCollection(iteratedReturnType, types);
                TypeMirror executableElementEnclosingType = executableElement.getEnclosingElement().asType();
                if (types.isSameType(executableElementEnclosingType, iteratedReturnType)) {
                    return method;
                }
            }
        }
        return null;
    }

    public static final int REL_NONE = 0;
    public static final int REL_TO_ONE = 1;
    public static final int REL_TO_MANY = 2;

    public static TypeMirror stripCollection(TypeMirror passedType, Types types) {
        if (TypeKind.DECLARED != passedType.getKind() || !(passedType instanceof DeclaredType)) {
            return passedType;
        }
        TypeElement passedTypeElement = (TypeElement) types.asElement(passedType);
        String passedTypeQualifiedName = passedTypeElement.getQualifiedName().toString();   //does not include type parameter info
        Class passedTypeClass = null;
        try {
            passedTypeClass = Class.forName(passedTypeQualifiedName);
        } catch (ClassNotFoundException e) {
            //just let passedTypeClass be null
        }
        if (passedTypeClass != null && Collection.class.isAssignableFrom(passedTypeClass)) {
            List<? extends TypeMirror> passedTypeArgs = ((DeclaredType) passedType).getTypeArguments();
            if (passedTypeArgs.isEmpty()) {
                return passedType;
            }
            return passedTypeArgs.get(0);
        }
        return passedType;
    }

    public static boolean isFieldOptionalAndNullable(ExecutableElement method, boolean fieldAccess) {
        boolean isFieldOptional = true;
        Boolean isFieldNullable;
        Element fieldElement = fieldAccess ? JavaSourceParserUtil.guessField(method) : method;
        if (fieldElement == null) {
            fieldElement = method;
        }
        String[] fieldAnnotationFqns = {"javax.persistence.ManyToOne", "javax.persistence.OneToOne", "javax.persistence.Basic"};
        Boolean isFieldOptionalBoolean = findAnnotationValueAsBoolean(fieldElement, fieldAnnotationFqns, "optional");
        if (isFieldOptionalBoolean != null) {
            isFieldOptional = isFieldOptionalBoolean.booleanValue();
        }
        if (!isFieldOptional) {
            return false;
        }
        //field is optional
        fieldAnnotationFqns = new String[]{"javax.persistence.Column", "javax.persistence.JoinColumn"};
        isFieldNullable = findAnnotationValueAsBoolean(fieldElement, fieldAnnotationFqns, "nullable");
        if (isFieldNullable != null) {
            return isFieldNullable.booleanValue();
        }
        //new ballgame
        boolean result = true;
        AnnotationMirror fieldAnnotation = JavaSourceParserUtil.findAnnotation(fieldElement, "javax.persistence.JoinColumns"); //NOI18N
        if (fieldAnnotation != null) {
            //all joinColumn annotations must indicate nullable = false to return a false result
            List<AnnotationMirror> joinColumnAnnotations = JavaSourceParserUtil.findNestedAnnotations(fieldAnnotation, "javax.persistence.JoinColumn");
            for (AnnotationMirror joinColumnAnnotation : joinColumnAnnotations) {
                String columnNullableValue = JavaSourceParserUtil.findAnnotationValueAsString(joinColumnAnnotation, "nullable"); //NOI18N
                if (columnNullableValue != null) {
                    result = Boolean.parseBoolean(columnNullableValue);
                    if (result) {
                        break;  //one of the joinColumn annotations is nullable, so return true
                    }
                } else {
                    result = true;
                    break;  //one of the joinColumn annotations is nullable, so return true
                }
            }
        }
        return result;
    }

    private static Boolean findAnnotationValueAsBoolean(Element fieldElement, String[] fieldAnnotationFqns, String annotationKey) {
        Boolean isFieldXable = null;
        for (int i = 0; i < fieldAnnotationFqns.length; i++) {
            String fieldAnnotationFqn = fieldAnnotationFqns[i];
            AnnotationMirror fieldAnnotation = JavaSourceParserUtil.findAnnotation(fieldElement, fieldAnnotationFqn); //NOI18N
            if (fieldAnnotation != null) {
                String annotationValueString = JavaSourceParserUtil.findAnnotationValueAsString(fieldAnnotation, annotationKey); //NOI18N
                if (annotationValueString != null) {
                    isFieldXable = Boolean.valueOf(annotationValueString);
                } else {
                    isFieldXable = Boolean.TRUE;
                }
                break;
            }
        }
        return isFieldXable;
    }

    /**
     * check if there is id in the entity
     *
     * @param typeElement
     * @return true if id is present
     */
    public static boolean haveId(final TypeElement clazz) {
        boolean idDetected = false;
        TypeElement typeElement = clazz;
        while (typeElement != null && !idDetected) {
            if (isAnnotatedWith(typeElement, "javax.persistence.Entity") || isAnnotatedWith(typeElement, "javax.persistence.MappedSuperclass")) { // NOI18N
                for (Element element : typeElement.getEnclosedElements()) {
                    if (isAnnotatedWith(element, "javax.persistence.Id") || isAnnotatedWith(element, "javax.persistence.EmbeddedId")) {
                        idDetected = true;
                    }
                }
            }
            typeElement = getSuperclassTypeElement(typeElement);
        }
        if (!idDetected) {
            return false;//
        } else {
            return true;
        }
    }

    public static ExecutableElement getIdGetter(final boolean isFieldAccess, final TypeElement typeElement) {
        ExecutableElement[] methods = JavaSourceParserUtil.getMethods(typeElement);
        for (ExecutableElement method : methods) {
            String methodName = method.getSimpleName().toString();
            if (methodName.startsWith("get")) {
                Element element = isFieldAccess ? JavaSourceParserUtil.guessField(method) : method;
                if (element != null) {
                    if (JavaSourceParserUtil.isAnnotatedWith(element, "javax.persistence.Id") || JavaSourceParserUtil.isAnnotatedWith(element, "javax.persistence.EmbeddedId")) {
                        return method;
                    }
                }
            }
        }
        Logger.getLogger(JavaSourceParserUtil.class.getName()).log(Level.WARNING, "Cannot find ID getter in class: {0}", typeElement.getQualifiedName());
        return null;
    }

    public static boolean isGenerated(ExecutableElement method, boolean isFieldAccess) {
        Element element = isFieldAccess ? JavaSourceParserUtil.guessField(method) : method;
        if (element != null) {
            if (JavaSourceParserUtil.isAnnotatedWith(element, "javax.persistence.GeneratedValue")) { // NOI18N
                return true;
            }
        }
        return false;
    }

    public static boolean exceptionsThrownIncludes(WorkingCopy workingCopy, String fqClass, String methodName, List<String> formalParamFqTypes, String exceptionFqClassMaybeIncluded) {
        List<String> exceptionsThrown = getExceptionsThrown(workingCopy, fqClass, methodName, formalParamFqTypes);
        for (String exception : exceptionsThrown) {
            if (exceptionFqClassMaybeIncluded.equals(exception)) {
                return true;
            }
        }
        return false;
    }

    public static List<String> getExceptionsThrown(WorkingCopy workingCopy, String fqClass, String methodName, List<String> formalParamFqTypes) {
        if (formalParamFqTypes == null) {
            formalParamFqTypes = Collections.<String>emptyList();
        }
        ExecutableElement desiredMethodElement = null;
        TypeElement suppliedTypeElement = workingCopy.getElements().getTypeElement(fqClass);
        TypeElement typeElement = suppliedTypeElement;
        whileloop:
        while (typeElement != null) {
            for (ExecutableElement methodElement : ElementFilter.methodsIn(typeElement.getEnclosedElements())) {
                if (methodElement.getSimpleName().contentEquals(methodName)) {
                    List<? extends VariableElement> formalParamElements = methodElement.getParameters();
                    //for now, just check sizes
                    if (formalParamElements.size() == formalParamFqTypes.size()) {
                        desiredMethodElement = methodElement;
                        break whileloop;
                    }
                }
            }
            typeElement = getSuperclassTypeElement(typeElement);
        }
        if (desiredMethodElement == null) {
            throw new IllegalArgumentException("Could not find " + methodName + " in " + fqClass);
        }
        List<String> result = new ArrayList<String>();
        List<? extends TypeMirror> thrownTypes = desiredMethodElement.getThrownTypes();
        for (TypeMirror thrownType : thrownTypes) {
            if (thrownType.getKind() == TypeKind.DECLARED) {
                DeclaredType thrownDeclaredType = (DeclaredType) thrownType;
                TypeElement thrownElement = (TypeElement) thrownDeclaredType.asElement();
                String thrownFqClass = thrownElement.getQualifiedName().toString();
                result.add(thrownFqClass);
            } else {
                result.add(null);
            }
        }
        return result;
    }

    /**
     * Returns all methods in class and its super classes which are entity
     * classes or mapped superclasses.
     */
//    public static ExecutableElement[] getEntityMethods(TypeElement entityTypeElement) {
//        List<ExecutableElement> result = new LinkedList<ExecutableElement>();
//        TypeElement typeElement = entityTypeElement;
//        while (typeElement != null) {
//            if (isAnnotatedWith(typeElement, "javax.persistence.Entity") || isAnnotatedWith(typeElement, "javax.persistence.MappedSuperclass")) { // NOI18N
//                result.addAll(ElementFilter.methodsIn(typeElement.getEnclosedElements()));
//            }
//            typeElement = getSuperclassTypeElement(typeElement);
//        }
//        return result.toArray(new ExecutableElement[result.size()]);
//    }
    public static ExecutableElement[] getMethods(TypeElement typeElement) {
        List<ExecutableElement> result = new LinkedList<ExecutableElement>();
        result.addAll(ElementFilter.methodsIn(typeElement.getEnclosedElements()));
        return result.toArray(new ExecutableElement[result.size()]);
    }

    public static VariableElement[] getFields(TypeElement typeElement) {
        List<VariableElement> result = new LinkedList<VariableElement>();
        result.addAll(ElementFilter.fieldsIn(typeElement.getEnclosedElements()));
        return result.toArray(new VariableElement[result.size()]);
    }

    public static VariableElement guessField(ExecutableElement getter) {
        String name = getter.getSimpleName().toString().substring(3);
        String guessFieldName = name.substring(0, 1).toLowerCase() + name.substring(1);
        TypeElement typeElement = (TypeElement) getter.getEnclosingElement();
        for (VariableElement variableElement : ElementFilter.fieldsIn(typeElement.getEnclosedElements())) {
            if (variableElement.getSimpleName().contentEquals(guessFieldName)) {
                return variableElement;
            }
        }
        Logger.getLogger(JavaSourceParserUtil.class.getName()).log(Level.WARNING, "Cannot detect the field associated with property: {0}", guessFieldName);
        return null;
    }

    /**
     * TODO: actually it's guess setter from setter, need to review if it's a
     * problem of expected
     *
     * @param setter
     * @return
     */
    public static VariableElement guessGetter(ExecutableElement setter) {
        String name = setter.getSimpleName().toString().substring(3);
        String guessGetterName = "set" + name;
        TypeElement typeElement = (TypeElement) setter.getEnclosingElement();
        for (VariableElement variableElement : ElementFilter.fieldsIn(typeElement.getEnclosedElements())) {
            if (variableElement.getSimpleName().contentEquals(guessGetterName)) {
                return variableElement;
            }
        }
        Logger.getLogger(JavaSourceParserUtil.class.getName()).log(Level.INFO, "Cannot detect setter associated with getter: {0}", guessGetterName);
        return null;
    }

    public static class TypeInfo {

        private String rawType;
        private TypeInfo[] declaredTypeParameters;

        public String getRawType() {
            return rawType;
        }

        public TypeInfo[] getDeclaredTypeParameters() {
            return declaredTypeParameters;
        }

        public TypeInfo(String rawType) {
            if (rawType == null) {
                throw new IllegalArgumentException();
            }
            this.rawType = rawType;
        }

        public TypeInfo(String rawType, TypeInfo[] declaredTypeParameters) {
            if (rawType == null) {
                throw new IllegalArgumentException();
            }
            this.rawType = rawType;
            if (declaredTypeParameters == null || declaredTypeParameters.length == 0) {
                return;
            }
            this.declaredTypeParameters = declaredTypeParameters;
        }

        public TypeInfo(String rawType, String[] declaredTypeParamStrings) {
            if (rawType == null) {
                throw new IllegalArgumentException();
            }
            this.rawType = rawType;
            if (declaredTypeParamStrings == null || declaredTypeParamStrings.length == 0) {
                return;
            }
            this.declaredTypeParameters = TypeInfo.fromStrings(declaredTypeParamStrings);
        }

        public static TypeInfo[] fromStrings(String[] strings) {
            if (strings == null || strings.length == 0) {
                return null;
            }
            TypeInfo[] typeInfos = new TypeInfo[strings.length];
            for (int i = 0; i < strings.length; i++) {
                typeInfos[i] = new TypeInfo(strings[i]);
            }
            return typeInfos;
        }
    }

//    private static String getPersistenceVersion(Project project) throws IOException {
//        String version = Persistence.VERSION_1_0;
//        PersistenceScope persistenceScopes[] = PersistenceUtils.getPersistenceScopes(project);
//        if (persistenceScopes.length > 0) {
//            FileObject persXml = persistenceScopes[0].getPersistenceXml();
//            if (persXml != null) {
//                Persistence persistence = PersistenceMetadata.getDefault().getRoot(persXml);
//                version = persistence.getVersion();
//            }
//        }
//        return version;
//    }
//
//    static boolean isId(ExecutableElement method, boolean isFieldAccess) {
//        Element element = isFieldAccess ? JavaSourceParserUtil.guessField(method) : method;
//        if (element != null) {
//            if (JavaSourceParserUtil.isAnnotatedWith(element, "javax.persistence.Id") || JavaSourceParserUtil.isAnnotatedWith(element, "javax.persistence.EmbeddedId")) { // NOI18N
//                return true;
//            }
//        }
//        return false;
//    }
}


text:
const db = require('./database/queries/albums');

// middleware for database logic

module.exports = {
  get: db.getAlbums,
  getById: db.getAlbumByID
};

redpajama_set_name: RedPajamaGithub


text:
@interface PodsDummy_Pods_AddressBookKit_Tests : NSObject
@end
@implementation PodsDummy_Pods_AddressBookKit_Tests
@end


text:
@interface NUIObserver : NSObject

+ (void)addObserverTo:(id)object forKeyPath:(NSString *)keyPath selector:(SEL)selector;
+ (void)removeObserverFrom:(id)object forKeyPath:(NSString *)keyPath selector:(SEL)selector;

@end


text:
import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from 'react-native';
import {
    any,
    func,
    string,
} from 'prop-types';

class Prediction extends Component {
    static propTypes = {
        prediction: any,
        title: string,
        description: string,
        onPress: func.isRequired
    }

    constructor(props) {
        super(props);
    }

    render() {
        return (
            <TouchableOpacity onPress={this._handlePress}>
                <View style={style.item}>
                    <Text style={style.title}>{this.props.title}</Text>
                    <Text style={style.description}>{this.props.description}</Text>
                </View>
            </TouchableOpacity>
        );
    }

    _handlePress = () => {
        this.props.onPress(this.props.prediction);
    }
}

export const style = StyleSheet.create({
    item: {
        borderTopColor: 'rgba(0, 0, 0, 0.2)',
        borderTopWidth: StyleSheet.hairlineWidth,
        paddingBottom: 10,
        paddingLeft: 10,
        paddingRight: 10,
        paddingTop: 10,
    },

    description: {
        color: 'grey'
    },
});

export default Prediction;


text:
/** @file
@brief Header file describing the OSVR direct-to-device rendering interface for
D3D

@date 2015

@author
Sensics, Inc.
<http://sensics.com/osvr>
*/

// Copyright 2015 Sensics, Inc.
//
// 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.

#pragma once
#include "RenderManagerD3DBase.h"
#include <SDL.h>

namespace osvr {
namespace renderkit {

    class RenderManagerD3D11 : public RenderManagerD3D11Base {
      public:
        virtual ~RenderManagerD3D11();

        // Opens the D3D renderer we're going to use.
        OpenResults OpenDisplay() override;

        bool OSVR_RENDERMANAGER_EXPORT
          GetTimingInfo(size_t whichEye, OSVR_RenderTimingInfo& info) override;

      protected:
        /// Construct a D3D RenderManager.
        RenderManagerD3D11(
            OSVR_ClientContext context,
            ConstructorParameters p);

        // Classes and structures needed to do our rendering.
        class DisplayInfo {
          public:
            /// @todo Release these pointers in destructor
            SDL_Window* m_window = nullptr; ///< SDL window pointer
            HWND m_rawWindow = nullptr; ///< Raw Windows handle for the window
            IDXGISwapChain* m_swapChain =
                nullptr; ///< Pointer to the swap chain to use
            ID3D11Texture2D* m_renderTarget =
                nullptr; ///< Pointer to render target texture
            ID3D11RenderTargetView* m_renderTargetView =
                nullptr; ///< Pointer to our render target view
        };
        std::vector<DisplayInfo> m_displays;

        //===================================================================
        // Overloaded render functions from the base class.
        bool RenderFrameInitialize() override { return true; }
        bool RenderDisplayInitialize(size_t display) override { return true; }
        bool RenderEyeFinalize(size_t eye) override { return true; }
        bool RenderDisplayFinalize(size_t display) override { return true; }

        bool PresentDisplayInitialize(size_t display) override;
        bool PresentDisplayFinalize(size_t display) override;
        bool PresentFrameFinalize() override;

        bool SolidColorEye(size_t eye, const RGBColorf &color) override;

        friend RenderManager OSVR_RENDERMANAGER_EXPORT*
        createRenderManager(OSVR_ClientContext context,
                            const std::string& renderLibraryName,
                            GraphicsLibrary graphicsLibrary);

      private:
    };

} // namespace renderkit
} // namespace osvr


text:
package com.uip;

public class Principal3 {

    public static void main(String[] args) {
	// write your code here
    }
}


text:
<?php

namespace app\widgets;

use yii\base\Widget;

class FastSearch extends Widget
{

    public function run()
    {
        return $this->render('fastsearch');
    }
}


text:
package com.kotcrab.vis.ui.util;

import com.kotcrab.vis.ui.InputValidator;
import com.kotcrab.vis.ui.util.dialog.DialogUtils;
import com.kotcrab.vis.ui.widget.VisValidableTextField;

/**
 * Provides premade validators that can be used with {@link VisValidableTextField} or {@link DialogUtils} when displaying
 * input dialogs
 * @author Kotcrab
 */
public class Validators {
	public static final IntegerValidator INTEGERS = new IntegerValidator();
	public static final FloatValidator FLOATS = new FloatValidator();

	/** Validates whether input is a integer number */
	public static class IntegerValidator implements InputValidator {
		@Override
		public boolean validateInput (String input) {
			try {
				Integer.parseInt(input);
				return true;
			} catch (NumberFormatException e) {
				return false;
			}
		}
	}

	/** Validates whether input is a float number */
	public static class FloatValidator implements InputValidator {
		@Override
		public boolean validateInput (String input) {
			try {
				Float.parseFloat(input);
				return true;
			} catch (NumberFormatException e) {
				return false;
			}
		}
	}

	/** Validates whether input is lesser (alternatively lesser or equal) than provided number */
	public static class LesserThanValidator implements InputValidator {
		private float lesserThan;
		private boolean equals;

		public LesserThanValidator (float lesserThan) {
			this.lesserThan = lesserThan;
		}

		public LesserThanValidator (float lesserThan, boolean inputCanBeEqual) {
			this.lesserThan = lesserThan;
			this.equals = inputCanBeEqual;
		}

		@Override
		public boolean validateInput (String input) {
			try {
				float value = Float.valueOf(input);
				return equals ? value <= lesserThan : value < lesserThan;
			} catch (NumberFormatException ex) {
				return false;
			}
		}
	}

	/** Validates whether input is geater (alternatively greater or equal) than provided number */
	public static class GreaterThanValidator implements InputValidator {
		private float greaterThan;
		private boolean equals;

		public GreaterThanValidator (float greaterThan) {
			this.greaterThan = greaterThan;
		}

		public GreaterThanValidator (float greaterThan, boolean inputCanBeEqual) {
			this.greaterThan = greaterThan;
			this.equals = inputCanBeEqual;
		}

		@Override
		public boolean validateInput (String input) {
			try {
				float value = Float.valueOf(input);
				return equals ? value >= greaterThan : value > greaterThan;
			} catch (NumberFormatException ex) {
				return false;
			}
		}
	}
}


text:
from django.db import models

class Foo(models.Model):
    attribute1 = models.IntegerField()

class Bar(models.Model):
    attribute2 = models.IntegerField()


text:
/*
 * Copyright 2015 Cloudius Systems
 */
#include <cmath>
#include "core/reactor.hh"
#include "core/app-template.hh"
#include "rpc/rpc.hh"
#include "core/sleep.hh"

struct serializer {
};

template <typename T, typename Output>
inline
void write_arithmetic_type(Output& out, T v) {
    static_assert(std::is_arithmetic<T>::value, "must be arithmetic type");
    return out.write(reinterpret_cast<const char*>(&v), sizeof(T));
}

template <typename T, typename Input>
inline
T read_arithmetic_type(Input& in) {
    static_assert(std::is_arithmetic<T>::value, "must be arithmetic type");
    T v;
    in.read(reinterpret_cast<char*>(&v), sizeof(T));
    return v;
}

template <typename Output>
inline void write(serializer, Output& output, int32_t v) { return write_arithmetic_type(output, v); }
template <typename Output>
inline void write(serializer, Output& output, uint32_t v) { return write_arithmetic_type(output, v); }
template <typename Output>
inline void write(serializer, Output& output, int64_t v) { return write_arithmetic_type(output, v); }
template <typename Output>
inline void write(serializer, Output& output, uint64_t v) { return write_arithmetic_type(output, v); }
template <typename Output>
inline void write(serializer, Output& output, double v) { return write_arithmetic_type(output, v); }
template <typename Input>
inline int32_t read(serializer, Input& input, rpc::type<int32_t>) { return read_arithmetic_type<int32_t>(input); }
template <typename Input>
inline uint32_t read(serializer, Input& input, rpc::type<uint32_t>) { return read_arithmetic_type<uint32_t>(input); }
template <typename Input>
inline uint64_t read(serializer, Input& input, rpc::type<uint64_t>) { return read_arithmetic_type<uint64_t>(input); }
template <typename Input>
inline uint64_t read(serializer, Input& input, rpc::type<int64_t>) { return read_arithmetic_type<int64_t>(input); }
template <typename Input>
inline double read(serializer, Input& input, rpc::type<double>) { return read_arithmetic_type<double>(input); }

template <typename Output>
inline void write(serializer, Output& out, const sstring& v) {
    write(out, v.size());
    out.write(v.c_str(), v.size());
}

template <typename Input>
inline sstring read(serializer, Input& in) {
    auto size = read<size_t>(in);
    sstring ret(sstring::initialized_later(), size);
    in.read(ret.begin(), size);
    return ret;
}

namespace bpo = boost::program_options;
using namespace std::chrono_literals;

int main(int ac, char** av) {
    app_template app;
    app.add_options()
                    ("port", bpo::value<uint16_t>()->default_value(10000), "RPC server port")
                    ("server", bpo::value<std::string>(), "Server address");
    std::cout << "start ";
    rpc::protocol<serializer> myrpc(serializer{});
    static std::unique_ptr<rpc::protocol<serializer>::server> server;
    static std::unique_ptr<rpc::protocol<serializer>::client> client;
    static double x = 30.0;

    return app.run_deprecated(ac, av, [&] {
        auto&& config = app.configuration();
        uint16_t port = config["port"].as<uint16_t>();
        auto test1 = myrpc.register_handler(1, [x = 0](int i) mutable { print("test1 count %d got %d\n", ++x, i); });
        auto test2 = myrpc.register_handler(2, [](int a, int b){ print("test2 got %d %d\n", a, b); return make_ready_future<int>(a+b); });
        auto test3 = myrpc.register_handler(3, [](double x){ print("test3 got %f\n", x); return std::make_unique<double>(sin(x)); });
        auto test4 = myrpc.register_handler(4, [](){ print("test4 throw!\n"); throw std::runtime_error("exception!"); });
        auto test5 = myrpc.register_handler(5, [](){ print("test5 no wait\n"); return rpc::no_wait; });
        auto test6 = myrpc.register_handler(6, [](const rpc::client_info& info, int x){ print("test6 client %s, %d\n", inet_ntoa(info.addr.as_posix_sockaddr_in().sin_addr), x); });
        auto test8 = myrpc.register_handler(8, [](){ print("test8 sleep for 5 sec\n"); return sleep(2s); });

        if (config.count("server")) {
            std::cout << "client" << std::endl;
            auto test7 = myrpc.make_client<long (long a, long b)>(7);

            client = std::make_unique<rpc::protocol<serializer>::client>(myrpc, ipv4_addr{config["server"].as<std::string>()});

            auto f = test8(*client, 1500ms).then_wrapped([](future<> f) {
                try {
                    f.get();
                    printf("test8 should not get here!\n");
                } catch (rpc::timeout_error) {
                    printf("test8 timeout!\n");
                }
            });
            for (auto i = 0; i < 100; i++) {
                print("iteration=%d\n", i);
                test1(*client, 5).then([] (){ print("test1 ended\n");});
                test2(*client, 1, 2).then([] (int r) { print("test2 got %d\n", r); });
                test3(*client, x).then([](double x) { print("sin=%f\n", x); });
                test4(*client).then_wrapped([](future<> f) {
                    try {
                        f.get();
                        printf("test4 your should not see this!");
                    } catch (std::runtime_error& x){
                        print("test4 %s\n", x.what());
                    }
                });
                test5(*client).then([] { print("test5 no wait ended\n"); });
                test6(*client, 1).then([] { print("test6 ended\n"); });
                test7(*client, 5, 6).then([] (long r) { print("test7 got %ld\n", r); });
            }
            f.finally([] {
                sleep(1s).then([] {
                    client->stop().then([] {
                        engine().exit(0);
                    });
                });
            });
        } else {
            std::cout << "server on port " << port << std::endl;
            myrpc.register_handler(7, [](long a, long b) mutable {
                auto p = make_lw_shared<promise<>>();
                auto t = make_lw_shared<timer<>>();
                print("test7 got %ld %ld\n", a, b);
                auto f = p->get_future().then([a, b, t] {
                    print("test7 calc res\n");
                    return a - b;
                });
                t->set_callback([p = std::move(p)] () mutable { p->set_value(); });
                t->arm(1s);
                return f;
            });
            server = std::make_unique<rpc::protocol<serializer>::server>(myrpc, ipv4_addr{port});
        }
    });

}


text:
* Bug fixes
* Documentation fixes

For new feature additions (e.g., new graphs and calculators), we are currently not planning to accept new feature pull requests into the MediaPipe repository. Instead, we like to get contributors to create their own repositories of the new feature and list it at [Awesome MediaPipe](https://mediapipe.page.link/awesome-mediapipe). This will allow contributors to more quickly get their code out to the community.

Before sending your pull requests, make sure you followed this list.

- Read [contributing guidelines](CONTRIBUTING.md).
- Read [Code of Conduct](CODE_OF_CONDUCT.md).
- Ensure you have signed the [Contributor License Agreement (CLA)](https://cla.developers.google.com/).

## How to become a contributor and submit your own code

### Contributor License Agreements

We'd love to accept your patches! Before we can take them, we have to jump a couple of legal hurdles.

Please fill out either the individual or corporate Contributor License Agreement (CLA).

  * If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an [individual CLA](https://code.google.com/legal/individual-cla-v1.0.html).
  * If you work for a company that wants to allow you to contribute your work, then you'll need to sign a [corporate CLA](https://code.google.com/legal/corporate-cla-v1.0.html).

Follow either of the two links above to access the appropriate CLA and instructions for how to sign and return it. Once we receive it, we'll be able to accept your pull requests.

***NOTE***: Only original source code from you and other people that have signed the CLA can be accepted into the main repository.

### Contributing code

If you have bug fixes and documentation fixes to MediaPipe, send us your pull requests! For those
just getting started, GitHub has a [howto](https://help.github.com/articles/using-pull-requests/).

MediaPipe team members will be assigned to review your pull requests. Once the bug/documentation fixes are verified, a MediaPipe team member will acknowledge your contribution in the pull request comments, manually merge the fixes into our internal codebase upstream, and apply the `to be closed` label to the pull request. These fixes will later be pushed to GitHub in the next release, and a MediaPipe team member will then close the pull request.


text:
/*
 * Created by SharpDevelop.
 * User: BlueCobold
 * Date: 06.06.2015
 * Time: 11:41
 *
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Windows.Forms;

namespace AdbInput
{
	/// <summary>
	/// Class with program entry point.
	/// </summary>
	internal sealed class Program
	{
		/// <summary>
		/// Program entry point.
		/// </summary>
		[STAThread]
		private static void Main(string[] args)
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			Application.Run(new MainForm());
		}

	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 The Android Open Source Project

     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 name must be unique so suffix with "tests" so package loader doesn't ignore us -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.apis.tests">

    <!-- We add an application tag here just so that we can indicate that
         this package needs to link against the android.test library,
         which is needed when building test cases. -->
    <application>
        <uses-library android:name="android.test.runner" />
    </application>

    <!--
    This declares that this app uses the instrumentation test runner targeting
    the package of com.example.android.apis.  To run the tests use the command:
    "adb shell am instrument -w com.example.android.apis.tests/android.test.InstrumentationTestRunner"
    -->
    <instrumentation android:name="android.test.InstrumentationTestRunner"
                     android:targetPackage="com.example.android.apis"
                     android:label="Tests for Api Demos."/>

</manifest>


text: This document has moved to <https://www.algolia.com/doc/offline-mode>.


text:
@class RootViewController;

@class DetailViewController;

@class LoginViewController;

@interface octochefAppDelegate : NSObject <UIApplicationDelegate> {

}

@property (nonatomic, retain) IBOutlet UIWindow *window;

@property (nonatomic, retain) IBOutlet UISplitViewController *splitViewController;

@property (nonatomic, retain) IBOutlet RootViewController *rootViewController;

@property (nonatomic, retain) IBOutlet DetailViewController *detailViewController;

@end