text:
package fr.adrienbrault.idea.symfony2plugin.doctrine;

import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.containers.ContainerUtil;
import com.jetbrains.php.PhpIndex;
import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment;
import com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocParamTag;
import com.jetbrains.php.lang.psi.elements.*;
import com.jetbrains.php.lang.psi.elements.impl.PhpNamedElementImpl;
import fr.adrienbrault.idea.symfony2plugin.doctrine.component.DocumentNamespacesParser;
import fr.adrienbrault.idea.symfony2plugin.doctrine.component.EntityNamesServiceParser;
import fr.adrienbrault.idea.symfony2plugin.doctrine.dict.DoctrineModelField;
import fr.adrienbrault.idea.symfony2plugin.doctrine.dict.DoctrineTypes;
import fr.adrienbrault.idea.symfony2plugin.doctrine.metadata.dict.DoctrineMetadataModel;
import fr.adrienbrault.idea.symfony2plugin.doctrine.metadata.util.DoctrineMetadataUtil;
import fr.adrienbrault.idea.symfony2plugin.extension.DoctrineModelProvider;
import fr.adrienbrault.idea.symfony2plugin.extension.DoctrineModelProviderParameter;
import fr.adrienbrault.idea.symfony2plugin.util.*;
import fr.adrienbrault.idea.symfony2plugin.util.dict.DoctrineModel;
import fr.adrienbrault.idea.symfony2plugin.util.dict.SymfonyBundle;
import fr.adrienbrault.idea.symfony2plugin.util.service.ServiceXmlParserFactory;
import fr.adrienbrault.idea.symfony2plugin.util.yaml.YamlHelper;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.yaml.psi.*;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Daniel Espendiller <daniel@espendiller.net>
 */
public class EntityHelper {

    public static final ExtensionPointName<DoctrineModelProvider> MODEL_POINT_NAME = new ExtensionPointName<>("fr.adrienbrault.idea.symfony2plugin.extension.DoctrineModelProvider");

    final public static String[] ANNOTATION_FIELDS = new String[] {
        "\\Doctrine\\ORM\\Mapping\\Column",
        "\\Doctrine\\ORM\\Mapping\\OneToOne",
        "\\Doctrine\\ORM\\Mapping\\ManyToOne",
        "\\Doctrine\\ORM\\Mapping\\OneToMany",
        "\\Doctrine\\ORM\\Mapping\\ManyToMany",
    };

    final public static Set<String> RELATIONS = new HashSet<>(Arrays.asList("manytoone", "manytomany", "onetoone", "onetomany"));

    /**
     * Resolve shortcut and namespaces classes for current phpclass and attached modelname
     */
    @Nullable
    public static PhpClass getAnnotationRepositoryClass(@NotNull PhpClass phpClass, @NotNull String modelName) {

        // \ns\Class fine we dont need to resolve classname we are in global context
        if(modelName.startsWith("\\")) {
            return PhpElementsUtil.getClassInterface(phpClass.getProject(), modelName);
        }

        // repositoryClass="Classname" pre-append namespace here
        PhpNamedElementImpl phpNamedElementImpl = PsiTreeUtil.getParentOfType(phpClass, PhpNamedElementImpl.class);
        if(phpNamedElementImpl != null) {
            String className = phpNamedElementImpl.getFQN() + "\\" +  modelName;
            PhpClass namespaceClass = PhpElementsUtil.getClassInterface(phpClass.getProject(), className);
            if(namespaceClass != null) {
                return namespaceClass;
            }
        }

        // repositoryClass="Classname\Test" trailing backslash can be stripped
        return  PhpElementsUtil.getClassInterface(phpClass.getProject(), modelName);
    }

    /**
     * Search for a repository class of a model
     *
     * @param project Current project
     * @param shortcutName "\Class\Name" or "FooBundle:Name"
     */
    @Nullable
    public static PhpClass getEntityRepositoryClass(@NotNull Project project, @NotNull String shortcutName) {

        PhpClass phpClass = resolveShortcutName(project, shortcutName);
        if(phpClass == null) {
            return null;
        }

        String presentableFQN = phpClass.getPresentableFQN();
        PhpClass classRepository = DoctrineMetadataUtil.getClassRepository(project, presentableFQN);
        if(classRepository != null) {
            return classRepository;
        }

        // @TODO: deprecated code
        // search on annotations
        PhpDocComment docAnnotation = phpClass.getDocComment();
        if(docAnnotation != null) {

            // search for repositoryClass="Foo\Bar\RegisterRepository"
            // @MongoDB\Document; @ORM\Entity
            String docAnnotationText = docAnnotation.getText();
            Matcher matcher = Pattern.compile("repositoryClass[\\s]*=[\\s]*[\"|'](.*)[\"|']").matcher(docAnnotationText);
            if (matcher.find()) {
                return getAnnotationRepositoryClass(phpClass, matcher.group(1));
            }
        }

        SymfonyBundle symfonyBundle = new SymfonyBundleUtil(PhpIndex.getInstance(project)).getContainingBundle(phpClass);
        if(symfonyBundle != null) {
            PhpClass repositoryClass = getEntityRepositoryClass(project, symfonyBundle, presentableFQN);
            if(repositoryClass != null) {
                return repositoryClass;
            }
        }

        // old __CLASS__ Repository type
        // @TODO remove this fallback when we implemented all cases
        return resolveShortcutName(project, shortcutName + "Repository");
    }

    public static List<DoctrineModelField> getModelFieldsSet(YAMLKeyValue yamlKeyValue) {

        List<DoctrineModelField> fields = new ArrayList<>();

        for(Map.Entry<String, YAMLKeyValue> entry: getYamlModelFieldKeyValues(yamlKeyValue).entrySet()) {
            List<DoctrineModelField> fieldSet = getYamlDoctrineFields(entry.getKey(), entry.getValue());
            if(fieldSet != null) {
                fields.addAll(fieldSet);
            }
        }

        return fields;
    }

    @Nullable
    public static List<DoctrineModelField> getYamlDoctrineFields(String keyName, @Nullable YAMLKeyValue yamlKeyValue) {

        if(yamlKeyValue == null) {
            return null;
        }

        PsiElement yamlCompoundValue = yamlKeyValue.getValue();
        if(yamlCompoundValue == null) {
            return null;
        }

        List<DoctrineModelField> modelFields = new ArrayList<>();
        for(YAMLKeyValue yamlKey: PsiTreeUtil.getChildrenOfTypeAsList(yamlCompoundValue, YAMLKeyValue.class)) {
            String fieldName = YamlHelper.getYamlKeyName(yamlKey);
            if(fieldName != null) {
                DoctrineModelField modelField = new DoctrineModelField(fieldName);
                modelField.addTarget(yamlKey);
                attachYamlFieldTypeName(keyName, modelField, yamlKey);
                modelFields.add(modelField);
            }
        }

        return modelFields;
    }

    public static void attachYamlFieldTypeName(String keyName, DoctrineModelField doctrineModelField, YAMLKeyValue yamlKeyValue) {

        if("fields".equals(keyName) || "id".equals(keyName)) {

            YAMLKeyValue yamlType = YamlHelper.getYamlKeyValue(yamlKeyValue, "type");
            if(yamlType != null) {
                doctrineModelField.setTypeName(yamlType.getValueText());
            }

            YAMLKeyValue yamlColumn = YamlHelper.getYamlKeyValue(yamlKeyValue, "column");
            if(yamlColumn != null) {
                doctrineModelField.setColumn(yamlColumn.getValueText());
            }

            return;
        }

        if(RELATIONS.contains(keyName.toLowerCase())) {
            YAMLKeyValue targetEntity = YamlHelper.getYamlKeyValue(yamlKeyValue, "targetEntity");
            if(targetEntity != null) {
                doctrineModelField.setRelationType(keyName);
                doctrineModelField.setRelation(getOrmClass(yamlKeyValue.getContainingFile(), targetEntity.getValueText()));
            }
        }

    }

    @NotNull
    public static String getOrmClass(@NotNull PsiFile psiFile, @NotNull String className) {

        // force global namespace not need to search for class
        if(className.startsWith("\\")) {
            return className;
        }

        String entityName = null;

        // espend\Doctrine\ModelBundle\Entity\Bike:
        // ...
        // targetEntity: Foo
        if(psiFile instanceof YAMLFile) {
            YAMLDocument yamlDocument = PsiTreeUtil.getChildOfType(psiFile, YAMLDocument.class);
            if(yamlDocument != null) {
                YAMLKeyValue entityKeyValue = PsiTreeUtil.getChildOfType(yamlDocument, YAMLKeyValue.class);
                if(entityKeyValue != null) {
                    entityName = entityKeyValue.getKeyText();
                }
            }
        } else if(psiFile instanceof XmlFile) {

            XmlTag rootTag = ((XmlFile) psiFile).getRootTag();
            if(rootTag != null) {
                XmlTag entity = rootTag.findFirstSubTag("entity");
                if(entity != null) {
                    String name = entity.getAttributeValue("name");
                    if(org.apache.commons.lang.StringUtils.isBlank(name)) {
                        entityName = name;
                    }
                }
            }
        }

        if(entityName == null) {
            return className;
        }

        // trim class name
        int lastBackSlash = entityName.lastIndexOf("\\");
        if(lastBackSlash > 0) {
            String fqnClass = entityName.substring(0, lastBackSlash + 1) + className;
            if(PhpElementsUtil.getClass(psiFile.getProject(), fqnClass) != null) {
                return fqnClass;
            }
        }

        return className;
    }

    @NotNull
    public static Map<String, YAMLKeyValue> getYamlModelFieldKeyValues(YAMLKeyValue yamlKeyValue) {
        Map<String, YAMLKeyValue> keyValueCollection = new HashMap<>();

        for(String fieldMap: new String[] { "id", "fields", "manyToOne", "oneToOne", "manyToMany", "oneToMany"}) {
            YAMLKeyValue targetYamlKeyValue = YamlHelper.getYamlKeyValue(yamlKeyValue, fieldMap, true);
            if(targetYamlKeyValue != null) {
                keyValueCollection.put(fieldMap, targetYamlKeyValue);
            }
        }

        return keyValueCollection;
    }

    @NotNull
    public static PsiElement[] getModelFieldTargets(@NotNull PhpClass phpClass,@NotNull String fieldName) {

        Collection<PsiElement> psiElements = new ArrayList<>();

        DoctrineMetadataModel modelFields = DoctrineMetadataUtil.getModelFields(phpClass.getProject(), phpClass.getPresentableFQN());
        if(modelFields != null) {
            for (DoctrineModelField field : modelFields.getFields()) {
                if(field.getName().equals(fieldName) && field.getTargets().size() > 0) {
                    return field.getTargets().toArray(new PsiElement[psiElements.size()]);
                }
            }
        }

        // @TODO: deprecated
        PsiFile psiFile = EntityHelper.getModelConfigFile(phpClass);

        if(psiFile instanceof YAMLFile) {
            // @TODO: migrate to getEntityFields()
            YAMLValue topLevelValue = ((YAMLFile) psiFile).getDocuments().get(0).getTopLevelValue();
            if(topLevelValue instanceof YAMLMapping) {
                Collection<YAMLKeyValue> keyValues = ((YAMLMapping) topLevelValue).getKeyValues();
                if(keyValues.size() > 0) {
                    for(YAMLKeyValue yamlKeyValue: EntityHelper.getYamlModelFieldKeyValues(keyValues.iterator().next()).values()) {
                        ContainerUtil.addIfNotNull(psiElements, YamlHelper.getYamlKeyValue(yamlKeyValue, "name"));
                    }
                }
            }
        }

        if(psiFile instanceof XmlFile) {
            for (DoctrineModelField field : getEntityFields((XmlFile) psiFile)) {
                if(field.getName().equals(fieldName)) {
                    psiElements.addAll(field.getTargets());
                }
            }
        }

        // provide fallback on annotations
        // @TODO: better detect annotation switch; yaml and annotation are valid; need deps on annotation plugin
        PhpDocComment docComment = phpClass.getDocComment();
        if(docComment != null) {
            if(docComment.getText().contains("Entity") || docComment.getText().contains("@ORM") || docComment.getText().contains("repositoryClass")) {
                for(Field field: phpClass.getFields()) {
                    if(!field.isConstant() && fieldName.equals(field.getName())) {
                        psiElements.add(field);
                    }
                }
            }
        }

        String methodName = "get" + StringUtils.camelize(fieldName.toLowerCase(), false);
        Method method = phpClass.findMethodByName(methodName);
        if(method != null) {
            psiElements.add(method);
        }

        return psiElements.toArray(new PsiElement[psiElements.size()]);

    }

    @Nullable
    private static PsiFile getEntityMetadataFile(@NotNull Project project, @NotNull SymfonyBundle symfonyBundleUtil, @NotNull String className, @NotNull String modelShortcut) {

        for(String s: new String[] {"yml", "yaml", "xml"}) {

            String entityFile = "Resources/config/doctrine/" + className + String.format(".%s.%s", modelShortcut, s);
            VirtualFile virtualFile = symfonyBundleUtil.getRelative(entityFile);
            if(virtualFile != null) {
                PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
                if(psiFile != null) {
                    return psiFile;
                }
            }

        }

        return null;
    }

    @Nullable
    public static PsiFile getModelConfigFile(@NotNull PhpClass phpClass) {

        // new code
        String presentableFQN = phpClass.getPresentableFQN();
        Collection<VirtualFile> metadataFiles = DoctrineMetadataUtil.findMetadataFiles(phpClass.getProject(), presentableFQN);
        if(metadataFiles.size() > 0) {
            PsiFile file = PsiManager.getInstance(phpClass.getProject()).findFile(metadataFiles.iterator().next());
            if(file != null) {
                return file;
            }
        }

        // @TODO: deprecated code
        SymfonyBundle symfonyBundle = new SymfonyBundleUtil(phpClass.getProject()).getContainingBundle(phpClass);
        if(symfonyBundle != null) {
            for(String modelShortcut: new String[] {"orm", "mongodb", "couchdb"}) {
                String className = phpClass.getName();

                int n = presentableFQN.indexOf("\\Entity\\");
                if(n > 0) {
                    className = presentableFQN.substring(n + 8).replace("\\", ".");
                }

                PsiFile entityMetadataFile = getEntityMetadataFile(phpClass.getProject(), symfonyBundle, className, modelShortcut);
                if(entityMetadataFile != null) {
                    return entityMetadataFile;
                }

            }
        }

        return null;
    }

    @NotNull
    public static Collection<DoctrineModelField> getModelFields(@NotNull PhpClass phpClass) {

        // new code
        String presentableFQN = phpClass.getPresentableFQN();
        DoctrineMetadataModel fields = DoctrineMetadataUtil.getModelFields(phpClass.getProject(), presentableFQN);
        if(fields != null) {
            return fields.getFields();
        }

        // @TODO: old deprecated code
        PsiFile psiFile = getModelConfigFile(phpClass);
        if(psiFile == null) {
            Collections.emptyList();
        }

        if(psiFile instanceof YAMLFile) {
            List<DoctrineModelField> modelFields = new ArrayList<>();

            PsiElement yamlDocument = psiFile.getFirstChild();
            if(yamlDocument instanceof YAMLDocument) {
                PsiElement arrayKeyValue = yamlDocument.getFirstChild();
                if(arrayKeyValue instanceof YAMLKeyValue) {

                    // first line is class name; check of we are right
                    String className = YamlHelper.getYamlKeyName(((YAMLKeyValue) arrayKeyValue));
                    if(PhpElementsUtil.isEqualClassName(phpClass, className)) {
                        modelFields.addAll(getModelFieldsSet((YAMLKeyValue) arrayKeyValue));
                    }

                }
            }

            return modelFields;
        }

        if(psiFile instanceof XmlFile) {
            return getEntityFields((XmlFile) psiFile);
        }

        // provide fallback on annotations
        List<DoctrineModelField> modelFields = new ArrayList<>();

        PhpDocComment docComment = phpClass.getDocComment();
        if(docComment != null) {
            if(AnnotationBackportUtil.hasReference(docComment, "\\Doctrine\\ORM\\Mapping\\Entity")) {
                for(Field field: phpClass.getFields()) {
                    if(!field.isConstant()) {
                        if(AnnotationBackportUtil.hasReference(field.getDocComment(), ANNOTATION_FIELDS)) {
                            DoctrineModelField modelField = new DoctrineModelField(field.getName());
                            attachAnnotationInformation(field, modelField.addTarget(field));
                            modelFields.add(modelField);
                        }
                    }
                }
            }
        }

        return modelFields;
    }

    @NotNull
    public static List<DoctrineModelField> getEntityFields(@NotNull XmlFile psiFile) {

        List<DoctrineModelField> modelFields = new ArrayList<>();

        XmlTag rootTag = psiFile.getRootTag();
        if(rootTag == null) {
            return Collections.emptyList();
        }

        final XmlTag entity = rootTag.findFirstSubTag("entity");
        if(entity == null) {
            return Collections.emptyList();
        }

        for (XmlTag xmlTag : new ArrayList<XmlTag>() {{
            addAll(Arrays.asList(entity.findSubTags("field")));
            addAll(Arrays.asList(entity.findSubTags("id")));
        }}) {

            String name = xmlTag.getAttributeValue("name");
            if(org.apache.commons.lang.StringUtils.isBlank(name)) {
                continue;
            }

            DoctrineModelField field = new DoctrineModelField(name);

            field.addTarget(xmlTag);

            String column = xmlTag.getAttributeValue("column");
            if(org.apache.commons.lang.StringUtils.isNotBlank(name)) {
                field.setColumn(column);
            }

            String type = xmlTag.getAttributeValue("type");
            if(org.apache.commons.lang.StringUtils.isNotBlank(type)) {
                field.setTypeName(type);
            }

            modelFields.add(field);
        }

        for(String s: new String[] {"one-to-one", "one-to-many", "many-to-many", "many-to-one"}) {
            for (XmlTag xmlTag : entity.findSubTags(s)) {

                String targetEntity = xmlTag.getAttributeValue("target-entity");
                if(targetEntity == null) {
                    continue;
                }

                String field = xmlTag.getAttributeValue("field");
                if(field == null) {
                    continue;
                }

                DoctrineModelField entityField = new DoctrineModelField(field);
                entityField.addTarget(xmlTag);

                // find namespace
                entityField.setRelation(getOrmClass(psiFile, targetEntity));

                entityField.setRelationType(StringUtils.camelize(s.replace("-", "_")));
                modelFields.add(entityField);
            }
        }

        return modelFields;
    }

    @Nullable
    private static PhpClass getEntityRepositoryClass(Project project, SymfonyBundle symfonyBundle, String classFqnName) {

        // some default bundle search path
        // Bundle/Resources/config/doctrine/Product.orm.yml
        // Bundle/Resources/config/doctrine/Product.mongodb.yml
        List<String[]> managerConfigs = new ArrayList<>();
        managerConfigs.add(new String[] { "Entity", "orm"});
        managerConfigs.add(new String[] { "Document", "mongodb"});

        for(String[] managerConfig: managerConfigs) {
            String entityName = classFqnName.substring(symfonyBundle.getNamespaceName().length() - 1);
            if(entityName.startsWith(managerConfig[0] + "\\")) {
                entityName =  entityName.substring((managerConfig[0] + "\\").length());
            }

            // entities in sub folder: 'Foo\Bar' -> 'Foo.Bar.orm.yml'
            String entityFile = "Resources/config/doctrine/" + entityName.replace("\\", ".") + String.format(".%s.yml", managerConfig[1]);
            VirtualFile virtualFile = symfonyBundle.getRelative(entityFile);
            if(virtualFile != null) {
                PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
                if(psiFile != null) {

                    // search for "repositoryClass: Foo\Bar\RegisterRepository" also provide quoted values
                    Matcher matcher = Pattern.compile("[\\s]*repositoryClass:[\\s]*[\"|']*(.*)[\"|']*").matcher(psiFile.getText());
                    if (matcher.find()) {
                        return PhpElementsUtil.getClass(PhpIndex.getInstance(project), matcher.group(1));
                    }

                    // we found entity config so no other check needed
                    return null;
                }

            }
        }

        return null;
    }

    @Nullable
    public static PhpClass resolveShortcutName(@NotNull Project project, @NotNull String shortcutName) {
        return resolveShortcutName(project, shortcutName, DoctrineTypes.Manager.ORM, DoctrineTypes.Manager.MONGO_DB, DoctrineTypes.Manager.COUCH_DB);
    }

    /**
     *
     * @param project PHPStorm projects
     * @param shortcutName name as MyBundle\Entity\Model or MyBundle:Model
     * @return null|PhpClass
     */
    @Nullable
    public static PhpClass resolveShortcutName(@NotNull Project project, @Nullable String shortcutName, DoctrineTypes.Manager... managers) {
        if(shortcutName == null) {
            return null;
        }

        // we dont need to resolve bundle name, use class name
        if (!shortcutName.contains(":")) {
            return PhpElementsUtil.getClassInterface(project, shortcutName);
        }

        // resolve:
        // MyBundle:Model -> MyBundle\Entity\Model
        // MyBundle:Folder\Model -> MyBundle\Entity\Folder\Model

        List<DoctrineTypes.Manager> managerList = Arrays.asList(managers);

        // collect entitymanager namespaces on bundle or container file
        Map<String, String> em = new HashMap<>();
        if(managerList.contains(DoctrineTypes.Manager.ORM)) {
            Map<String, String> entityNameMap = ServiceXmlParserFactory.getInstance(project, EntityNamesServiceParser.class).getEntityNameMap();
            em.putAll(entityNameMap);
            em.putAll(EntityHelper.getWeakBundleNamespaces(project, entityNameMap, "Entity"));
        }

        Map<String, String> odm = new HashMap<>();
        if(managerList.contains(DoctrineTypes.Manager.MONGO_DB) || managerList.contains(DoctrineTypes.Manager.COUCH_DB)) {
            Map<String, String> documentMap = ServiceXmlParserFactory.getInstance(project, DocumentNamespacesParser.class).getNamespaceMap();
            odm.putAll(documentMap);
            odm.putAll(EntityHelper.getWeakBundleNamespaces(project, documentMap, "Document"));
        }

        // split bundle and model name
        int firstDirectorySeparatorIndex = shortcutName.indexOf(":");
        String bundlename = shortcutName.substring(0, firstDirectorySeparatorIndex);
        String entityName = shortcutName.substring(firstDirectorySeparatorIndex + 1);

        // conditional find namespace on manager paths
        for(Map<String, String> map: Arrays.asList(em, odm)) {
            String namespace = map.get(bundlename);
            if(namespace == null) {
                continue;
            }

            PhpClass classInterface = PhpElementsUtil.getClassInterface(project, namespace + "\\" + entityName);
            if(classInterface != null) {
                return classInterface;
            }
        }

        return null;
    }

    @Nullable
    public static DoctrineTypes.Manager getManager(MethodReference methodReference) {

        PhpPsiElement phpTypedElement = methodReference.getFirstPsiChild();
        if(!(phpTypedElement instanceof PhpTypedElement)) {
            return null;
        }

        for(String typeString: PhpIndex.getInstance(methodReference.getProject()).completeType(methodReference.getProject(), ((PhpTypedElement) phpTypedElement).getType(), new HashSet<>()).getTypes()) {
            for(Map.Entry<DoctrineTypes.Manager, String> entry: DoctrineTypes.getManagerInstanceMap().entrySet()) {
                if(PhpElementsUtil.isInstanceOf(methodReference.getProject(), typeString, entry.getValue())) {
                    return entry.getKey();
                }
            }
        }

        return null;
    }

    public static PsiElement[] getModelPsiTargets(Project project, @NotNull String entityName) {
        List<PsiElement> results = new ArrayList<>();

        PhpClass phpClass = EntityHelper.getEntityRepositoryClass(project, entityName);
        if(phpClass != null) {
            results.add(phpClass);
        }

        // search any php model file
        PhpClass entity = EntityHelper.resolveShortcutName(project, entityName);
        if(entity != null) {
            results.add(entity);

            // find model config eg ClassName.orm.yml
            PsiFile psiFile = EntityHelper.getModelConfigFile(entity);
            if(psiFile != null) {
                results.add(psiFile);
            }

        }

        return results.toArray(new PsiElement[results.size()]);
    }

    public static void attachAnnotationInformation(Field field, DoctrineModelField doctrineModelField) {

        // we already have that without regular expression
        // @TODO: de.espend.idea.php.annotation.util.AnnotationUtil.getPhpDocCommentAnnotationContainer()
        // fully require plugin now?

        // get some more presentable completion information
        // dont resolve docblocks; just extract them from doc comment
        PhpDocComment docBlock = field.getDocComment();

        if(docBlock == null) {
            return;
        }

        String text = docBlock.getText();

        // column type
        Matcher matcher = Pattern.compile("type[\\s]*=[\\s]*[\"|']([\\w_\\\\]+)[\"|']").matcher(text);
        if (matcher.find()) {
            doctrineModelField.setTypeName(matcher.group(1));
        }

        // relation type
        matcher = Pattern.compile("((Many|One)To(Many|One))\\(").matcher(text);
        if (matcher.find()) {
            doctrineModelField.setRelationType(matcher.group(1));

            // targetEntity name
            matcher = Pattern.compile("targetEntity[\\s]*=[\\s]*[\"|']([\\w_\\\\]+)[\"|']").matcher(text);
            if (matcher.find()) {
                doctrineModelField.setRelation(matcher.group(1));
            } else {
                // @TODO: external split
                // FLOW shortcut:
                // @var "\DateTime" is targetEntity
                PhpDocParamTag varTag = docBlock.getVarTag();
                if(varTag != null) {
                    String type = varTag.getType().toString();
                    if(org.apache.commons.lang.StringUtils.isNotBlank(type)) {
                        doctrineModelField.setRelation(type);
                    }
                }
            }
        }

        matcher = Pattern.compile("Column\\(").matcher(text);
        if (matcher.find()) {
            matcher = Pattern.compile("name\\s*=\\s*\"(\\w+)\"").matcher(text);
            if(matcher.find()) {
                doctrineModelField.setColumn(matcher.group(1));
            }

        }

    }

    /**
     * One PhpClass can have multiple targets and names @TODO: refactor
     */
    public static Collection<DoctrineModel> getModelClasses(final Project project) {

        HashMap<String, String> shortcutNames = new HashMap<String, String>() {{
            putAll(ServiceXmlParserFactory.getInstance(project, EntityNamesServiceParser.class).getEntityNameMap());
            putAll(ServiceXmlParserFactory.getInstance(project, DocumentNamespacesParser.class).getNamespaceMap());
        }};

        for (SymfonyBundle symfonyBundle : new SymfonyBundleUtil(project).getBundles()) {
            for(String s : new String[] {"Entity", "Document", "CouchDocument"}) {
                String namespace = symfonyBundle.getNamespaceName() + s;
                if(symfonyBundle.getRelative(s) != null || PhpIndex.getInstance(project).getNamespacesByName(namespace).size() > 0) {
                    shortcutNames.put(symfonyBundle.getName(), namespace);
                }
            }
        }

        // class fqn fallback
        Collection<DoctrineModel> doctrineModels = getModelClasses(project, shortcutNames);
        for (PhpClass phpClass : DoctrineMetadataUtil.getModels(project)) {
            if(containsDoctrineModelClass(doctrineModels, phpClass)) {
                continue;
            }

            doctrineModels.add(new DoctrineModel(phpClass));
        }

        DoctrineModelProviderParameter containerLoaderExtensionParameter = new DoctrineModelProviderParameter(project, new ArrayList<>());
        for(DoctrineModelProvider provider : EntityHelper.MODEL_POINT_NAME.getExtensions()) {
            for(DoctrineModelProviderParameter.DoctrineModel doctrineModel: provider.collectModels(containerLoaderExtensionParameter)) {
                doctrineModels.add(new DoctrineModel(doctrineModel.getPhpClass(), doctrineModel.getName()));
            }
        }

        return doctrineModels;
    }

    private static boolean containsDoctrineModelClass(@NotNull Collection<DoctrineModel> models, @NotNull PhpClass phpClass) {
        for (DoctrineModel doctrineModel : models) {
            if(PhpElementsUtil.isEqualClassName(doctrineModel.getPhpClass(), phpClass)) {
                return true;
            }
        }

        return false;
    }

    public static Collection<DoctrineModel> getModelClasses(Project project, Map<String, String> shortcutNames) {

        PhpClass repositoryInterface = PhpElementsUtil.getInterface(PhpIndex.getInstance(project), DoctrineTypes.REPOSITORY_INTERFACE);

        Collection<DoctrineModel> models = new ArrayList<>();
        for (Map.Entry<String, String> entry : shortcutNames.entrySet()) {
            for(PhpClass phpClass: PhpIndexUtil.getPhpClassInsideNamespace(project, entry.getValue())) {
                if(repositoryInterface != null && !isEntity(phpClass, repositoryInterface)) {
                    continue;
                }

                models.add(new DoctrineModel(phpClass, entry.getKey(), entry.getValue()));
            }
        }

        return models;
    }

    public static boolean isEntity(PhpClass entityClass, PhpClass repositoryClass) {

        if(entityClass.isAbstract() || entityClass.isInterface()) {
            return false;
        }

        return !PhpElementsUtil.isInstanceOf(entityClass, repositoryClass);
    }

    public static Map<String, String> getWeakBundleNamespaces(Project project, Map<String, String> entityNameMap, String subFolder) {

        Map<String, String> missingMap = new HashMap<>();

        Collection<SymfonyBundle> symfonyBundles = new SymfonyBundleUtil(project).getBundles();
        for(SymfonyBundle symfonyBundle: symfonyBundles) {
            if(symfonyBundle.isTestBundle()) {
                continue;
            }

            // namespace already known
            String bundleName = symfonyBundle.getName();
            if(entityNameMap.containsKey(bundleName)) {
               continue;
            }

            // find namepsace on file or class index
            String namespace = symfonyBundle.getNamespaceName() + subFolder;
            if(symfonyBundle.getRelative(subFolder) != null || PhpIndex.getInstance(project).getNamespacesByName(namespace).size() > 0) {
                missingMap.put(bundleName, namespace);
            }
        }

        return missingMap;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/dp_50"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/tv_roja_count"
        android:layout_width="@dimen/dp_70"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textSize="@dimen/text_size_15"/>

    <View
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:background="@color/table_colomn_divider" />

    <TextView
        android:id="@+id/tv_sehri_time"
        android:layout_width="@dimen/dp_70"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textSize="@dimen/text_size_15"/>

    <View
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:background="@color/table_colomn_divider" />

    <TextView
        android:id="@+id/tv_ifter_time"
        android:layout_width="@dimen/dp_70"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textSize="@dimen/text_size_15"/>

    <View
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:background="@color/table_colomn_divider" />

    <TextView
        android:id="@+id/tv_date"
        android:layout_height="match_parent"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:textSize="@dimen/text_size_15"
        android:gravity="center" />

</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
package com.github.drxaos.jvmvm.tests.interpretable;

public class Closure {

    interface Op {
        int eval(int a, int b);
    }

    static int y = 4;

    public static void main(String... args) {

        int x = 3;

        Op addition = (a, b) -> (a + b + x + y);

        int res = addition.eval(1, 2);

        if (res != 10) {
            throw new RuntimeException();
        }
    }

}


text:
game.PlayerErentity = me.Entity.extend({
    init: function(x, y, settings){
        this._super(me.Entity, 'init', [x, y, {
                image:"mario",
                spritewidth: "128",
                spriteheight: "128",
                width: 128,
                height: 128,
                getShape: function (){
                 return (new me.Rect(0, 0, 30, 128)).toPolygon();
               }
        }]);

        this.renderable.addAnimation("idle", [3]);
        this.renderable.addAnimation("smallwalk", [8, 9, 10, 11, 12, 13], 80);
        this.renderable.setCurrentAnimation("idle");

        //the first  number sets the speed mario move on x axis, the second sets the speed on the y axis
         this.body.setVelocity(5, 20);
         me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
    },

    update: function(delta){
     if(me.input.iskeypressed("right")){
         this.renderable.setCurrentAnimation("smallwalk");
         this.body.vel.x += this.body.accel.x * me.timer.tick;
     }else{
         this.body.vel.x = 0;
       }

          this.body.update(delta);
          me.collision.check(this, true, this.collideHandler.bind(this), true);

        if(this.body.vel.x !== 0) {
            if (!this.remderable.setCurrentAnimation("smallwalk")) {
                this.remderable.setCurrentAnimation("smallwalk");
            }
       }else{
            this.renderable.setCurrentAnimation("idle");
       }

       this._super(me.Entity, "update", [delta]);
         return true;
    },

    collidenhandler: function(response){

    }
});

game.leveltrigger = me.Entity.extend({
   init: function(x, y, settings) {
       this._super(me.Entity, 'init', [x, y, settings]);
       this.body. onCollision = this.onCollision.bind(this);
       this.level = settings.level;
       this.xspawn = settings.xspawn;
       this.yspawn = settings.yspawn;
   },

   onCollision: function() {
       this.body.setCollisionmask(me.collision.types.NO_OBJECT);
       me.levelDirector.loadLevel(this.level);
       me.state.current().ressetplayer(this.xspawn, this.yspawn);

   }

});


text:
#ifndef QALGORITHMS_H
#define QALGORITHMS_H

#include <QtCore/qglobal.h>

#if defined(Q_CC_MSVC) && _MSC_VER > 1500
#include <intrin.h>
#endif

QT_BEGIN_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED

/*
    Warning: The contents of QAlgorithmsPrivate is not a part of the public Qt API
    and may be changed from version to version or even be completely removed.
*/
namespace QAlgorithmsPrivate {

#if QT_DEPRECATED_SINCE(5, 2)
template <typename RandomAccessIterator, typename T, typename LessThan>
QT_DEPRECATED_X("Use std::sort") Q_OUTOFLINE_TEMPLATE void qSortHelper(RandomAccessIterator start, RandomAccessIterator end, const T &t, LessThan lessThan);
template <typename RandomAccessIterator, typename T>
QT_DEPRECATED_X("Use std::sort") inline void qSortHelper(RandomAccessIterator begin, RandomAccessIterator end, const T &dummy);

template <typename RandomAccessIterator, typename T, typename LessThan>
QT_DEPRECATED_X("Use std::stable_sort") Q_OUTOFLINE_TEMPLATE void qStableSortHelper(RandomAccessIterator start, RandomAccessIterator end, const T &t, LessThan lessThan);
template <typename RandomAccessIterator, typename T>
QT_DEPRECATED_X("Use std::stable_sort") inline void qStableSortHelper(RandomAccessIterator, RandomAccessIterator, const T &);

template <typename RandomAccessIterator, typename T, typename LessThan>
QT_DEPRECATED_X("Use std::lower_bound") Q_OUTOFLINE_TEMPLATE RandomAccessIterator qLowerBoundHelper(RandomAccessIterator begin, RandomAccessIterator end, const T &value, LessThan lessThan);
template <typename RandomAccessIterator, typename T, typename LessThan>
QT_DEPRECATED_X("Use std::upper_bound") Q_OUTOFLINE_TEMPLATE RandomAccessIterator qUpperBoundHelper(RandomAccessIterator begin, RandomAccessIterator end, const T &value, LessThan lessThan);
template <typename RandomAccessIterator, typename T, typename LessThan>
QT_DEPRECATED_X("Use std::binary_search") Q_OUTOFLINE_TEMPLATE RandomAccessIterator qBinaryFindHelper(RandomAccessIterator begin, RandomAccessIterator end, const T &value, LessThan lessThan);
#endif // QT_DEPRECATED_SINCE(5, 2)

}

#if QT_DEPRECATED_SINCE(5, 2)
template <typename InputIterator, typename OutputIterator>
QT_DEPRECATED_X("Use std::copy") inline OutputIterator qCopy(InputIterator begin, InputIterator end, OutputIterator dest)
{
    while (begin != end)
        *dest++ = *begin++;
    return dest;
}

template <typename BiIterator1, typename BiIterator2>
QT_DEPRECATED_X("Use std::copy_backward") inline BiIterator2 qCopyBackward(BiIterator1 begin, BiIterator1 end, BiIterator2 dest)
{
    while (begin != end)
        *--dest = *--end;
    return dest;
}

template <typename InputIterator1, typename InputIterator2>
QT_DEPRECATED_X("Use std::equal") inline bool qEqual(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2)
{
    for (; first1 != last1; ++first1, ++first2)
        if (!(*first1 == *first2))
            return false;
    return true;
}

template <typename ForwardIterator, typename T>
QT_DEPRECATED_X("Use std::fill") inline void qFill(ForwardIterator first, ForwardIterator last, const T &val)
{
    for (; first != last; ++first)
        *first = val;
}

template <typename Container, typename T>
QT_DEPRECATED_X("Use std::fill") inline void qFill(Container &container, const T &val)
{
    qFill(container.begin(), container.end(), val);
}

template <typename InputIterator, typename T>
QT_DEPRECATED_X("Use std::find") inline InputIterator qFind(InputIterator first, InputIterator last, const T &val)
{
    while (first != last && !(*first == val))
        ++first;
    return first;
}

template <typename Container, typename T>
QT_DEPRECATED_X("Use std::find") inline typename Container::const_iterator qFind(const Container &container, const T &val)
{
    return qFind(container.constBegin(), container.constEnd(), val);
}

template <typename InputIterator, typename T, typename Size>
QT_DEPRECATED_X("Use std::count") inline void qCount(InputIterator first, InputIterator last, const T &value, Size &n)
{
    for (; first != last; ++first)
        if (*first == value)
            ++n;
}

template <typename Container, typename T, typename Size>
QT_DEPRECATED_X("Use std::count") inline void qCount(const Container &container, const T &value, Size &n)
{
    qCount(container.constBegin(), container.constEnd(), value, n);
}

#ifdef Q_QDOC
typedef void* LessThan;
template <typename T> LessThan qLess();
template <typename T> LessThan qGreater();
#else
template <typename T>
class QT_DEPRECATED_X("Use std::less") qLess
{
public:
    inline bool operator()(const T &t1, const T &t2) const
    {
        return (t1 < t2);
    }
};

template <typename T>
class QT_DEPRECATED_X("Use std::greater") qGreater
{
public:
    inline bool operator()(const T &t1, const T &t2) const
    {
        return (t2 < t1);
    }
};
#endif

template <typename RandomAccessIterator>
QT_DEPRECATED_X("Use std::sort") inline void qSort(RandomAccessIterator start, RandomAccessIterator end)
{
    if (start != end)
        QAlgorithmsPrivate::qSortHelper(start, end, *start);
}

template <typename RandomAccessIterator, typename LessThan>
QT_DEPRECATED_X("Use std::sort") inline void qSort(RandomAccessIterator start, RandomAccessIterator end, LessThan lessThan)
{
    if (start != end)
        QAlgorithmsPrivate::qSortHelper(start, end, *start, lessThan);
}

template<typename Container>
QT_DEPRECATED_X("Use std::sort") inline void qSort(Container &c)
{
#ifdef Q_CC_BOR
    // Work around Borland 5.5 optimizer bug
    c.detach();
#endif
    if (!c.empty())
        QAlgorithmsPrivate::qSortHelper(c.begin(), c.end(), *c.begin());
}

template <typename RandomAccessIterator>
QT_DEPRECATED_X("Use std::stable_sort") inline void qStableSort(RandomAccessIterator start, RandomAccessIterator end)
{
    if (start != end)
        QAlgorithmsPrivate::qStableSortHelper(start, end, *start);
}

template <typename RandomAccessIterator, typename LessThan>
QT_DEPRECATED_X("Use std::stable_sort") inline void qStableSort(RandomAccessIterator start, RandomAccessIterator end, LessThan lessThan)
{
    if (start != end)
        QAlgorithmsPrivate::qStableSortHelper(start, end, *start, lessThan);
}

template<typename Container>
QT_DEPRECATED_X("Use std::stable_sort") inline void qStableSort(Container &c)
{
#ifdef Q_CC_BOR
    // Work around Borland 5.5 optimizer bug
    c.detach();
#endif
    if (!c.empty())
        QAlgorithmsPrivate::qStableSortHelper(c.begin(), c.end(), *c.begin());
}

template <typename RandomAccessIterator, typename T>
QT_DEPRECATED_X("Use std::lower_bound") Q_OUTOFLINE_TEMPLATE RandomAccessIterator qLowerBound(RandomAccessIterator begin, RandomAccessIterator end, const T &value)
{
    // Implementation is duplicated from QAlgorithmsPrivate to keep existing code
    // compiling. We have to allow using *begin and value with different types,
    // and then implementing operator< for those types.
    RandomAccessIterator middle;
    int n = end - begin;
    int half;

    while (n > 0) {
        half = n >> 1;
        middle = begin + half;
        if (*middle < value) {
            begin = middle + 1;
            n -= half + 1;
        } else {
            n = half;
        }
    }
    return begin;
}

template <typename RandomAccessIterator, typename T, typename LessThan>
QT_DEPRECATED_X("Use std::lower_bound") Q_OUTOFLINE_TEMPLATE RandomAccessIterator qLowerBound(RandomAccessIterator begin, RandomAccessIterator end, const T &value, LessThan lessThan)
{
    return QAlgorithmsPrivate::qLowerBoundHelper(begin, end, value, lessThan);
}

template <typename Container, typename T>
QT_DEPRECATED_X("Use std::lower_bound") Q_OUTOFLINE_TEMPLATE typename Container::const_iterator qLowerBound(const Container &container, const T &value)
{
    return QAlgorithmsPrivate::qLowerBoundHelper(container.constBegin(), container.constEnd(), value, qLess<T>());
}

template <typename RandomAccessIterator, typename T>
QT_DEPRECATED_X("Use std::upper_bound") Q_OUTOFLINE_TEMPLATE RandomAccessIterator qUpperBound(RandomAccessIterator begin, RandomAccessIterator end, const T &value)
{
    // Implementation is duplicated from QAlgorithmsPrivate.
    RandomAccessIterator middle;
    int n = end - begin;
    int half;

    while (n > 0) {
        half = n >> 1;
        middle = begin + half;
        if (value < *middle) {
            n = half;
        } else {
            begin = middle + 1;
            n -= half + 1;
        }
    }
    return begin;
}

template <typename RandomAccessIterator, typename T, typename LessThan>
QT_DEPRECATED_X("Use std::upper_bound") Q_OUTOFLINE_TEMPLATE RandomAccessIterator qUpperBound(RandomAccessIterator begin, RandomAccessIterator end, const T &value, LessThan lessThan)
{
    return QAlgorithmsPrivate::qUpperBoundHelper(begin, end, value, lessThan);
}

template <typename Container, typename T>
QT_DEPRECATED_X("Use std::upper_bound") Q_OUTOFLINE_TEMPLATE typename Container::const_iterator qUpperBound(const Container &container, const T &value)
{
    return QAlgorithmsPrivate::qUpperBoundHelper(container.constBegin(), container.constEnd(), value, qLess<T>());
}

template <typename RandomAccessIterator, typename T>
QT_DEPRECATED_X("Use std::binary_search") Q_OUTOFLINE_TEMPLATE RandomAccessIterator qBinaryFind(RandomAccessIterator begin, RandomAccessIterator end, const T &value)
{
    // Implementation is duplicated from QAlgorithmsPrivate.
    RandomAccessIterator it = qLowerBound(begin, end, value);

    if (it == end || value < *it)
        return end;

    return it;
}

template <typename RandomAccessIterator, typename T, typename LessThan>
QT_DEPRECATED_X("Use std::binary_search") Q_OUTOFLINE_TEMPLATE RandomAccessIterator qBinaryFind(RandomAccessIterator begin, RandomAccessIterator end, const T &value, LessThan lessThan)
{
    return QAlgorithmsPrivate::qBinaryFindHelper(begin, end, value, lessThan);
}

template <typename Container, typename T>
QT_DEPRECATED_X("Use std::binary_search") Q_OUTOFLINE_TEMPLATE typename Container::const_iterator qBinaryFind(const Container &container, const T &value)
{
    return QAlgorithmsPrivate::qBinaryFindHelper(container.constBegin(), container.constEnd(), value, qLess<T>());
}
#endif // QT_DEPRECATED_SINCE(5, 2)

template <typename ForwardIterator>
Q_OUTOFLINE_TEMPLATE void qDeleteAll(ForwardIterator begin, ForwardIterator end)
{
    while (begin != end) {
        delete *begin;
        ++begin;
    }
}

template <typename Container>
inline void qDeleteAll(const Container &c)
{
    qDeleteAll(c.begin(), c.end());
}

/*
    Warning: The contents of QAlgorithmsPrivate is not a part of the public Qt API
    and may be changed from version to version or even be completely removed.
*/
namespace QAlgorithmsPrivate {

#if QT_DEPRECATED_SINCE(5, 2)

template <typename RandomAccessIterator, typename T, typename LessThan>
QT_DEPRECATED_X("Use std::sort") Q_OUTOFLINE_TEMPLATE void qSortHelper(RandomAccessIterator start, RandomAccessIterator end, const T &t, LessThan lessThan)
{
top:
    int span = int(end - start);
    if (span < 2)
        return;

    --end;
    RandomAccessIterator low = start, high = end - 1;
    RandomAccessIterator pivot = start + span / 2;

    if (lessThan(*end, *start))
        qSwap(*end, *start);
    if (span == 2)
        return;

    if (lessThan(*pivot, *start))
        qSwap(*pivot, *start);
    if (lessThan(*end, *pivot))
        qSwap(*end, *pivot);
    if (span == 3)
        return;

    qSwap(*pivot, *end);

    while (low < high) {
        while (low < high && lessThan(*low, *end))
            ++low;

        while (high > low && lessThan(*end, *high))
            --high;

        if (low < high) {
            qSwap(*low, *high);
            ++low;
            --high;
        } else {
            break;
        }
    }

    if (lessThan(*low, *end))
        ++low;

    qSwap(*end, *low);
    qSortHelper(start, low, t, lessThan);

    start = low + 1;
    ++end;
    goto top;
}

template <typename RandomAccessIterator, typename T>
QT_DEPRECATED_X("Use std::sort") inline void qSortHelper(RandomAccessIterator begin, RandomAccessIterator end, const T &dummy)
{
    qSortHelper(begin, end, dummy, qLess<T>());
}

template <typename RandomAccessIterator>
QT_DEPRECATED_X("Use std::reverse") Q_OUTOFLINE_TEMPLATE void qReverse(RandomAccessIterator begin, RandomAccessIterator end)
{
    --end;
    while (begin < end)
        qSwap(*begin++, *end--);
}

template <typename RandomAccessIterator>
QT_DEPRECATED_X("Use std::rotate") Q_OUTOFLINE_TEMPLATE void qRotate(RandomAccessIterator begin, RandomAccessIterator middle, RandomAccessIterator end)
{
    qReverse(begin, middle);
    qReverse(middle, end);
    qReverse(begin, end);
}

template <typename RandomAccessIterator, typename T, typename LessThan>
QT_DEPRECATED_X("Use std::merge") Q_OUTOFLINE_TEMPLATE void qMerge(RandomAccessIterator begin, RandomAccessIterator pivot, RandomAccessIterator end, T &t, LessThan lessThan)
{
    const int len1 = pivot - begin;
    const int len2 = end - pivot;

    if (len1 == 0 || len2 == 0)
        return;

    if (len1 + len2 == 2) {
        if (lessThan(*(begin + 1), *(begin)))
            qSwap(*begin, *(begin + 1));
        return;
    }

    RandomAccessIterator firstCut;
    RandomAccessIterator secondCut;
    int len2Half;
    if (len1 > len2) {
        const int len1Half = len1 / 2;
        firstCut = begin + len1Half;
        secondCut = qLowerBound(pivot, end, *firstCut, lessThan);
        len2Half = secondCut - pivot;
    } else {
        len2Half = len2 / 2;
        secondCut = pivot + len2Half;
        firstCut = qUpperBound(begin, pivot, *secondCut, lessThan);
    }

    qRotate(firstCut, pivot, secondCut);
    const RandomAccessIterator newPivot = firstCut + len2Half;
    qMerge(begin, firstCut, newPivot, t, lessThan);
    qMerge(newPivot, secondCut, end, t, lessThan);
}

template <typename RandomAccessIterator, typename T, typename LessThan>
QT_DEPRECATED_X("Use std::stable_sort") Q_OUTOFLINE_TEMPLATE void qStableSortHelper(RandomAccessIterator begin, RandomAccessIterator end, const T &t, LessThan lessThan)
{
    const int span = end - begin;
    if (span < 2)
       return;

    const RandomAccessIterator middle = begin + span / 2;
    qStableSortHelper(begin, middle, t, lessThan);
    qStableSortHelper(middle, end, t, lessThan);
    qMerge(begin, middle, end, t, lessThan);
}

template <typename RandomAccessIterator, typename T>
QT_DEPRECATED_X("Use std::stable_sort") inline void qStableSortHelper(RandomAccessIterator begin, RandomAccessIterator end, const T &dummy)
{
    qStableSortHelper(begin, end, dummy, qLess<T>());
}

template <typename RandomAccessIterator, typename T, typename LessThan>
QT_DEPRECATED_X("Use std::lower_bound") Q_OUTOFLINE_TEMPLATE RandomAccessIterator qLowerBoundHelper(RandomAccessIterator begin, RandomAccessIterator end, const T &value, LessThan lessThan)
{
    RandomAccessIterator middle;
    int n = int(end - begin);
    int half;

    while (n > 0) {
        half = n >> 1;
        middle = begin + half;
        if (lessThan(*middle, value)) {
            begin = middle + 1;
            n -= half + 1;
        } else {
            n = half;
        }
    }
    return begin;
}

template <typename RandomAccessIterator, typename T, typename LessThan>
QT_DEPRECATED_X("Use std::upper_bound") Q_OUTOFLINE_TEMPLATE RandomAccessIterator qUpperBoundHelper(RandomAccessIterator begin, RandomAccessIterator end, const T &value, LessThan lessThan)
{
    RandomAccessIterator middle;
    int n = end - begin;
    int half;

    while (n > 0) {
        half = n >> 1;
        middle = begin + half;
        if (lessThan(value, *middle)) {
            n = half;
        } else {
            begin = middle + 1;
            n -= half + 1;
        }
    }
    return begin;
}

template <typename RandomAccessIterator, typename T, typename LessThan>
QT_DEPRECATED_X("Use std::binary_search") Q_OUTOFLINE_TEMPLATE RandomAccessIterator qBinaryFindHelper(RandomAccessIterator begin, RandomAccessIterator end, const T &value, LessThan lessThan)
{
    RandomAccessIterator it = qLowerBoundHelper(begin, end, value, lessThan);

    if (it == end || lessThan(value, *it))
        return end;

    return it;
}

#endif // QT_DEPRECATED_SINCE(5, 2)

#ifdef Q_CC_CLANG
// Clang had a bug where __builtin_ctz/clz/popcount were not marked as constexpr.
#  if (defined __apple_build_version__ &&  __clang_major__ >= 7) || (Q_CC_CLANG >= 307)
#    define QT_HAS_CONSTEXPR_BUILTINS
#  endif
#elif defined(Q_CC_MSVC) && !defined(Q_CC_INTEL) && !defined(Q_OS_WINCE) && !defined(Q_PROCESSOR_ARM)
#  define QT_HAS_CONSTEXPR_BUILTINS
#elif defined(Q_CC_GNU)
#  define QT_HAS_CONSTEXPR_BUILTINS
#endif

#if defined QT_HAS_CONSTEXPR_BUILTINS
#if defined(Q_CC_GNU) || defined(Q_CC_CLANG)
#  define QT_HAS_BUILTIN_CTZS
Q_DECL_CONSTEXPR Q_ALWAYS_INLINE uint qt_builtin_ctzs(quint16 v) Q_DECL_NOTHROW
{
#  if QT_HAS_BUILTIN(__builtin_ctzs)
    return __builtin_ctzs(v);
#  else
    return __builtin_ctz(v);
#  endif
}
#define QT_HAS_BUILTIN_CLZS
Q_DECL_CONSTEXPR Q_ALWAYS_INLINE uint qt_builtin_clzs(quint16 v) Q_DECL_NOTHROW
{
#  if QT_HAS_BUILTIN(__builtin_clzs)
    return __builtin_clzs(v);
#  else
    return __builtin_clz(v) - 16U;
#  endif
}
#define QT_HAS_BUILTIN_CTZ
Q_DECL_CONSTEXPR Q_ALWAYS_INLINE uint qt_builtin_ctz(quint32 v) Q_DECL_NOTHROW
{
    return __builtin_ctz(v);
}
#define QT_HAS_BUILTIN_CLZ
Q_DECL_CONSTEXPR Q_ALWAYS_INLINE uint qt_builtin_clz(quint32 v) Q_DECL_NOTHROW
{
    return __builtin_clz(v);
}
#define QT_HAS_BUILTIN_CTZLL
Q_DECL_CONSTEXPR Q_ALWAYS_INLINE uint qt_builtin_ctzll(quint64 v) Q_DECL_NOTHROW
{
    return __builtin_ctzll(v);
}
#define QT_HAS_BUILTIN_CLZLL
Q_DECL_CONSTEXPR Q_ALWAYS_INLINE uint qt_builtin_clzll(quint64 v) Q_DECL_NOTHROW
{
    return __builtin_clzll(v);
}
#define QALGORITHMS_USE_BUILTIN_POPCOUNT
Q_DECL_CONSTEXPR Q_ALWAYS_INLINE uint qt_builtin_popcount(quint32 v) Q_DECL_NOTHROW
{
    return __builtin_popcount(v);
}
Q_DECL_CONSTEXPR Q_ALWAYS_INLINE uint qt_builtin_popcount(quint8 v) Q_DECL_NOTHROW
{
    return __builtin_popcount(v);
}
Q_DECL_CONSTEXPR Q_ALWAYS_INLINE uint qt_builtin_popcount(quint16 v) Q_DECL_NOTHROW
{
    return __builtin_popcount(v);
}
#define QALGORITHMS_USE_BUILTIN_POPCOUNTLL
Q_DECL_CONSTEXPR Q_ALWAYS_INLINE uint qt_builtin_popcountll(quint64 v) Q_DECL_NOTHROW
{
    return __builtin_popcountll(v);
}
#elif defined(Q_CC_MSVC) && !defined(Q_OS_WINCE) && !defined(Q_PROCESSOR_ARM)
#define QT_HAS_BUILTIN_CTZ
Q_DECL_CONSTEXPR Q_ALWAYS_INLINE unsigned long qt_builtin_ctz(quint32 val)
{
    unsigned long result;
    _BitScanForward(&result, val);
    return result;
}
#define QT_HAS_BUILTIN_CLZ
Q_DECL_CONSTEXPR Q_ALWAYS_INLINE unsigned long qt_builtin_clz(quint32 val)
{
    unsigned long result;
    _BitScanReverse(&result, val);
    // Now Invert the result: clz will count *down* from the msb to the lsb, so the msb index is 31
    // and the lsb index is 0. The result for the index when counting up: msb index is 0 (because it
    // starts there), and the lsb index is 31.
    result ^= sizeof(quint32) * 8 - 1;
    return result;
}
#if Q_PROCESSOR_WORDSIZE == 8
// These are only defined for 64bit builds.
#define QT_HAS_BUILTIN_CTZLL
Q_DECL_CONSTEXPR Q_ALWAYS_INLINE unsigned long qt_builtin_ctzll(quint64 val)
{
    unsigned long result;
    _BitScanForward64(&result, val);
    return result;
}
// MSVC calls it _BitScanReverse and returns the carry flag, which we don't need
#define QT_HAS_BUILTIN_CLZLL
Q_DECL_CONSTEXPR Q_ALWAYS_INLINE unsigned long qt_builtin_clzll(quint64 val)
{
    unsigned long result;
    _BitScanReverse64(&result, val);
    // see qt_builtin_clz
    result ^= sizeof(quint64) * 8 - 1;
    return result;
}
#endif // MSVC 64bit
#  define QT_HAS_BUILTIN_CTZS
Q_DECL_CONSTEXPR Q_ALWAYS_INLINE uint qt_builtin_ctzs(quint16 v) Q_DECL_NOTHROW
{
    return qt_builtin_ctz(v);
}
#define QT_HAS_BUILTIN_CLZS
Q_DECL_CONSTEXPR Q_ALWAYS_INLINE uint qt_builtin_clzs(quint16 v) Q_DECL_NOTHROW
{
    return qt_builtin_clz(v) - 16U;
}
#define QALGORITHMS_USE_BUILTIN_POPCOUNT
Q_DECL_CONSTEXPR Q_ALWAYS_INLINE uint qt_builtin_popcount(quint32 v) Q_DECL_NOTHROW
{
    return __popcnt(v);
}
Q_DECL_CONSTEXPR Q_ALWAYS_INLINE uint qt_builtin_popcount(quint8 v) Q_DECL_NOTHROW
{
    return __popcnt16(v);
}
Q_DECL_CONSTEXPR Q_ALWAYS_INLINE uint qt_builtin_popcount(quint16 v) Q_DECL_NOTHROW
{
    return __popcnt16(v);
}
#if Q_PROCESSOR_WORDSIZE == 8
#define QALGORITHMS_USE_BUILTIN_POPCOUNTLL
Q_DECL_CONSTEXPR Q_ALWAYS_INLINE uint qt_builtin_popcountll(quint64 v) Q_DECL_NOTHROW
{
    return __popcnt64(v);
}
#endif // MSVC 64bit
#endif // MSVC
#endif // QT_HAS_CONSTEXPR_BUILTINS

} //namespace QAlgorithmsPrivate

Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qPopulationCount(quint32 v) Q_DECL_NOTHROW
{
#ifdef QALGORITHMS_USE_BUILTIN_POPCOUNT
    return QAlgorithmsPrivate::qt_builtin_popcount(v);
#else
    // See http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
    return
        (((v      ) & 0xfff)    * Q_UINT64_C(0x1001001001001) & Q_UINT64_C(0x84210842108421)) % 0x1f +
        (((v >> 12) & 0xfff)    * Q_UINT64_C(0x1001001001001) & Q_UINT64_C(0x84210842108421)) % 0x1f +
        (((v >> 24) & 0xfff)    * Q_UINT64_C(0x1001001001001) & Q_UINT64_C(0x84210842108421)) % 0x1f;
#endif
}

Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qPopulationCount(quint8 v) Q_DECL_NOTHROW
{
#ifdef QALGORITHMS_USE_BUILTIN_POPCOUNT
    return QAlgorithmsPrivate::qt_builtin_popcount(v);
#else
    return
        (((v      ) & 0xfff)    * Q_UINT64_C(0x1001001001001) & Q_UINT64_C(0x84210842108421)) % 0x1f;
#endif
}

Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qPopulationCount(quint16 v) Q_DECL_NOTHROW
{
#ifdef QALGORITHMS_USE_BUILTIN_POPCOUNT
    return QAlgorithmsPrivate::qt_builtin_popcount(v);
#else
    return
        (((v      ) & 0xfff)    * Q_UINT64_C(0x1001001001001) & Q_UINT64_C(0x84210842108421)) % 0x1f +
        (((v >> 12) & 0xfff)    * Q_UINT64_C(0x1001001001001) & Q_UINT64_C(0x84210842108421)) % 0x1f;
#endif
}

Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qPopulationCount(quint64 v) Q_DECL_NOTHROW
{
#ifdef QALGORITHMS_USE_BUILTIN_POPCOUNTLL
    return QAlgorithmsPrivate::qt_builtin_popcountll(v);
#else
    return
        (((v      ) & 0xfff)    * Q_UINT64_C(0x1001001001001) & Q_UINT64_C(0x84210842108421)) % 0x1f +
        (((v >> 12) & 0xfff)    * Q_UINT64_C(0x1001001001001) & Q_UINT64_C(0x84210842108421)) % 0x1f +
        (((v >> 24) & 0xfff)    * Q_UINT64_C(0x1001001001001) & Q_UINT64_C(0x84210842108421)) % 0x1f +
        (((v >> 36) & 0xfff)    * Q_UINT64_C(0x1001001001001) & Q_UINT64_C(0x84210842108421)) % 0x1f +
        (((v >> 48) & 0xfff)    * Q_UINT64_C(0x1001001001001) & Q_UINT64_C(0x84210842108421)) % 0x1f +
        (((v >> 60) & 0xfff)    * Q_UINT64_C(0x1001001001001) & Q_UINT64_C(0x84210842108421)) % 0x1f;
#endif
}

Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline uint qPopulationCount(long unsigned int v) Q_DECL_NOTHROW
{
    return qPopulationCount(static_cast<quint64>(v));
}

#if defined(Q_CC_GNU) && !defined(Q_CC_CLANG)
#undef QALGORITHMS_USE_BUILTIN_POPCOUNT
#endif

Q_DECL_RELAXED_CONSTEXPR inline uint qCountTrailingZeroBits(quint32 v) Q_DECL_NOTHROW
{
#if defined(QT_HAS_BUILTIN_CTZ)
    return v ? QAlgorithmsPrivate::qt_builtin_ctz(v) : 32U;
#else
    // see http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightParallel
    unsigned int c = 32; // c will be the number of zero bits on the right
    v &= -signed(v);
    if (v) c--;
    if (v & 0x0000FFFF) c -= 16;
    if (v & 0x00FF00FF) c -= 8;
    if (v & 0x0F0F0F0F) c -= 4;
    if (v & 0x33333333) c -= 2;
    if (v & 0x55555555) c -= 1;
    return c;
#endif
}

Q_DECL_RELAXED_CONSTEXPR inline uint qCountTrailingZeroBits(quint8 v) Q_DECL_NOTHROW
{
#if defined(QT_HAS_BUILTIN_CTZ)
    return v ? QAlgorithmsPrivate::qt_builtin_ctz(v) : 8U;
#else
    unsigned int c = 8; // c will be the number of zero bits on the right
    v &= -signed(v);
    if (v) c--;
    if (v & 0x0000000F) c -= 4;
    if (v & 0x00000033) c -= 2;
    if (v & 0x00000055) c -= 1;
    return c;
#endif
}

Q_DECL_RELAXED_CONSTEXPR inline uint qCountTrailingZeroBits(quint16 v) Q_DECL_NOTHROW
{
#if defined(QT_HAS_BUILTIN_CTZS)
    return v ? QAlgorithmsPrivate::qt_builtin_ctzs(v) : 16U;
#else
    unsigned int c = 16; // c will be the number of zero bits on the right
    v &= -signed(v);
    if (v) c--;
    if (v & 0x000000FF) c -= 8;
    if (v & 0x00000F0F) c -= 4;
    if (v & 0x00003333) c -= 2;
    if (v & 0x00005555) c -= 1;
    return c;
#endif
}

Q_DECL_RELAXED_CONSTEXPR inline uint qCountTrailingZeroBits(quint64 v) Q_DECL_NOTHROW
{
#if defined(QT_HAS_BUILTIN_CTZLL)
    return v ? QAlgorithmsPrivate::qt_builtin_ctzll(v) : 64;
#else
    quint32 x = static_cast<quint32>(v);
    return x ? qCountTrailingZeroBits(x)
             : 32 + qCountTrailingZeroBits(static_cast<quint32>(v >> 32));
#endif
}

Q_DECL_RELAXED_CONSTEXPR inline uint qCountTrailingZeroBits(unsigned long v) Q_DECL_NOTHROW
{
    return qCountTrailingZeroBits(QIntegerForSizeof<long>::Unsigned(v));
}

Q_DECL_RELAXED_CONSTEXPR inline uint qCountLeadingZeroBits(quint32 v) Q_DECL_NOTHROW
{
#if defined(QT_HAS_BUILTIN_CLZ)
    return v ? QAlgorithmsPrivate::qt_builtin_clz(v) : 32U;
#else
    // Hacker's Delight, 2nd ed. Fig 5-16, p. 102
    v = v | (v >> 1);
    v = v | (v >> 2);
    v = v | (v >> 4);
    v = v | (v >> 8);
    v = v | (v >> 16);
    return qPopulationCount(~v);
#endif
}

Q_DECL_RELAXED_CONSTEXPR inline uint qCountLeadingZeroBits(quint8 v) Q_DECL_NOTHROW
{
#if defined(QT_HAS_BUILTIN_CLZ)
    return v ? QAlgorithmsPrivate::qt_builtin_clz(v)-24U : 8U;
#else
    v = v | (v >> 1);
    v = v | (v >> 2);
    v = v | (v >> 4);
    return qPopulationCount(static_cast<quint8>(~v));
#endif
}

Q_DECL_RELAXED_CONSTEXPR inline uint qCountLeadingZeroBits(quint16 v) Q_DECL_NOTHROW
{
#if defined(QT_HAS_BUILTIN_CLZS)
    return v ? QAlgorithmsPrivate::qt_builtin_clzs(v) : 16U;
#else
    v = v | (v >> 1);
    v = v | (v >> 2);
    v = v | (v >> 4);
    v = v | (v >> 8);
    return qPopulationCount(static_cast<quint16>(~v));
#endif
}

Q_DECL_RELAXED_CONSTEXPR inline uint qCountLeadingZeroBits(quint64 v) Q_DECL_NOTHROW
{
#if defined(QT_HAS_BUILTIN_CLZLL)
    return v ? QAlgorithmsPrivate::qt_builtin_clzll(v) : 64U;
#else
    v = v | (v >> 1);
    v = v | (v >> 2);
    v = v | (v >> 4);
    v = v | (v >> 8);
    v = v | (v >> 16);
    v = v | (v >> 32);
    return qPopulationCount(~v);
#endif
}

Q_DECL_RELAXED_CONSTEXPR inline uint qCountLeadingZeroBits(unsigned long v) Q_DECL_NOTHROW
{
    return qCountLeadingZeroBits(QIntegerForSizeof<long>::Unsigned(v));
}

QT_WARNING_POP
QT_END_NAMESPACE

#endif // QALGORITHMS_H


text:
package main

import (
	"bufio"
	"net"
	"os"
	"regexp"
	"strings"
	"time"

	"github.com/hoisie/redis"
)

type Hosts struct {
	fileHosts  *FileHosts
	redisHosts *RedisHosts
}

func NewHosts(hs HostsSettings, rs RedisSettings) Hosts {
	fileHosts := &FileHosts{hs.HostsFile, make(map[string]string)}

	var redisHosts *RedisHosts
	if hs.RedisEnable {
		rc := &redis.Client{Addr: rs.Addr(), Db: rs.DB, Password: rs.Password}
		redisHosts = &RedisHosts{rc, hs.RedisKey, make(map[string]string)}
	}

	hosts := Hosts{fileHosts, redisHosts}
	hosts.refresh()
	return hosts

}

/*
1. Match local /etc/hosts file first, remote redis records second
2. Fetch hosts records from /etc/hosts file and redis per minute
*/

func (h *Hosts) Get(domain string, family int) (ip net.IP, ok bool) {

	var sip string

	if sip, ok = h.fileHosts.Get(domain); !ok {
		if h.redisHosts != nil {
			sip, ok = h.redisHosts.Get(domain)
		}
	}

	if sip == "" {
		return nil, false
	}

	switch family {
	case _IP4Query:
		ip = net.ParseIP(sip).To4()
	case _IP6Query:
		ip = net.ParseIP(sip).To16()
	default:
		return nil, false
	}
	return ip, (ip != nil)
}

func (h *Hosts) refresh() {
	ticker := time.NewTicker(time.Minute)
	go func() {
		for {
			h.fileHosts.Refresh()
			if h.redisHosts != nil {
				h.redisHosts.Refresh()
			}
			<-ticker.C
		}
	}()
}

type RedisHosts struct {
	redis *redis.Client
	key   string
	hosts map[string]string
}

func (r *RedisHosts) Get(domain string) (ip string, ok bool) {
	ip, ok = r.hosts[domain]
	return
}

func (r *RedisHosts) Set(domain, ip string) (bool, error) {
	return r.redis.Hset(r.key, domain, []byte(ip))
}

func (r *RedisHosts) Refresh() {
	r.redis.Hgetall(r.key, r.hosts)
	Debug("update hosts records from redis")
}

type FileHosts struct {
	file  string
	hosts map[string]string
}

func (f *FileHosts) Get(domain string) (ip string, ok bool) {
	ip, ok = f.hosts[domain]
	return
}

func (f *FileHosts) Refresh() {
	buf, err := os.Open(f.file)
	if err != nil {
		panic("Can't open " + f.file)
	}

	scanner := bufio.NewScanner(buf)
	for scanner.Scan() {

		line := scanner.Text()
		line = strings.TrimSpace(line)

		if strings.HasPrefix(line, "#") || line == "" {
			continue
		}

		sli := strings.Split(line, " ")
		if len(sli) == 1 {
			sli = strings.Split(line, "\t")
		}

		if len(sli) < 2 {
			continue
		}

		domain := sli[len(sli)-1]
		ip := sli[0]
		if !f.isDomain(domain) || !f.isIP(ip) {
			continue
		}

		f.hosts[domain] = ip
	}
	Debug("update hosts records from %s", f.file)
}

func (f *FileHosts) isDomain(domain string) bool {
	if f.isIP(domain) {
		return false
	}
	match, _ := regexp.MatchString("^[a-zA-Z0-9][a-zA-Z0-9-]", domain)
	return match
}

func (f *FileHosts) isIP(ip string) bool {
	return (net.ParseIP(ip) != nil)
}


text:
require "acts_as_contextable/version"
require 'active_record'
require 'active_support/inflector'

$LOAD_PATH.unshift(File.dirname(__FILE__))

module ActsAsContextable

  if defined?(ActiveRecord::Base)
    require 'acts_as_contextable/extenders/contextable'
    require 'acts_as_contextable/extenders/context'
    require 'acts_as_contextable/context_reference'
    ActiveRecord::Base.extend ActsAsContextable::Extenders::Contextable
    ActiveRecord::Base.extend ActsAsContextable::Extenders::Context
  end

end

require 'acts_as_contextable/extenders/controller'
ActiveSupport.on_load(:action_controller) do
  include ActsAsContextable::Extenders::Controller
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace Querify
{
    public static class QueryableExtensions
    {
        public const int MaxPageSize = 128;
        public const int DefaultPageSize = 10;

        private static readonly List<IFutureConverter> FutureConverters
            = new List<IFutureConverter>();

        private class LinqToObjectsFutureConverter : IFutureConverter
        {
            public bool CanHandle<T>(IQueryable<T> queryable)
            {
                return true;
            }

            public IEnumerable<T> ToFuture<T>(IQueryable<T> queryable)
            {
                return queryable;
            }

            public Lazy<T> ToFutureValue<T>(IQueryable<T> queryable)
            {
                return new Lazy<T>(() => queryable.SingleOrDefault());
            }

            public Lazy<TResult> ToFutureValue<TSource, TResult>(IQueryable<TSource> queryable, Expression<Func<IQueryable<TSource>, TResult>> selector)
            {
                return new Lazy<TResult>(() => selector.Compile()(queryable));
            }
        }

        static QueryableExtensions()
        {
            FutureConverters.Add(new LinqToObjectsFutureConverter());
        }

        /// <summary>
        /// Find items matching the specified expression
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="expression"></param>
        /// <param name="page">Page number to retrieve</param>
        /// <param name="pageSize">Number of items per page to retrieve (default: 10, max: 128)</param>
        /// <returns>A paged set of matching results</returns>
        public static PagedResult<T> Find<T>(this IQueryable<T> query, Expression<Func<T, bool>> expression = null,
                                                int page = 1, int pageSize = DefaultPageSize)
        {
            if (pageSize < 1 || pageSize > MaxPageSize)
            {
                throw new ArgumentOutOfRangeException("pageSize",
                    string.Format(
                    "Items per page must be a value between 1 and {0} (default is {1}", MaxPageSize, DefaultPageSize));
            }

            if (!(page > 0))
            {
                throw new ArgumentOutOfRangeException("page", "Page must be a value greater than zero");
            }

            if (expression != null)
            {
                query = query.Where(expression);
            }

            var count = AsFutureValue(query, x => x.Count());

            var items = AsFuture(query
                                     .Skip((page - 1) * pageSize)
                                     .Take(pageSize));

            return new PagedResult<T>(pageSize, () => count.Value, items);
        }

        /// <summary>
        /// Find one item matching the specified expression
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="expression"></param>
        /// <returns></returns>
        public static Lazy<T> FindOne<T>(this IQueryable<T> query, Expression<Func<T, bool>> expression = null)
        {
            if (expression == null)
            {
                return new Lazy<T>(() => AsFutureValue(query).Value);
            }

            query = query.Where(expression);

            return new Lazy<T>(() => AsFutureValue(query).Value);
        }

        /// <summary>
        /// Find one item matching the specified expression, throwing a <see cref="NoMatchFoundException"/> of no match is found
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="expression"></param>
        /// <returns></returns>
        public static Lazy<T> FindOneOrThrow<T>(this IQueryable<T> query, Expression<Func<T, bool>> expression = null)
            where T : class
        {
            var result = FindOne(query, expression);
            return new Lazy<T>(() =>
                {
                    var value = result.Value;
                    if (value == null)
                    {
                        throw new NoMatchFoundException("Expected a result but no matching result was found of type " +
                                                        typeof(T));
                    }
                    return value;
                });
        }

        public static void RegisterConverter(IFutureConverter converter)
        {
            FutureConverters.Insert(0, converter);
        }

        private static IFutureConverter GetConverter<T>(IQueryable<T> queryable)
        {
            return FutureConverters.First(x => x.CanHandle(queryable));
        }

        private static IEnumerable<T> AsFuture<T>(IQueryable<T> queryable)
        {
            return GetConverter(queryable).ToFuture(queryable);
        }

        private static Lazy<T> AsFutureValue<T>(IQueryable<T> queryable)
        {
            return GetConverter(queryable).ToFutureValue(queryable);
        }

        private static Lazy<TResult> AsFutureValue<TSource, TResult>(IQueryable<TSource> queryable, Expression<Func<IQueryable<TSource>, TResult>> selector) where TResult : struct
        {
            return GetConverter(queryable).ToFutureValue(queryable, selector);
        }
    }
}


text:
export default func => {
  const memoizedFunc = function(...args) {
    let result
    const key = JSON.stringify(args)
    if (memoizedFunc.cache[key] !== undefined) {
      result = memoizedFunc.cache[key]
    } else {
      result = func(...args)
      memoizedFunc.cache[key] = result
    }
    return result
  }
  memoizedFunc.cache = {}
  return memoizedFunc
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><author id="user243" lang="en">
	<document><![CDATA[I'm going to kick this bitch in the face if she doesn't stop snoring		]]></document>
	<document><![CDATA["@username: Who up ?"not Zoe		]]></document>
	<document><![CDATA[@username this bitch was just sleeping and you blew up her phone ????		]]></document>
	<document><![CDATA[Can't go home alone again need someone to numb the pain		]]></document>
	<document><![CDATA[I lose weight with anything ????		]]></document>
	<document><![CDATA["@username: To take a date to homecoming or no?" Hell nah		]]></document>
	<document><![CDATA[I feel like I have braces on		]]></document>
	<document><![CDATA[I hate everyone in school lol		]]></document>
	<document><![CDATA[They replaced arden b with wet seal, what am I going to do with my life ...		]]></document>
	<document><![CDATA[Trying to watch Kim n kanye get married and like 20 people r texting me srsly		]]></document>
	<document><![CDATA["@username: they tackle their problems together http://t.co/PoUvwJDYrS"bye		]]></document>
	<document><![CDATA[You're gone and I gotta stay high all the time to keep you out my mind		]]></document>
	<document><![CDATA["@username: Parallel enrollment on off days has me going places while everyone else is still at school ????" same ????		]]></document>
	<document><![CDATA[@username I'm so productive now		]]></document>
	<document><![CDATA[Don't understand why my face is so white compared to my body ????		]]></document>
	<document><![CDATA[I swear I talk to nobody till I look at my inbox		]]></document>
	<document><![CDATA[That just goes to show though how many people are actually close to me		]]></document>
	<document><![CDATA[You can have like 50 friends and still feel alone af		]]></document>
	<document><![CDATA[Need a nap		]]></document>
	<document><![CDATA[My dreams are so fucked up .,,		]]></document>
	<document><![CDATA[Even though I just had the most fucked up dream I am so calm		]]></document>
	<document><![CDATA[@username what a mature decision		]]></document>
	<document><![CDATA[Fuck a calc hw		]]></document>
	<document><![CDATA[@username I ran out of paper so this shit isn't getting done tonight		]]></document>
	<document><![CDATA[A days make me want to KMS cause that's the day I see annoying people		]]></document>
	<document><![CDATA["@username: I'm bored, quote with any pic of us :-)"this is so ugly http://t.co/FGcQLkXAAa		]]></document>
	<document><![CDATA[@username what ????		]]></document>
	<document><![CDATA[I want to wear a hoodie and jeans to school but it's gonna be hot af out. Do u see how hard my life is		]]></document>
	<document><![CDATA[I'm in a good mood right now even though there is literally nothing to be happy about :)))		]]></document>
	<document><![CDATA[My relationship goals are Kim and kanye		]]></document>
	<document><![CDATA[Crash is so cute		]]></document>
	<document><![CDATA[WHAT THE FUCK WHAT THE FUCK NO WHAT THE FUCK		]]></document>
	<document><![CDATA[This is so fucked up ????		]]></document>
	<document><![CDATA[@username omg it looks exactly like you		]]></document>
	<document><![CDATA[@username it's so cute		]]></document>
	<document><![CDATA[I think taylors being a lor harsh		]]></document>
	<document><![CDATA[If max dies I'm gonna cry though like fr		]]></document>
	<document><![CDATA["@username: White people smell like Microsoft Word 2007"????????????		]]></document>
	<document><![CDATA[Can American horror story come on already		]]></document>
	<document><![CDATA[It's funny when people try too hard to make a funny tweet		]]></document>
	<document><![CDATA[Don't understand how a girl can deal with a younger guy like I can barely tolerate guys my age...		]]></document>
	<document><![CDATA[@username well there's always gonna be some exceptions with everything		]]></document>
	<document><![CDATA[There's girls in school that I looks at think wow you're gonna be so pretty after high school		]]></document>
	<document><![CDATA[Kinda scared to sleep cause my dream earlier was pretty intense		]]></document>
	<document><![CDATA["@username: Bitch I'm the bomb like tick..tick.. ????????" ????		]]></document>
	<document><![CDATA[I'm too stubborn to ask for help when I need it, I wanna do everything on my own and I'm not sure I can do this alone anymore		]]></document>
	<document><![CDATA[I hate that everyone goes to ccbc. Yesterday alone I saw like half of perry hall ????		]]></document>
	<document><![CDATA[I find comfort in a tank top and a maxi skirt not some sweatpants and a Tshirt tbh		]]></document>
	<document><![CDATA[Some americans really fucking disgust me		]]></document>
	<document><![CDATA[@username like damn I don't wanna keep going to school with all of you		]]></document>
	<document><![CDATA[I know everything, if you think I don't know I probably already do or I'm gonna find out soon ???? I know shit I don't even wanna know		]]></document>
	<document><![CDATA[But that's really cause everyone tells me everything		]]></document>
	<document><![CDATA["@username: Life is disappointing. Whenever I feel like I'm doing well something always happens." My life		]]></document>
	<document><![CDATA[Me Zoe and Megan are so perfect together like I couldn't have anyone better to be my friends ????		]]></document>
	<document><![CDATA[I am honestly terrified of who's gonna ask me to prom		]]></document>
	<document><![CDATA[@username ID RATHER HAVE THAT FEAR		]]></document>
	<document><![CDATA[@username alone is better ????fuck a date		]]></document>
	<document><![CDATA[All a prom date is good for is pictures lmao		]]></document>
	<document><![CDATA[I'm only worried about being asked to prom because I literally hate everyone in school		]]></document>
	<document><![CDATA[@username I just don't wanna deal with saying no to people lmao		]]></document>
	<document><![CDATA[@username I miss u already :( http://t.co/DKVBGeMTPc		]]></document>
	<document><![CDATA[@username nobody got time to take you out		]]></document>
	<document><![CDATA[@username I hate you a lot		]]></document>
	<document><![CDATA[@username @username where'd this even come from		]]></document>
	<document><![CDATA[@username @username aw thanks :)		]]></document>
	<document><![CDATA[@username fuck that nigga		]]></document>
	<document><![CDATA[It's the second week of school and this bitch has already left Maryland ????		]]></document>
	<document><![CDATA[I want you so much but I hate your guts I hate you		]]></document>
	<document><![CDATA[Idk why I'm listening to daughter, they're always putting me in my feelings		]]></document>
	<document><![CDATA["@username: I don't think that foreign parents understand how hard it is to be born in a different culture with a different generation" this		]]></document>
	<document><![CDATA["@username: "you make my enchilada tingle, Guadeloupe"

"jorge, we are at escuela!!" http://t.co/FKRqosbnjD"laughing so hard		]]></document>
	<document><![CDATA[@username not even Mexican to begin with		]]></document>
	<document><![CDATA["@username: Colombian Moms.... http://t.co/eEB7rlfDFz"I'm dying		]]></document>
	<document><![CDATA[@username the page and the fact that he's talkin bout enchiladas ????		]]></document>
	<document><![CDATA[@username well my people don't really eat that		]]></document>
	<document><![CDATA[@username @username he's a lil slow		]]></document>
	<document><![CDATA[@username Thursday ????		]]></document>
	<document><![CDATA[Hate being early		]]></document>
	<document><![CDATA[Don't understand how I've managed to have such an annoying day and be in a good mood. My emotions are out of wack		]]></document>
	<document><![CDATA[@username where tf did U get that		]]></document>
	<document><![CDATA[@username okay thanks :)))		]]></document>
	<document><![CDATA["@username: The headaches ive been getting are so bad????" Me all the time ????		]]></document>
	<document><![CDATA[Really had to change my schedule now though????		]]></document>
	<document><![CDATA[When I don't feel like talking to anyone is when my phone is blowing up ????		]]></document>
	<document><![CDATA[@username who said I was replying to everyone		]]></document>
	<document><![CDATA["@username: Why tf is stealing phones such a big thing... like go get your broke ass a job"still salty		]]></document>
	<document><![CDATA[You guys all suck because you're literally up my ass 24/7 and now that I'm bored no ones talking to me		]]></document>
	<document><![CDATA[When I'm sad I listen to the flawless remix and remember I'm a bad bitch		]]></document>
	<document><![CDATA[I'm so harsh but I really don't give a shit		]]></document>
	<document><![CDATA["@username: Need something new in my life I'm bored"!!!!		]]></document>
	<document><![CDATA[@username rlly		]]></document>
	<document><![CDATA[@username who just faved and unfaved my pic		]]></document>
	<document><![CDATA[@username right cause you creepin????		]]></document>
	<document><![CDATA[@username but there's a human in there		]]></document>
	<document><![CDATA[Only me and Zoe cry together and then die laughing the next second		]]></document>
	<document><![CDATA["@username: accurate http://t.co/m7wbH21Bb4" this is so me????		]]></document>
	<document><![CDATA[I'm awake and hungry which are the worst things to be rn		]]></document>
	<document><![CDATA[If it ain't about the money, bitch you can miss me wit it		]]></document>
	<document><![CDATA[I'm bored n alone now		]]></document>
	<document><![CDATA[I'm older than Ronnie banks, that's weird to think about		]]></document>
</author>


text:
<?php

namespace Acme\DemoBundle\Model;

class NoteCollection
{
    /**
     * @var Note[]
     */
    public $notes;

    /**
     * @var integer
     */
    public $offset;

    /**
     * @var integer
     */
    public $limit;

    /**
     * @param Note[]  $notes
     * @param integer $offset
     * @param integer $limit
     */
    public function __construct($notes = array(), $offset = null, $limit = null)
    {
        $this->notes = $notes;
        $this->offset = $offset;
        $this->limit = $limit;
    }
}


text:
package org.osmdroid.util;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Fabrice Fontaine
 * @since 6.0.2
 */
public class UrlBackoff {

    private static final long[] mExponentialBackoffDurationInMillisDefault = new long[]{
            5000, 15000, 60000, 120000, 300000
    };

    private long[] mExponentialBackoffDurationInMillis = mExponentialBackoffDurationInMillisDefault;
    private final Map<String, Delay> mDelays = new HashMap<>();

    public void next(final String pUrl) {
        Delay delay;
        synchronized (mDelays) {
            delay = mDelays.get(pUrl);
        }
        if (delay == null) {
            delay = new Delay(mExponentialBackoffDurationInMillis);
            synchronized (mDelays) {
                mDelays.put(pUrl, delay);
            }
        } else {
            delay.next();
        }
    }

    public Delay remove(final String pUrl) {
        synchronized (mDelays) {
            return mDelays.remove(pUrl);
        }
    }

    public boolean shouldWait(final String pUrl) {
        final Delay delay;
        synchronized (mDelays) {
            delay = mDelays.get(pUrl);
        }
        return delay != null && delay.shouldWait();
    }

    public void clear() {
        synchronized (mDelays) {
            mDelays.clear();
        }
    }

    public void setExponentialBackoffDurationInMillis(final long[] pExponentialBackoffDurationInMillis) {
        mExponentialBackoffDurationInMillis = pExponentialBackoffDurationInMillis;
    }
}


text:
<?php

require_once 'function.tag.php';

function smarty_function_checkbox(array $params, Smarty_Internal_Template $template) {
    $isSwitch = isset($params['isSwitch']) ? (bool) $params['isSwitch'] : false;
    $checked = isset($params['checked']) ? (bool) $params['checked'] : false;
    $id = isset($params['id']) ? (string) $params['id'] : null;
    $label = (string) $params['label'];
    $name = isset($params['name']) ? (string) $params['name'] : null;
    $tabindex = isset($params['tabindex']) ? (int) $params['tabindex'] : null;
    $value = isset($params['value']) ? (string) $params['value'] : null;

    $classList = [];
    if (isset($params['class'])) {
        $classList[] = (string) $params['class'];
    }
    if ($isSwitch) {
        $classList[] = 'checkbox-switch';
    }

    if (null === $id) {
        $id = uniqid();
    }

    $html = smarty_function_tag([
        'el'       => 'input',
        'type'     => 'checkbox',
        'id'       => $id,
        'class'    => !empty($classList) ? implode(' ', $classList) : null,
        'checked'  => $checked ? 'checked' : null,
        'name'     => $name,
        'tabindex' => $tabindex,
        'value'    => $value,
    ], $template);

    $htmlLabelContent = '';
    if ($isSwitch) {
        $htmlLabelContent .= smarty_function_tag([
            'el'    => 'span',
            'class' => 'handle',
        ], $template);
    }
    $htmlLabelContent .= smarty_function_tag([
        'el'      => 'span',
        'content' => $label,
        'class'   => 'label',
    ], $template);

    $html .= smarty_function_tag([
        'el'      => 'label',
        'content' => $htmlLabelContent,
        'for'     => $id,
    ], $template);

    return $html;
}


text:
package org.adligo.tests4j_tests.trials_api.bad_mock_source_file_trials;

import java.util.List;

import org.adligo.tests4j.models.shared.metadata.I_TestMetadata;
import org.adligo.tests4j.models.shared.metadata.I_TrialMetadata;
import org.adligo.tests4j.models.shared.metadata.I_TrialRunMetadata;
import org.adligo.tests4j.models.shared.results.I_TrialFailure;
import org.adligo.tests4j.models.shared.results.I_TrialResult;
import org.adligo.tests4j.shared.asserts.common.I_Asserts;
import org.adligo.tests4j.shared.en.Tests4J_EnglishConstants;
import org.adligo.tests4j.shared.i18n.I_Tests4J_AnnotationMessages;
import org.adligo.tests4j.system.shared.trials.BeforeTrial;
import org.adligo.tests4j.system.shared.trials.SourceFileScope;
import org.adligo.tests4j.system.shared.trials.SourceFileTrial;
import org.adligo.tests4j.system.shared.trials.Test;
import org.adligo.tests4j.system.shared.trials.TrialRecursion;
import org.adligo.tests4j_tests.trials_api.common.ExpectedFailureRunner;
import org.adligo.tests4j_tests.trials_api.common.SystemRunnerMock;

/**
 * note this trial is run by the Run_SourceFileTrial_Trial,
 * and is intended to fail.
 *
 * @author scott
 *
 */
@SourceFileScope (sourceClass = NoSourceFileScopeAnnotationTrial.class)
@TrialRecursion
public class BeforeTrialHasParamsTrial extends SourceFileTrial {

	@BeforeTrial
	public static void beforeTrial(String p) {}

	@Test
	public void testFoo() {}

	public static void runTestDelegate(I_Asserts asserts)  throws Exception {
		ExpectedFailureRunner runner = new ExpectedFailureRunner();
		runner.run(BeforeTrialHasParamsTrial.class);

		I_TrialRunMetadata metadata = runner.getMetadata();
		asserts.assertNotNull(metadata);
		List<? extends I_TrialMetadata> trialsMetadata = metadata.getAllTrialMetadata();
		asserts.assertNotNull(trialsMetadata);
		asserts.assertEquals("java.util.Collections$UnmodifiableRandomAccessList",
				trialsMetadata.getClass().getName());
		asserts.assertEquals(1, trialsMetadata.size());
		I_TrialMetadata trialMeta = trialsMetadata.get(0);
		asserts.assertNotNull(trialMeta);
		asserts.assertEquals("org.adligo.tests4j_tests.trials_api.bad_mock_source_file_trials.BeforeTrialHasParamsTrial",
				trialMeta.getTrialName());
		asserts.assertEquals(0L, trialMeta.getTimeout());
		asserts.assertFalse(trialMeta.isIgnored());

		List<? extends I_TestMetadata> testsMetadata = trialMeta.getTests();
		asserts.assertNotNull(testsMetadata);
		asserts.assertEquals("java.util.Collections$UnmodifiableRandomAccessList",
				testsMetadata.getClass().getName());
		asserts.assertEquals(1, testsMetadata.size());
		I_TestMetadata testMeta = testsMetadata.get(0);
		asserts.assertNotNull(testMeta);
		asserts.assertEquals("testFoo", testMeta.getTestName());
		asserts.assertEquals(0L, testMeta.getTimeout());

		List<I_TrialResult> results = runner.getResults();
		asserts.assertEquals(1, results.size());
		I_TrialResult result = results.get(0);
		asserts.assertNotNull(result);
		asserts.assertFalse(result.isPassed());
		List<I_TrialFailure> failures = result.getFailures();
		asserts.assertNotNull(failures);
		asserts.assertEquals(1, failures.size());
		I_TrialFailure failure = failures.get(0);

		I_Tests4J_AnnotationMessages messages =  Tests4J_EnglishConstants.ENGLISH.getAnnotationMessages();
		asserts.assertEquals(messages.getBeforeTrialHasWrongParams(), failure.getMessage());
		asserts.assertEquals(
				"org.adligo.tests4j_tests.trials_api.bad_mock_source_file_trials.BeforeTrialHasParamsTrial was not annotated correctly.",
				failure.getFailureDetail());

		SystemRunnerMock tracker =  runner.getMockSystem();
		asserts.assertEquals(0, tracker.getLastStatus());
	}

	public static int getAsserts() {
		return 22;
	}
}


text:
/**
 * Created by Samuel Schmid on 23.03.14.
 *
 * Class for Download grunt dependencies
 *
 * @type {Setup}
 */
module.exports = Setup;

function Setup(grunt) {
    this.grunt = grunt;
    this.package = grunt.config().pkg;
    this.appconfig = grunt.config().appconfig;
}

Setup.prototype.downloadDependencies = function(context)  {
    var dependencies = this.package.dependencies;
    var appconfig = this.appconfig;
    var grunt = this.grunt;
    //
    //  grunt.log.debug(JSON.stringify(appconfig));
    var asyncTasks=[];
    for (var key in appconfig.db.dependencies) {
        if ( appconfig.db.dependencies.hasOwnProperty(key)) {

            if(dependencies.hasOwnProperty(key)) {
                grunt.log.debug("extension " +key +":" + JSON.stringify(appconfig.db.dependencies[key]));
                grunt.log.debug("package * " + key +":"+ JSON.stringify(dependencies[key]));
                //TODO install dependencies of db if newer version in config
            } else {

                var version = appconfig.db.dependencies[key];
                if(version === "*") {
                    version = "latest";
                }
                asyncTasks.push(
                    {
                        cmd:'npm',
                        args: ['install', key + "@" + version]
                    }
                );

            }

        }
    }

    var done = context.async();
    var next = function(index){
        var task = asyncTasks[index];
        grunt.log.write("\ninstall extension \n" + asyncTasks[index].args[1] );
        grunt.util.spawn(task, function(error,result) {
            grunt.log.write(result);

            if(error) {

                done(error)
            } else {
                if(asyncTasks.length > ++index) {

                    next(index);
                } else {

                    done(error);
                }
            }

        });
    }
    if(asyncTasks.length > 0) {
        var index = 0;
        next(index);

    }

}


text:
package org.apache.gobblin.service.modules.flow;

import com.typesafe.config.Config;

import org.apache.gobblin.runtime.api.FlowSpec;
import org.apache.gobblin.service.modules.flowgraph.DataNode;

/**
 * {@link DataMovementAuthorizer} that always returns true.
 */
public class NoopDataMovementAuthorizer implements DataMovementAuthorizer {
  public NoopDataMovementAuthorizer(Config config) {}

  public boolean isMovementAuthorized(FlowSpec flowSpec, DataNode sourceNode, DataNode destNode) {
    return true;
  }
}


text:
"""Drivers for streaming reductions framework."""

import warnings
# Dependency imports

import tensorflow.compat.v2 as tf
from tensorflow_probability.python.internal import loop_util
from tensorflow_probability.python.internal import prefer_static as ps
from tensorflow_probability.python.internal import samplers

__all__ = [
    'step_kernel',
]

def step_kernel(
    num_steps,
    current_state,
    previous_kernel_results=None,
    kernel=None,
    return_final_kernel_results=False,
    parallel_iterations=10,
    seed=None,
    name=None,
):
  """Takes `num_steps` repeated `TransitionKernel` steps from `current_state`.

  This is meant to be a minimal driver for executing `TransitionKernel`s; for
  something more featureful, see `sample_chain`.

  Args:
    num_steps: Integer number of Markov chain steps.
    current_state: `Tensor` or Python `list` of `Tensor`s representing the
      current state(s) of the Markov chain(s).
    previous_kernel_results: A `Tensor` or a nested collection of `Tensor`s.
      Warm-start for the auxiliary state needed by the given `kernel`.
      If not supplied, `step_kernel` will cold-start with
      `kernel.bootstrap_results`.
    kernel: An instance of `tfp.mcmc.TransitionKernel` which implements one step
      of the Markov chain.
    return_final_kernel_results: If `True`, then the final kernel results are
      returned alongside the chain state after `num_steps` steps are taken.
      This can be useful to inspect the final auxiliary state, or for a later
      warm restart.
    parallel_iterations: The number of iterations allowed to run in parallel. It
      must be a positive integer. See `tf.while_loop` for more details.
    seed: PRNG seed; see `tfp.random.sanitize_seed` for details.
    name: Python `str` name prefixed to Ops created by this function.
      Default value: `None` (i.e., 'mcmc_step_kernel').

  Returns:
    next_state: Markov chain state after `num_step` steps are taken, of
      identical type as `current_state`.
    final_kernel_results: kernel results, as supplied by `kernel.one_step` after
      `num_step` steps are taken. This is only returned if
      `return_final_kernel_results` is `True`.
  """
  is_seeded = seed is not None
  seed = samplers.sanitize_seed(seed, salt='experimental.mcmc.step_kernel')

  if not kernel.is_calibrated:
    warnings.warn('supplied `TransitionKernel` is not calibrated. Markov '
                  'chain may not converge to intended target distribution.')
  with tf.name_scope(name or 'mcmc_step_kernel'):
    num_steps = ps.convert_to_shape_tensor(
        num_steps, dtype_hint=tf.int32, name='num_steps')
    current_state = tf.nest.map_structure(
        lambda x: tf.convert_to_tensor(x, name='current_state'),
        current_state)
    if previous_kernel_results is None:
      previous_kernel_results = kernel.bootstrap_results(current_state)

    def _seeded_one_step(seed, *state_and_results):
      step_seed, passalong_seed = (
          samplers.split_seed(seed) if is_seeded else (None, seed))
      one_step_kwargs = dict(seed=step_seed) if is_seeded else {}
      return [passalong_seed] + list(
          kernel.one_step(*state_and_results, **one_step_kwargs))

    _, next_state, final_kernel_results = loop_util.smart_for_loop(
        loop_num_iter=num_steps,
        body_fn=_seeded_one_step,
        initial_loop_vars=list((seed, current_state, previous_kernel_results)),
        parallel_iterations=parallel_iterations)

    # return semantics are simple enough to not warrant the use of named tuples
    # as in `sample_chain`
    if return_final_kernel_results:
      return next_state, final_kernel_results
    else:
      return next_state


text:
<script src="../../es6-promise/es6-promise.min.js"></script>
<script src="../../es6-promise/es6-promise.auto.min.js"></script>