text:
package org.jetbrains.plugins.groovy.lang.psi.util;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.RecursionManager;
import com.intellij.openapi.util.Trinity;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiClassImplUtil;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.scope.ElementClassHint;
import com.intellij.psi.scope.NameHint;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.psi.util.*;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MostlySingularMultiMap;
import com.intellij.util.containers.hash.HashSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.GroovyLanguage;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrEnumConstantInitializer;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrReferenceList;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinitionBody;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAccessorMethod;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrGdkMethod;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrReflectedMethod;
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement;
import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.typedef.GrTypeDefinitionImpl;
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrScriptField;
import org.jetbrains.plugins.groovy.lang.resolve.CollectClassMembersUtil;
import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil;

import java.util.*;

/**
 * @author Maxim.Medvedev
 */
public class GrClassImplUtil {
  private static final Logger LOG = Logger.getInstance(GrClassImplUtil.class);

  private GrClassImplUtil() {
  }

  private static final Condition<PsiMethod> CONSTRUCTOR_CONDITION = PsiMethod::isConstructor;

  @NotNull
  public static GrMethod[] getCodeConstructors(@NotNull GrTypeDefinition definition) {
    GrMethod[] methods = definition.getCodeMethods();
    List<GrMethod> result = ContainerUtil.filter(methods, CONSTRUCTOR_CONDITION);
    return result.toArray(GrMethod.EMPTY_ARRAY);
  }

  @NotNull
  public static PsiMethod[] getConstructors(@NotNull GrTypeDefinition definition) {
    PsiMethod[] methods = definition.getMethods();
    List<PsiMethod> result = ContainerUtil.filter(methods, CONSTRUCTOR_CONDITION);
    return result.toArray(PsiMethod.EMPTY_ARRAY);
  }

  @Nullable
  public static PsiClass findInnerClassByName(GrTypeDefinition grType, String name, boolean checkBases) {
    if (!checkBases) {
      for (PsiClass inner : grType.getInnerClasses()) {
        if (name.equals(inner.getName())) return inner;
      }
      return null;
    }
    else {
      Map<String, CandidateInfo> innerClasses = CollectClassMembersUtil.getAllInnerClasses(grType, true);
      final CandidateInfo info = innerClasses.get(name);
      return info == null ? null : (PsiClass)info.getElement();
    }
  }

  @Nullable
  public static PsiClass getSuperClass(@NotNull GrTypeDefinition grType) {
    return getSuperClass(grType, grType.getExtendsListTypes());
  }

  @Nullable
  public static PsiClass getSuperClass(@NotNull GrTypeDefinition grType, @NotNull PsiClassType[] extendsListTypes) {
    if (extendsListTypes.length == 0) return getBaseClass(grType);
    final PsiClass superClass = extendsListTypes[0].resolve();
    return superClass != null ? superClass : getBaseClass(grType);
  }

  @Nullable
  public static PsiClass getBaseClass(GrTypeDefinition grType) {
    if (grType.isEnum()) {
      return JavaPsiFacade.getInstance(grType.getProject()).findClass(CommonClassNames.JAVA_LANG_ENUM, grType.getResolveScope());
    }
    else {
      return JavaPsiFacade.getInstance(grType.getProject()).findClass(CommonClassNames.JAVA_LANG_OBJECT, grType.getResolveScope());
    }
  }

  @NotNull
  public static PsiClassType[] getSuperTypes(GrTypeDefinition grType, boolean includeSynthetic) {
    PsiClassType[] extendsList = grType.getExtendsListTypes(includeSynthetic);
    if (extendsList.length == 0) {
      extendsList = new PsiClassType[]{createBaseClassType(grType)};
    }

    return ArrayUtil.mergeArrays(extendsList, grType.getImplementsListTypes(includeSynthetic), PsiClassType.ARRAY_FACTORY);
  }

  public static PsiClassType createBaseClassType(GrTypeDefinition grType) {
    if (grType.isEnum()) {
      return TypesUtil.createTypeByFQClassName(CommonClassNames.JAVA_LANG_ENUM, grType);
    }
    return TypesUtil.getJavaLangObject(grType);
  }

  @NotNull
  public static PsiMethod[] getAllMethods(final GrTypeDefinition grType) {
    return CachedValuesManager.getCachedValue(grType, () -> {
      List<PsiMethod> list = ContainerUtil.newArrayList();
      getAllMethodsInner(grType, list, new HashSet<>());
      return CachedValueProvider.Result
        .create(list.toArray(new PsiMethod[list.size()]), PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT, grType);
    });
  }

  @NotNull
  public static List<PsiMethod> getAllMethods(Collection<? extends PsiClass> classes) {
    List<PsiMethod> allMethods = new ArrayList<>();
    HashSet<PsiClass> visited = new HashSet<>();

    for (PsiClass psiClass : classes) {
      getAllMethodsInner(psiClass, allMethods, visited);
    }

    return allMethods;
  }

  private static void getAllMethodsInner(PsiClass clazz, List<PsiMethod> allMethods, HashSet<PsiClass> visited) {
    if (visited.contains(clazz)) return;
    visited.add(clazz);

    ContainerUtil.addAll(allMethods, clazz.getMethods());

    final PsiClass[] supers = clazz.getSupers();
    for (PsiClass aSuper : supers) {
      getAllMethodsInner(aSuper, allMethods, visited);
    }
  }

  public static PsiClassType[] getReferenceListTypes(@Nullable GrReferenceList list) {
    if (list == null) return PsiClassType.EMPTY_ARRAY;
    return list.getReferencedTypes();
  }

  @NotNull
  public static PsiClass[] getInterfaces(GrTypeDefinition grType) {
    final PsiClassType[] implementsListTypes = grType.getImplementsListTypes();
    List<PsiClass> result = new ArrayList<>(implementsListTypes.length);
    for (PsiClassType type : implementsListTypes) {
      final PsiClass psiClass = type.resolve();
      if (psiClass != null) result.add(psiClass);
    }
    return result.toArray(new PsiClass[result.size()]);
  }

  @NotNull
  public static PsiClass[] getSupers(GrTypeDefinition grType, boolean includeSynthetic) {
    PsiClassType[] superTypes = grType.getSuperTypes(includeSynthetic);
    List<PsiClass> result = new ArrayList<>();
    for (PsiClassType superType : superTypes) {
      PsiClass superClass = superType.resolve();
      if (superClass != null) {
        result.add(superClass);
      }
    }

    return result.toArray(new PsiClass[result.size()]);
  }

  public static boolean processDeclarations(@NotNull GrTypeDefinition grType,
                                            @NotNull PsiScopeProcessor processor,
                                            @NotNull ResolveState state,
                                            @Nullable PsiElement lastParent,
                                            @NotNull PsiElement place) {
    if (place instanceof GrCodeReferenceElement && lastParent instanceof GrModifierList) {
      final PsiElement possibleAnnotation = PsiTreeUtil.skipParentsOfType(place, GrCodeReferenceElement.class);
      if (possibleAnnotation instanceof GrAnnotation && possibleAnnotation.getParent() == lastParent) {
        return true; //don't process class members while resolving annotation which annotates current class
      }
    }

    for (final PsiTypeParameter typeParameter : grType.getTypeParameters()) {
      if (!ResolveUtil.processElement(processor, typeParameter, state)) return false;
    }

    NameHint nameHint = processor.getHint(NameHint.KEY);
    String name = nameHint == null ? null : nameHint.getName(state);
    ElementClassHint classHint = processor.getHint(ElementClassHint.KEY);
    final PsiSubstitutor substitutor = state.get(PsiSubstitutor.KEY);
    final PsiElementFactory factory = JavaPsiFacade.getElementFactory(place.getProject());

    boolean processInstanceMethods = (ResolveUtil.shouldProcessMethods(classHint) || ResolveUtil.shouldProcessProperties(classHint)) &&
                                     shouldProcessInstanceMembers(grType, lastParent);

    LanguageLevel level = PsiUtil.getLanguageLevel(place);
    if (ResolveUtil.shouldProcessProperties(classHint)) {
      Map<String, CandidateInfo> fieldsMap = CollectClassMembersUtil.getAllFields(grType);
      if (name != null) {
        CandidateInfo fieldInfo = fieldsMap.get(name);
        if (fieldInfo != null) {
          if (!processField(grType, processor, state, place, processInstanceMethods, substitutor, factory, level, fieldInfo)) {
            return false;
          }
        }
        else if (grType.isTrait() && lastParent != null) {
          PsiField field = findFieldByName(grType, name, false, true);
          if (field != null && field.hasModifierProperty(PsiModifier.PUBLIC)) {
            if (!processField(grType, processor, state, place, processInstanceMethods, substitutor, factory, level,
                              new CandidateInfo(field, PsiSubstitutor.EMPTY))) {
              return false;
            }
          }
        }
      }
      else {
        for (CandidateInfo info : fieldsMap.values()) {
          if (!processField(grType, processor, state, place, processInstanceMethods, substitutor, factory, level, info)) {
            return false;
          }
        }
        if (grType.isTrait() && lastParent != null) {
          for (PsiField field : CollectClassMembersUtil.getFields(grType, true)) {
            if (field.hasModifierProperty(PsiModifier.PUBLIC)) {
              if (!processField(grType, processor, state, place, processInstanceMethods, substitutor, factory, level,
                                new CandidateInfo(field, PsiSubstitutor.EMPTY))) {
                return false;
              }
            }
          }
        }
      }
    }

    if (ResolveUtil.shouldProcessMethods(classHint)) {
      Map<String, List<CandidateInfo>> methodsMap = CollectClassMembersUtil.getAllMethods(grType, true);
      boolean isPlaceGroovy = place.getLanguage() == GroovyLanguage.INSTANCE;
      if (name == null) {
        for (List<CandidateInfo> list : methodsMap.values()) {
          for (CandidateInfo info : list) {
            if (!processMethod(grType, processor, state, place, processInstanceMethods, substitutor, factory, level, isPlaceGroovy, info)) {
              return false;
            }
          }
        }
      }
      else {
        List<CandidateInfo> byName = methodsMap.get(name);
        if (byName != null) {
          for (CandidateInfo info : byName) {
            if (!processMethod(grType, processor, state, place, processInstanceMethods, substitutor, factory, level, isPlaceGroovy, info)) {
              return false;
            }
          }
        }
      }
    }

    final GrTypeDefinitionBody body = grType.getBody();
    if (body != null) {
      if (ResolveUtil.shouldProcessClasses(classHint)) {
        for (PsiClass innerClass : getInnerClassesForResolve(grType, lastParent, place)) {
          if (name != null && !name.equals(innerClass.getName())) continue;
          if (!processor.execute(innerClass, state)) return false;
        }
      }
    }

    return true;
  }

  private static boolean processField(@NotNull GrTypeDefinition grType,
                                      @NotNull PsiScopeProcessor processor,
                                      @NotNull ResolveState state,
                                      @NotNull PsiElement place,
                                      boolean processInstanceMethods,
                                      @NotNull PsiSubstitutor substitutor,
                                      @NotNull PsiElementFactory factory,
                                      @NotNull LanguageLevel level, CandidateInfo fieldInfo) {
    final PsiField field = (PsiField)fieldInfo.getElement();
    if (!shouldProcessTraitMember(grType, field, place)) return true;
    if (!processInstanceMember(processInstanceMethods, field) || isSameDeclaration(place, field)) {
      return true;
    }
    LOG.assertTrue(field.getContainingClass() != null);
    final PsiSubstitutor finalSubstitutor =
      PsiClassImplUtil.obtainFinalSubstitutor(field.getContainingClass(), fieldInfo.getSubstitutor(), grType, substitutor, factory, level);

    return processor.execute(field, state.put(PsiSubstitutor.KEY, finalSubstitutor));
  }

  private static boolean processMethod(@NotNull GrTypeDefinition grType,
                                       @NotNull PsiScopeProcessor processor,
                                       @NotNull ResolveState state,
                                       @NotNull PsiElement place,
                                       boolean processInstanceMethods,
                                       @NotNull PsiSubstitutor substitutor,
                                       @NotNull PsiElementFactory factory,
                                       @NotNull LanguageLevel level,
                                       boolean placeGroovy,
                                       @NotNull CandidateInfo info) {
    PsiMethod method = (PsiMethod)info.getElement();
    if (!shouldProcessTraitMember(grType, method, place)) return true;
    if (!processInstanceMember(processInstanceMethods, method) ||
        isSameDeclaration(place, method) ||
        !isMethodVisible(placeGroovy, method)) {
      return true;
    }
    LOG.assertTrue(method.getContainingClass() != null);
    final PsiSubstitutor finalSubstitutor =
      PsiClassImplUtil.obtainFinalSubstitutor(method.getContainingClass(), info.getSubstitutor(), grType, substitutor, factory, level);

    return processor.execute(method, state.put(PsiSubstitutor.KEY, finalSubstitutor));
  }

  private static boolean shouldProcessTraitMember(@NotNull GrTypeDefinition grType,
                                                  @NotNull PsiMember element,
                                                  @NotNull PsiElement place) {
    return !grType.isTrait() ||
           !element.hasModifierProperty(PsiModifier.STATIC) ||
           grType.equals(element.getContainingClass()) && PsiTreeUtil.isAncestor(grType, place, true);
  }

  private static boolean shouldProcessInstanceMembers(@NotNull GrTypeDefinition grType, @Nullable PsiElement lastParent) {
    if (lastParent != null) {
      final GrModifierList modifierList = grType.getModifierList();
      if (modifierList != null && modifierList.findAnnotation(GroovyCommonClassNames.GROOVY_LANG_CATEGORY) != null) {
        return false;
      }
    }
    return true;
  }

  private static boolean processInstanceMember(boolean shouldProcessInstance, @NotNull PsiMember member) {
    if (shouldProcessInstance) return true;

    if (member instanceof GrReflectedMethod) {
      return ((GrReflectedMethod)member).getBaseMethod().hasModifierProperty(PsiModifier.STATIC);
    }
    else {
      return member.hasModifierProperty(PsiModifier.STATIC);
    }
  }

  @NotNull
  private static List<PsiClass> getInnerClassesForResolve(@NotNull final GrTypeDefinition grType,
                                                          @Nullable final PsiElement lastParent,
                                                          @NotNull final PsiElement place) {
    if (lastParent instanceof GrReferenceList || PsiTreeUtil.getParentOfType(place, GrReferenceList.class) != null) {
      return Arrays.asList(grType.getCodeInnerClasses());
    }

    boolean includeSynthetic = !PsiTreeUtil.isContextAncestor(grType, place, true);
    Object key = Trinity.create(grType, lastParent, place);
    List<PsiClass> classes = RecursionManager.doPreventingRecursion(key, false, () -> {
      List<PsiClass> result = new ArrayList<>();
      for (CandidateInfo info : CollectClassMembersUtil.getAllInnerClasses(grType, includeSynthetic).values()) {
        final PsiClass inner = (PsiClass)info.getElement();
        final PsiClass containingClass = inner.getContainingClass();
        assert containingClass != null;

        if (lastParent == null || !containingClass.isInterface() || PsiTreeUtil.isAncestor(containingClass, place, false)) {
          ContainerUtil.addIfNotNull(result, inner);
        }
      }
      return result;
    });

    if (classes == null) {
      return Arrays.asList(grType.getCodeInnerClasses());
    }

    return classes;
  }

  public static boolean isSameDeclaration(PsiElement place, PsiElement element) {
    if (element instanceof GrAccessorMethod) element = ((GrAccessorMethod)element).getProperty();

    if (!(element instanceof GrField)) return false;
    if (element instanceof GrScriptField) element = ((GrScriptField)element).getOriginalVariable();

    while (place != null) {
      if (place == element) return true;
      place = place.getParent();
      if (place instanceof GrClosableBlock) return false;
      if (place instanceof GrEnumConstantInitializer) return false;
    }
    return false;
  }

  private static boolean isMethodVisible(boolean isPlaceGroovy, PsiMethod method) {
    return isPlaceGroovy || !(method instanceof GrGdkMethod);
  }

  @Nullable
  public static PsiMethod findMethodBySignature(GrTypeDefinition grType, PsiMethod patternMethod, boolean checkBases) {
    final MethodSignature patternSignature = patternMethod.getSignature(PsiSubstitutor.EMPTY);
    for (PsiMethod method : findMethodsByName(grType, patternMethod.getName(), checkBases, false)) {
      MethodSignature signature = getSignatureForInheritor(method, grType);
      if (patternSignature.equals(signature)) return method;
    }

    return null;
  }

  private static PsiMethod[] findMethodsByName(GrTypeDefinition grType,
                                               String name,
                                               boolean checkBases,
                                               boolean includeSyntheticAccessors) {
    if (!checkBases) {
      List<PsiMethod> result = new ArrayList<>();
      for (PsiMethod method : CollectClassMembersUtil.getMethods(grType, includeSyntheticAccessors)) {
        if (name.equals(method.getName())) result.add(method);
      }

      return result.toArray(new PsiMethod[result.size()]);
    }

    Map<String, List<CandidateInfo>> methodsMap = CollectClassMembersUtil.getAllMethods(grType, includeSyntheticAccessors);
    return PsiImplUtil.mapToMethods(methodsMap.get(name));
  }

  @NotNull
  public static PsiMethod[] findMethodsBySignature(GrTypeDefinition grType, PsiMethod patternMethod, boolean checkBases) {
    return findMethodsBySignature(grType, patternMethod, checkBases, true);
  }

  @NotNull
  public static PsiMethod[] findCodeMethodsBySignature(GrTypeDefinition grType, PsiMethod patternMethod, boolean checkBases) {
    return findMethodsBySignature(grType, patternMethod, checkBases, false);
  }

  @NotNull
  public static PsiMethod[] findMethodsByName(GrTypeDefinition grType, @NonNls String name, boolean checkBases) {
    return findMethodsByName(grType, name, checkBases, true);
  }

  private static PsiMethod[] findMethodsBySignature(GrTypeDefinition grType,
                                                    PsiMethod patternMethod,
                                                    boolean checkBases,
                                                    boolean includeSynthetic) {
    ArrayList<PsiMethod> result = new ArrayList<>();
    final MethodSignature patternSignature = patternMethod.getSignature(PsiSubstitutor.EMPTY);
    for (PsiMethod method : findMethodsByName(grType, patternMethod.getName(), checkBases, includeSynthetic)) {
      MethodSignature signature = getSignatureForInheritor(method, grType);
      if (patternSignature.equals(signature)) {
        result.add(method);
      }
    }
    return result.toArray(new PsiMethod[result.size()]);
  }

  @Nullable
  private static MethodSignature getSignatureForInheritor(@NotNull PsiMethod methodFromSuperClass, @NotNull GrTypeDefinition inheritor) {
    final PsiClass clazz = methodFromSuperClass.getContainingClass();
    if (clazz == null) return null;
    PsiSubstitutor superSubstitutor = TypeConversionUtil.getClassSubstitutor(clazz, inheritor, PsiSubstitutor.EMPTY);
    if (superSubstitutor == null) return null;

    return methodFromSuperClass.getSignature(superSubstitutor);
  }

  @NotNull
  public static PsiMethod[] findCodeMethodsByName(GrTypeDefinition grType, @NonNls String name, boolean checkBases) {
    return findMethodsByName(grType, name, checkBases, false);
  }

  @NotNull
  public static List<Pair<PsiMethod, PsiSubstitutor>> findMethodsAndTheirSubstitutorsByName(GrTypeDefinition grType,
                                                                                String name,
                                                                                boolean checkBases) {
    final ArrayList<Pair<PsiMethod, PsiSubstitutor>> result = new ArrayList<>();

    if (!checkBases) {
      final PsiMethod[] methods = grType.findMethodsByName(name, false);
      for (PsiMethod method : methods) {
        result.add(Pair.create(method, PsiSubstitutor.EMPTY));
      }
    }
    else {
      final Map<String, List<CandidateInfo>> map = CollectClassMembersUtil.getAllMethods(grType, true);
      final List<CandidateInfo> candidateInfos = map.get(name);
      if (candidateInfos != null) {
        for (CandidateInfo info : candidateInfos) {
          final PsiElement element = info.getElement();
          result.add(Pair.create((PsiMethod)element, info.getSubstitutor()));
        }
      }
    }

    return result;
  }

  @NotNull
  public static List<Pair<PsiMethod, PsiSubstitutor>> getAllMethodsAndTheirSubstitutors(GrTypeDefinition grType) {
    final Map<String, List<CandidateInfo>> allMethodsMap = CollectClassMembersUtil.getAllMethods(grType, true);
    List<Pair<PsiMethod, PsiSubstitutor>> result = new ArrayList<>();
    for (List<CandidateInfo> infos : allMethodsMap.values()) {
      for (CandidateInfo info : infos) {
        result.add(Pair.create((PsiMethod)info.getElement(), info.getSubstitutor()));
      }
    }

    return result;
  }

  @Nullable
  public static PsiField findFieldByName(GrTypeDefinition grType, String name, boolean checkBases, boolean includeSynthetic) {
    if (!checkBases) {
      for (PsiField field : CollectClassMembersUtil.getFields(grType, includeSynthetic)) {
        if (name.equals(field.getName())) return field;
      }

      return null;
    }

    Map<String, CandidateInfo> fieldsMap = CollectClassMembersUtil.getAllFields(grType, includeSynthetic);
    final CandidateInfo info = fieldsMap.get(name);
    return info == null ? null : (PsiField)info.getElement();
  }

  public static PsiField[] getAllFields(GrTypeDefinition grType) {
    return getAllFields(grType, true);
  }

  public static PsiField[] getAllFields(GrTypeDefinition grType, boolean includeSynthetic) {
    Map<String, CandidateInfo> fieldsMap = CollectClassMembersUtil.getAllFields(grType, includeSynthetic);
    return ContainerUtil.map2Array(fieldsMap.values(), PsiField.class, entry -> (PsiField)entry.getElement());
  }

  public static boolean isClassEquivalentTo(GrTypeDefinitionImpl definition, PsiElement another) {
    return PsiClassImplUtil.isClassEquivalentTo(definition, another);
  }

  @NotNull
  public static Collection<? extends PsiMethod> expandReflectedMethods(@NotNull PsiMethod method) {
    if (method instanceof GrMethod) {
      GrReflectedMethod[] methods = ((GrMethod)method).getReflectedMethods();
      if (methods.length > 0) {
        return ContainerUtil.newSmartList(methods);
      }
    }
    return Collections.singletonList(method);
  }

  @NotNull
  public static Set<MethodSignature> getDuplicatedSignatures(@NotNull PsiClass clazz) {
    return CachedValuesManager.getCachedValue(clazz, () -> {
      PsiElementFactory factory = JavaPsiFacade.getInstance(clazz.getProject()).getElementFactory();
      MostlySingularMultiMap<MethodSignature, PsiMethod> signatures = MostlySingularMultiMap.newMap();
      for (PsiMethod method : clazz.getMethods()) {
        MethodSignature signature = method.getSignature(factory.createRawSubstitutor(method));
        signatures.add(signature, method);
      }

      Set<MethodSignature> result = ContainerUtil.newHashSet();
      for (MethodSignature signature : signatures.keySet()) {
        if (signatures.valuesForKey(signature) > 1) {
          result.add(signature);
        }
      }

      return CachedValueProvider.Result.create(result, clazz);
    });
  }

  public static GrAccessorMethod findSetter(GrField field) {
    return CachedValuesManager.getCachedValue(field, () -> CachedValueProvider.Result.create(
      doGetSetter(field), PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT
    ));
  }

  @Nullable
  private static GrAccessorMethod doGetSetter(GrField field) {
    PsiClass containingClass = field.getContainingClass();
    if (containingClass == null) return null;
    PsiMethod[] setters = containingClass.findMethodsByName(GroovyPropertyUtils.getSetterName(field.getName()), false);
    for (PsiMethod setter : setters) {
      if (setter instanceof GrAccessorMethod) {
        return (GrAccessorMethod)setter;
      }
    }
    return null;
  }

  public static GrAccessorMethod[] findGetters(GrField field) {
    return CachedValuesManager.getCachedValue(field, () -> CachedValueProvider.Result.create(
      doGetGetters(field), PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT
    ));
  }

  @NotNull
  private static GrAccessorMethod[] doGetGetters(GrField field) {
    PsiClass containingClass = field.getContainingClass();
    if (containingClass == null) return GrAccessorMethod.EMPTY_ARRAY;

    GrAccessorMethod getter = null;
    GrAccessorMethod booleanGetter = null;

    PsiMethod[] getters = containingClass.findMethodsByName(GroovyPropertyUtils.getGetterNameNonBoolean(field.getName()), false);
    for (PsiMethod method : getters) {
      if (method instanceof GrAccessorMethod) {
        getter = (GrAccessorMethod)method;
        break;
      }
    }

    PsiMethod[] booleanGetters = containingClass.findMethodsByName(GroovyPropertyUtils.getGetterNameBoolean(field.getName()), false);
    for (PsiMethod method : booleanGetters) {
      if (method instanceof GrAccessorMethod) {
        booleanGetter = (GrAccessorMethod)method;
        break;
      }
    }

    if (getter != null && booleanGetter != null) {
      return new GrAccessorMethod[]{getter, booleanGetter};
    }
    else if (getter != null) {
      return new GrAccessorMethod[]{getter};
    }
    else {
      return GrAccessorMethod.EMPTY_ARRAY;
    }
  }
}


text:
package org.openkilda.integration.model;

import org.openkilda.model.DetectedDevice;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

import lombok.Data;

import java.io.Serializable;

/**
 * The Class FlowEndpoint.
 *
 * @author Gaurav Chugh
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder({"switch-id", "port-id", "vlan-id"})
@Data
public class FlowV2Endpoint implements Serializable {

    private static final long serialVersionUID = 1L;

    @JsonProperty("switch_id")
    private String switchId;

    @JsonProperty("port_number")
    private int portId;

    @JsonProperty("vlan_id")
    private int vlanId;

    @JsonProperty("inner_vlan_id")
    private int innerVlanId;

    @JsonProperty("switch-name")
    private String switchName;

    @JsonProperty("detect_connected_devices")
    private DetectedDevice detectedDevice;

    public String getSwitchId() {
        return switchId;
    }

    public void setSwitchId(final String switchId) {
        this.switchId = switchId;
    }

    public int getPortId() {
        return portId;
    }

    public void setPortId(final int portId) {
        this.portId = portId;
    }

    public int getVlanId() {
        return vlanId;
    }

    public void setVlanId(final int vlanId) {
        this.vlanId = vlanId;
    }

    public static long getSerialversionuid() {
        return serialVersionUID;
    }

    public String getSwitchName() {
        return switchName;
    }

    public void setSwitchName(String switchName) {
        this.switchName = switchName;
    }

    @Override
    public String toString() {
        return "FlowEndpoint [switchId=" + switchId + ", portId=" + portId + ", vlanId=" + vlanId
                + "]";
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.spike.giantdataanalysis.commons.annotation.constraint.runtime;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.LOCAL_VARIABLE;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PACKAGE;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Documented
@Retention(RUNTIME)
@Target({ TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, ANNOTATION_TYPE, PACKAGE })
public @interface Feature {

  boolean value() default false;

  /** alias of {@link #value()} */
  boolean switchs() default false;

  String version() default "1.0.0";

  Scope scope() default Scope.EXPRIMENT;

  enum Scope {
    EXPRIMENT, PRODUCTION
  }

  String description() default "";
}


text:
<?php
$profile=\App\User::find(Auth::user()->id)->profile;

$menu_list = \App\AdmMenu::select()
	->where('parent_id', null)
	->where('active', '1')
	->get();

if(!$profile->sa){
	$user_module=\App\AdmModule::select(['id', 'menu_id'])
		->whereIn('id', \App\AdmEvent::select()
			->whereIn('id', \App\AdmPermission::select()
				->where('profile_id', $profile->id)
				->pluck('event_id')
			)
			->pluck('module_id')
		)
		->where('active', '1');
}
else{
	$user_module=\App\AdmModule::select()
		->where('active', '1');
}

$current_smenu =\App\AdmMenu::FindOrFail($current_module->menu_id);
?>

{{ Auth::user()->name }}

			 Online

      @foreach ($menu_list as $menu)
		<?php
			$menu_name=strtoupper($menu->name);

			$smenus=\App\AdmMenu::select()
				->whereIn('id', $user_module->pluck('menu_id'))
				->where('parent_id', $menu->id)
				->where('active', '1')
				->get();

			if(count($smenus)==0) continue;
		?>

{{ $menu_name }}

        @foreach ($smenus as $smenu)
		  <?php
			  $smenu_id=$smenu->id;
			  $smenu_name =$smenu->name;
			  $smenu_icon=$smenu->icon!=''? $smenu->icon: '';
			  $smenu_class=$current_smenu==$smenu? 'active': '';

			  $modules=\App\AdmModule::select()
			  ->whereIn('id', $user_module->pluck('id'))
			  ->where('menu_id', $smenu_id)
			  ->where('active', '1')->get();

			  if(count($modules)==0) continue;
		  ?>

				 {{ $smenu_name }}

				@foreach ($modules as $module)
				  <?php
					$module_id	  = $module->id;
					$module_name  = $module->name;
					$params 	  = !empty($module->params)? '?'.$module->params: NULL;
					$module_url   = url('/admin/'.$module->controller.$params);
					$module_icon  = $module->icon!=''? $module->icon: 'fa-list';
				    $module_class = $module==$current_module? 'active': '';
				  ?>

 {{ $module_name }}

				@endforeach

        @endforeach

      @endforeach


text:
package com.danikula.videocache;

import android.text.TextUtils;

import com.danikula.videocache.file.FileCache;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

import static com.danikula.videocache.ProxyCacheUtils.DEFAULT_BUFFER_SIZE;

/**
 * {@link ProxyCache} that read http url and writes data to {@link Socket}
 *
 * @author Alexey Danilov (danikula@gmail.com).
 */
class HttpProxyCache extends ProxyCache {

    private static final float NO_CACHE_BARRIER = .2f;

    private final HttpUrlSource source;
    private final FileCache cache;
    private CacheListener listener;

    public HttpProxyCache(HttpUrlSource source, FileCache cache) {
        super(source, cache);
        this.cache = cache;
        this.source = source;
    }

    public void registerCacheListener(CacheListener cacheListener) {
        this.listener = cacheListener;
    }

    public void processRequest(GetRequest request, Socket socket) throws IOException, ProxyCacheException {
        OutputStream out = new BufferedOutputStream(socket.getOutputStream());
        String responseHeaders = newResponseHeaders(request);
        out.write(responseHeaders.getBytes("UTF-8"));

        long offset = request.rangeOffset;
        if (isUseCache(request)) {
            responseWithCache(out, offset);
        } else {
            responseWithoutCache(out, offset);
        }
    }

    private boolean isUseCache(GetRequest request) throws ProxyCacheException {
        int sourceLength = source.length();
        boolean sourceLengthKnown = sourceLength > 0;
        int cacheAvailable = cache.available();
        // do not use cache for partial requests which too far from available cache. It seems user seek video.
        return !sourceLengthKnown || !request.partial || request.rangeOffset <= cacheAvailable + sourceLength * NO_CACHE_BARRIER;
    }

    private String newResponseHeaders(GetRequest request) throws IOException, ProxyCacheException {
        String mime = source.getMime();
        boolean mimeKnown = !TextUtils.isEmpty(mime);
        int length = cache.isCompleted() ? cache.available() : source.length();
        boolean lengthKnown = length >= 0;
        long contentLength = request.partial ? length - request.rangeOffset : length;
        boolean addRange = lengthKnown && request.partial;
        return new StringBuilder()
                .append(request.partial ? "HTTP/1.1 206 PARTIAL CONTENT\n" : "HTTP/1.1 200 OK\n")
                .append("Accept-Ranges: bytes\n")
                .append(lengthKnown ? String.format("Content-Length: %d\n", contentLength) : "")
                .append(addRange ? String.format("Content-Range: bytes %d-%d/%d\n", request.rangeOffset, length - 1, length) : "")
                .append(mimeKnown ? String.format("Content-Type: %s\n", mime) : "")
                .append("\n") // headers end
                .toString();
    }

    private void responseWithCache(OutputStream out, long offset) throws ProxyCacheException, IOException {
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int readBytes;
        while ((readBytes = read(buffer, offset, buffer.length)) != -1) {
            out.write(buffer, 0, readBytes);
            offset += readBytes;
        }
        out.flush();
    }

    private void responseWithoutCache(OutputStream out, long offset) throws ProxyCacheException, IOException {
        try {
            HttpUrlSource source = new HttpUrlSource(this.source);
            source.open((int) offset);
            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            int readBytes;
            while ((readBytes = source.read(buffer)) != -1) {
                out.write(buffer, 0, readBytes);
                offset += readBytes;
            }
            out.flush();
        } finally {
            source.close();
        }
    }

    @Override
    protected void onCachePercentsAvailableChanged(int percents) {
        if (listener != null) {
            listener.onCacheAvailable(cache.file, source.url, percents);
        }
    }
}


text:
package com.openthinks.webscheduler.task;

/**
 * Description for Task definition, combine {@link TaskDefinitionDescriber} and {@link TaskRefDefinitionDescriber}
 * @author dailey.yet@outlook.com
 *
 */
public final class TaskDefinitionMetaData {
	private TaskDefinitionDescriber describer;
	private TaskRefDefinitionDescriber refDescriber;
	private Class<? extends ITaskDefinition> type;

	public TaskDefinitionMetaData(ITaskDefinition taskInstance) {
		this(taskInstance.getTaskDescriber(), taskInstance.getTaskRefDescriber());
	}

	public TaskDefinitionMetaData(TaskDefinitionDescriber describer, TaskRefDefinitionDescriber refDescriber) {
		super();
		this.describer = describer;
		this.refDescriber = refDescriber;
		if (describer != null)
			this.type = describer.getTaskClass();
	}

	public TaskDefinitionDescriber getDescriber() {
		return describer;
	}

	public void setDescriber(TaskDefinitionDescriber describer) {
		this.describer = describer;
	}

	public TaskRefDefinitionDescriber getRefDescriber() {
		return refDescriber;
	}

	public void setRefDescriber(TaskRefDefinitionDescriber refDescriber) {
		this.refDescriber = refDescriber;
	}

	@SuppressWarnings("unchecked")
	public <T extends ITaskDefinition> Class<T> getType() {
		return (Class<T>) type;
	}

	public <T extends ITaskDefinition> void setType(Class<T> type) {
		this.type = type;
	}

}


text:
import { Component, OnInit } from '@angular/core';
import {AppGlobals} from "../globals";

declare var $:any;

@Component({
  selector: 'app-rentabilidad',
  templateUrl: './rentabilidad.component.html',
  styleUrls: ['./rentabilidad.component.css']
})
export class rentabilidadComponent implements OnInit {

  constructor(  public _global: AppGlobals) {

  }

  ngOnInit() {
  }
}


text:
// Generated by CoffeeScript 1.9.2

(function() {
  var BackboneORM, BackboneREST, _, publish;

  _ = (BackboneORM = require('backbone-orm'))._;

  module.exports = BackboneREST = require('./core');

  publish = {
    configure: require('./lib/configure')
  };

  _.extend(BackboneREST, publish);

  BackboneREST.modules = {
    'backbone-orm': BackboneORM
  };

}).call(this);


text:
package com.x.app.util.loader;

public class DetailSeriesInfo {
	public final class DetailSeriesContent extends DetailBase {
		private String is_finish;
		private int cur_episode;
		private String max_episode;
		private int season_num;

		public String isFinish() {
			return is_finish;
		}

		public int getCurEpisode() {
			return cur_episode;
		}

		public String getMaxEpisode() {
			return max_episode;
		}

		public int getSeasonNum() {
			return season_num;
		}
	}
}


text:
title: Validation
page_title: Validation - RadGrid
description: Check our Web Forms article about Validation.
slug: grid/data-editing/validation/validation
tags: validation
published: True
position: 0
---

# Validation

In order to validate the input in RadGrid when editing and inserting records, you could use a combination of the ValidationSettings properties exposed by the control and validation controls added to make the validation in RadGrid more flexible.

## Validation settings

RadGrid exposes the ValidationSettings class to give you control over the validation on submit inside the control. The available properties are:

* **EnableValidation** - A boolean value indicating whether the grid values should be validated upon submit. Defaults to `true`.

* **CommandsToValidate** - An array of string used to list the names of the commands which will trigger validation in RadGrid. By default, they are `"PerformInsert, Update"`.

* **EnableModelValidation** - A boolean value indicating whether model validation should be enabled.

* **ValidationGroup** - A property used to set a ValidationGroup for the grid control, so that it is validated only along a certain group of controls having the same group name. By default, the grid does not have a validation group set, so if you set one for your validators, make sure to set it for the grid as well.

## Adding a validator to an edit field in Telerik RadGrid

RadGrid provides an easy way to add required field validators to your generated input controls in Edit mode. This feature is applicable to:

* **GridBoundColumn**

* **GridNumericColumn**

* **GridHTMLEditorColumn**

* **GridDropDownColumn**

* **GridDateTimeColumn**

The **ColumnValidationSettings** property is used to control validation of a given column editor via autogenerated **RequiredFieldValidator** and ModelBinding **ModelErrorMessage** control. This property is read-only, however, you can set the properties of the **ColumnValidationSettings** object it returns.

The properties can be set either declaratively or programmatically:

````ASP.NET
<telerik:GridBoundColumn DataField="ShipName" HeaderText="ShipName" UniqueName="ShipName">
    <ColumnValidationSettings EnableRequiredFieldValidation="true" EnableModelErrorMessageValidation="true">
        <RequiredFieldValidator ForeColor="Red" ErrorMessage="This field is required"></RequiredFieldValidator>
        <ModelErrorMessage BackColor="Red" />
    </ColumnValidationSettings>
</telerik:GridBoundColumn>
````

>note  **ModelErrorMessage** control validation is available only in the Assemblies targetting the `.NET 4.5` (e.g. Telerik version xxxx.x.xxx.45) when ModelBinding is used. See [Included Assemblies]({%slug introduction/installation/included-assemblies%})
>

## Adding a validator explicitly

In order to prevent the update operation if the user enters data in an edit field which is not in the correct format, you can wire the **ItemCreated** event of the grid to add a validator of your choice. There are four stages which need to be passed:

1. Check whether the current item is in edit mode;

2. Obtain reference to the respective **GridColumnEditor** instance and the editing control inside it;

3. Create the validator and set its **ControlToValidate** property to point to the editing control;

4. Add the validator to the Controls collection of the editing control Parent.

Below are the code snippets of an example in which we add **RequiredFieldValidator** to the **TextBox** editor of **GridBoundColumn**.

````ASP.NET
<telerik:RadGrid RenderMode="Lightweight" ID="RadGrid1" runat="server" AutoGenerateColumns="False">
  <MasterTableView>
    <Columns>
      <telerik:GridBoundColumn UniqueName="ContactName" HeaderText="ContactName" DataField="ContactName">
      </telerik:GridBoundColumn>
      <telerik:GridEditCommandColumn UniqueName="EditCommandColumn">
      </telerik:GridEditCommandColumn>
    </Columns>
  </MasterTableView>
</telerik:RadGrid>
````
````C#
protected void RadGrid1_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
    if (e.Item is GridEditableItem && e.Item.IsInEditMode)
    {
        GridEditableItem item = e.Item as GridEditableItem;
        GridTextBoxColumnEditor editor = (GridTextBoxColumnEditor)item.EditManager.GetColumnEditor("ContactName");
        TableCell cell = (TableCell)editor.TextBoxControl.Parent;

        RequiredFieldValidator validator = new RequiredFieldValidator();

        validator.ControlToValidate = editor.TextBoxControl.ID;
        validator.ErrorMessage = "*";
        cell.Controls.Add(validator);
    }
}
````
````VB
Protected Sub RadGrid1_ItemCreated(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs)
    If (TypeOf e.Item Is GridEditableItem AndAlso e.Item.IsInEditMode) Then
        Dim item As GridEditableItem = CType(e.Item, GridEditableItem)
        Dim editor As GridTextBoxColumnEditor = CType(item.EditManager.GetColumnEditor("ContactName"), GridTextBoxColumnEditor)
        Dim cell As TableCell = CType(editor.TextBoxControl.Parent, TableCell)
        Dim validator As RequiredFieldValidator = New RequiredFieldValidator
        validator.ControlToValidate = editor.TextBoxControl.ID
        validator.ErrorMessage = "*"
        cell.Controls.Add(validator)
    End If
End Sub
````

>note With version older than Q1 2013 you should use the code snippet below to add RequiredFieldValidator to the TextBox editor of GridBoundColumn
>

````ASP.NET
<telerik:RadGrid RenderMode="Lightweight" ID="RadGrid1" runat="server" AutoGenerateColumns="False">
  <MasterTableView>
    <Columns>
      <telerik:GridBoundColumn UniqueName="ContactName" HeaderText="ContactName" DataField="ContactName">
      </telerik:GridBoundColumn>
      <telerik:GridEditCommandColumn UniqueName="EditCommandColumn">
      </telerik:GridEditCommandColumn>
    </Columns>
  </MasterTableView>
</telerik:RadGrid>
````
````C#
protected void RadGrid1_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
    if (e.Item is GridEditableItem && e.Item.IsInEditMode)
    {
        GridEditableItem item = e.Item as GridEditableItem;
        GridTextBoxColumnEditor editor = (GridTextBoxColumnEditor)item.EditManager.GetColumnEditor("ContactName");
        TableCell cell = (TableCell)editor.TextBoxControl.Parent;

        RequiredFieldValidator validator = new RequiredFieldValidator();
        editor.TextBoxControl.ID = "ID_for_validation";
        validator.ControlToValidate = editor.TextBoxControl.ID;
        validator.ErrorMessage = "*";
        cell.Controls.Add(validator);
    }
}
````
````VB
Protected Sub RadGrid1_ItemCreated(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs)
    If (TypeOf e.Item Is GridEditableItem AndAlso e.Item.IsInEditMode) Then
        Dim item As GridEditableItem = CType(e.Item, GridEditableItem)
        Dim editor As GridTextBoxColumnEditor = CType(item.EditManager.GetColumnEditor("ContactName"), GridTextBoxColumnEditor)
        Dim cell As TableCell = CType(editor.TextBoxControl.Parent, TableCell)
        Dim validator As RequiredFieldValidator = New RequiredFieldValidator
        editor.TextBoxControl.ID = "ID_for_validation"
        validator.ControlToValidate = editor.TextBoxControl.ID
        validator.ErrorMessage = "*"
        cell.Controls.Add(validator)
    End If
End Sub
````

## Adding a custom validator explicitly

In order to prevent the update operation if the user enters data in an edit field which is not in the correct format, you can wire the **ItemCreated** event of the grid to add a validator of your choice. These steps will guide you through this process:

1. Check whether the current item is in edit mode;

2. Obtain reference to the respective **GridColumnEditor** instance and the editing control inside it;

3. Create the validator and set its **ControlToValidate** property to point to the editing control;

4. Enable the **ValidateEmptyText** property of the validator if you prefer to check for empty inputs as well;

5. Set the **ClientValidationFunction**;

6. Subscribe to the **ServerValidate** event;

7. Optionally, you can set the **ValidationGroup** to separate the validation logic of the insert, edit or multiple edit forms;

8. Add the validator to the Controls collection of the editing control Parent;

Below are the code snippets of an example in which we add **CustomValidator** to the **TextBox** editor of **GridBoundColumn**. If the new value does not contain the letter *a*, the validation will fail on client-side. And if the new value does not contain the letter *b*, the validation will fail this time on server-side.

````ASP.NET
<telerik:GridBoundColumn DataField="ShipName"
    FilterControlAltText="Filter ShipName column" HeaderText="ShipName"
    SortExpression="ShipName" UniqueName="ShipName">
</telerik:GridBoundColumn>
````
````JavaScript
function shipNameValidation(valEl, args) {
    // validate on client-side
    args.IsValid = args.Value.includes("a");
}
````
````C#
protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
{
    if (e.Item.IsInEditMode)
    {
        GridEditableItem item = e.Item as GridEditableItem;
        GridTextBoxColumnEditor editor = (GridTextBoxColumnEditor)item.EditManager.GetColumnEditor("ShipName");
        TableCell cell = (TableCell)editor.TextBoxControl.Parent;

        CustomValidator validator = new CustomValidator()
        {
            ID = "CustomValidatorShipName",
            ControlToValidate = editor.TextBoxControl.ID,
            ValidateEmptyText = true,
            ErrorMessage = "* Cannot be empty and should contain a and b",
            ForeColor = Color.OrangeRed,
            ClientValidationFunction = "shipNameValidation",
            ValidationGroup = editor.TextBoxControl.UniqueID
        };
        validator.ServerValidate += CustomValidatorShipName_ServerValidate;

        // prevent insert and edit forms to validate each other
        // this button can also be of type Button, ImageButton or LinkButton depending on the following property:
        // RadGrid1.MasterTableView.EditFormSettings.EditColumn.ButtonType = GridButtonColumnType.FontIconButton; (default)
        string buttonName = item is IGridInsertItem ? "PerformInsertButton" : "UpdateButton";
        (item.FindControl(buttonName) as ElasticButton).ValidationGroup = editor.TextBoxControl.UniqueID;

        cell.Controls.Add(validator);
    }
}
private void CustomValidatorShipName_ServerValidate(object source, ServerValidateEventArgs args)
{
    // validate on server-side
    args.IsValid = args.Value.Contains("b");
}
````
````VB
Protected Sub RadGrid1_ItemCreated(sender As Object, e As GridItemEventArgs)
    If e.Item.IsInEditMode Then
        Dim item As GridEditableItem = TryCast(e.Item, GridEditableItem)
        Dim editor As GridTextBoxColumnEditor = CType(item.EditManager.GetColumnEditor("ShipName"), GridTextBoxColumnEditor)
        Dim cell As TableCell = CType(editor.TextBoxControl.Parent, TableCell)
        Dim validator As CustomValidator = New CustomValidator() With {
            .ID = "CustomValidatorShipName",
            .ControlToValidate = editor.TextBoxControl.ID,
            .ValidateEmptyText = True,
            .ErrorMessage = "* Cannot be empty and should contain a and b",
            .ForeColor = Color.OrangeRed,
            .ClientValidationFunction = "shipNameValidation",
            .ValidationGroup = editor.TextBoxControl.UniqueID
        }
        AddHandler validator.ServerValidate, AddressOf CustomValidatorShipName_ServerValidate

        ' prevent insert And edit forms to validate each other
        ' this button can also be of type Button, ImageButton Or LinkButton depending on the following property:
        ' RadGrid1.MasterTableView.EditFormSettings.EditColumn.ButtonType = GridButtonColumnType.FontIconButton; (default)
        Dim buttonName As String = If(TypeOf item Is IGridInsertItem, "PerformInsertButton", "UpdateButton")
        TryCast(item.FindControl(buttonName), ElasticButton).ValidationGroup = editor.TextBoxControl.UniqueID
        cell.Controls.Add(validator)
    End If
End Sub
Protected Sub CustomValidatorShipName_ServerValidate(source As Object, args As ServerValidateEventArgs)
    ' validate on server-side
    args.IsValid = args.Value.Contains("b")
End Sub
````

You can find a runnable web site sample in the [Add Custom Validator Explicitly for RadGrid Editing ](https://www.telerik.com/support/code-library/add-custom-validator-explicitly-for-radgrid-editing) Code-Library.

## Adding a validator to EditItemTemplate of GridTemplateColumn

The approach is the same as with the standard MS DataGrid control. You can place the respective validator in the **EditItemTemplate** of your **GridTemplateColumn** and relate its **ControlToValidate** property with the ID of the control you would like to validate. In the forthcoming sample the **RequiredFieldValidator** control will validate the **TextBox** control inside the **EditItemTemplate**:

````ASP.NET
<telerik:RadGrid RenderMode="Lightweight" ID="RadGrid1" runat="server">
  <MasterTableView AutoGenerateColumns="False">
    <Columns>
      <telerik:GridTemplateColumn HeaderText="ContactName" UniqueName="TemplateColumn">
        <EditItemTemplate>
          <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ContactName") %>'></asp:TextBox>
          <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*"
            ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
        </EditItemTemplate>
        <ItemTemplate>
          <asp:Label ID="Label1" runat="server" Text='<%# Eval("ContactName") %>'></asp:Label>
        </ItemTemplate>
      </telerik:GridTemplateColumn>
      <telerik:GridEditCommandColumn UniqueName="EditCommandColumn">
      </telerik:GridEditCommandColumn>
    </Columns>
  </MasterTableView>
</telerik:RadGrid>
````

**Server-side validation**In some scenarios you may want to disable the client-side validation for the grid input and perform the whole validation process server-side.Here is a sample means to perform server-side validation using **CustomValidator** and its **ServerValidate** event (the validator error message will be displayed when the user enters string in the textbox with **ID=TextBox1** which starts with **X** character):

````ASP.NET
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("DataItem.Country") %>'>
</asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Invalid input"
  ControlToValidate="TextBox1" OnServerValidate="CustomValidator1_ServerValidate">
</asp:CustomValidator>
````
````C#
protected void CustomValidator1_ServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args)
{
    if (args.Value.StartsWith("X"))
    {
        args.IsValid = false;
    }
}
protected void RadGrid1_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
{
    if (e.CommandName == RadGrid.UpdateCommandName)
    {
        if (!Page.IsValid)
        {
            e.Canceled = true;
        }
    }
}
````
````VB
Protected Sub CustomValidator1_ServerValidate(ByVal [source] As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
    If args.Value.StartsWith("X") Then
        args.IsValid = False
    End If
End Sub 'CustomValidator1_ServerValidate

Protected Sub RadGrid1_ItemCommand(ByVal [source] As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.ItemCommand
    If e.CommandName = RadGrid.UpdateCommandName Then
        If Not Page.IsValid Then
            e.Canceled = True
        End If
    End If
End Sub 'RadGrid1_ItemCommand
````

**Custom validation** For more complex/custom validation operations you can extend the default ASP.NET validation and integrate CustomValidator control inside your grid instance. Here is an online resource which gives an example of operating with CustomValidators and configuring them to validate the user input as per your requirements:[https://aspnet.4guysfromrolla.com/articles/073102-1.aspx](https://aspnet.4guysfromrolla.com/articles/073102-1.aspx)


text:
NAME=timescaledb
# Default is to timescaledev to avoid unexpected push to the main repo
# Set ORG to timescale in the caller
ORG=timescaledev
PG_VER=pg12
PG_VER_NUMBER=$(shell echo $(PG_VER) | cut -c3-)
TS_VERSION=main
PREV_TS_VERSION=$(shell wget --quiet -O - https://raw.githubusercontent.com/timescale/timescaledb/${TS_VERSION}/version.config | grep update_from_version | sed -e 's!update_from_version = !!')
PREV_TS_IMAGE="timescale/timescaledb:$(PREV_TS_VERSION)-pg$(PG_VER_NUMBER)$(PREV_EXTRA)"
PREV_IMAGE=$(shell if docker pull $(PREV_TS_IMAGE) >/dev/null; then echo "$(PREV_TS_IMAGE)"; else echo "postgres:$(PG_VER_NUMBER)-alpine"; fi )
# Beta releases should not be tagged as latest, so BETA is used to track.
BETA=$(findstring rc,$(TS_VERSION))
PLATFORM=linux/386,linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64

# PUSH_MULTI can be set to nothing for dry-run without pushing during multi-arch build
PUSH_MULTI=--push
TAG_VERSION=$(ORG)/$(NAME):$(TS_VERSION)-$(PG_VER)
TAG_LATEST=$(ORG)/$(NAME):latest-$(PG_VER)
TAG=-t $(TAG_VERSION) $(if $(BETA),,-t $(TAG_LATEST))
TAG_OSS=-t $(TAG_VERSION)-oss $(if $(BETA),,-t $(TAG_LATEST)-oss)

default: image

.multi_$(TS_VERSION)_$(PG_VER)_oss: Dockerfile
	test -n "$(TS_VERSION)"  # TS_VERSION
	test -n "$(PREV_TS_VERSION)"  # PREV_TS_VERSION
	docker buildx create --platform $(PLATFORM) --name multibuild --use
	docker buildx inspect multibuild --bootstrap
	docker buildx build --platform $(PLATFORM) \
		--build-arg TS_VERSION=$(TS_VERSION) \
		--build-arg PG_VERSION=$(PG_VER_NUMBER) \
		--build-arg PREV_IMAGE=$(PREV_IMAGE) \
		--build-arg OSS_ONLY=" -DAPACHE_ONLY=1" \
		$(TAG_OSS) $(PUSH_MULTI) .
	touch .multi_$(TS_VERSION)_$(PG_VER)_oss
	docker buildx rm multibuild

.multi_$(TS_VERSION)_$(PG_VER): Dockerfile
	test -n "$(TS_VERSION)"  # TS_VERSION
	test -n "$(PREV_TS_VERSION)"  # PREV_TS_VERSION
	test -n "$(PREV_IMAGE)"  # PREV_IMAGE
	docker buildx create --platform $(PLATFORM) --name multibuild --use
	docker buildx inspect multibuild --bootstrap
	docker buildx build --platform $(PLATFORM) \
		--build-arg TS_VERSION=$(TS_VERSION) \
		--build-arg PREV_IMAGE=$(PREV_IMAGE) \
		--build-arg PG_VERSION=$(PG_VER_NUMBER) \
		$(TAG) $(PUSH_MULTI) .
	touch .multi_$(TS_VERSION)_$(PG_VER)
	docker buildx rm multibuild

.build_$(TS_VERSION)_$(PG_VER)_oss: Dockerfile
	docker build --build-arg OSS_ONLY=" -DAPACHE_ONLY=1" --build-arg PG_VERSION=$(PG_VER_NUMBER) $(TAG_OSS) .
	touch .build_$(TS_VERSION)_$(PG_VER)_oss

.build_$(TS_VERSION)_$(PG_VER): Dockerfile
	docker build --build-arg PG_VERSION=$(PG_VER_NUMBER) $(TAG) .
	touch .build_$(TS_VERSION)_$(PG_VER)

image: .build_$(TS_VERSION)_$(PG_VER)

oss: .build_$(TS_VERSION)_$(PG_VER)_oss

push: image
	docker push $(TAG_VERSION)
	if [ -z "$(BETA)" ]; then \
		docker push $(TAG_LATEST); \
	fi

push-oss: oss
	docker push $(TAG_VERSION)-oss
	if [ -z "$(BETA)" ]; then \
		docker push $(TAG_LATEST)-oss; \
	fi

multi: .multi_$(TS_VERSION)_$(PG_VER)

multi-oss: .multi_$(TS_VERSION)_$(PG_VER)_oss

all: multi multi-oss

clean:
	rm -f *~ .build_* .multi_*
	-docker buildx rm multibuild

.PHONY: default image push push-oss oss multi multi-oss clean all


text:
#ifndef VENOM_RUNTIME_BUILTIN_H
#define VENOM_RUNTIME_BUILTIN_H

#include <iostream>

#include <backend/vm.h>
#include <runtime/venomobject.h>

namespace venom {
namespace runtime {

backend::FunctionDescriptor& BuiltinPrintDescriptor();
extern std::ostream venom_stdout;
venom_ret_cell print(backend::ExecutionContext* ctx, venom_cell arg0);

}
}

#endif /* VENOM_RUNTIME_BUILTIN_H */


text:
package com.suscipio_solutions.consecro_mud.Abilities.Traps;
import java.util.HashSet;
import java.util.List;
import java.util.Vector;

import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg;
import com.suscipio_solutions.consecro_mud.Items.interfaces.Item;
import com.suscipio_solutions.consecro_mud.Items.interfaces.RawMaterial;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB;
import com.suscipio_solutions.consecro_mud.core.CMLib;
import com.suscipio_solutions.consecro_mud.core.interfaces.Drink;
import com.suscipio_solutions.consecro_mud.core.interfaces.Physical;

@SuppressWarnings({"unchecked","rawtypes"})
public class Bomb_Water extends StdBomb
{
	@Override public String ID() { return "Bomb_Water"; }
	private final static String localizedName = CMLib.lang().L("water bomb");
	@Override public String name() { return localizedName; }
	@Override protected int trapLevel(){return 1;}
	@Override public String requiresToSet(){return "a water container";}

	@Override
	public List<Item> getTrapComponents()
	{
		final Vector V=new Vector();
		V.addElement(CMLib.materials().makeItemResource(RawMaterial.RESOURCE_FRESHWATER));
		return V;
	}
	@Override
	public boolean canSetTrapOn(MOB mob, Physical P)
	{
		if(!super.canSetTrapOn(mob,P)) return false;
		if((!(P instanceof Drink))
		||(((Drink)P).liquidHeld()!=((Drink)P).liquidRemaining())
		||(((Drink)P).liquidType()!=RawMaterial.RESOURCE_FRESHWATER))
		{
			if(mob!=null)
				mob.tell(L("You need a full water container to make this out of."));
			return false;
		}
		return true;
	}
	@Override
	public void spring(MOB target)
	{
		if(target.location()!=null)
		{
			if((target==invoker())
			||(invoker().getGroupMembers(new HashSet<MOB>()).contains(target))
			||(doesSaveVsTraps(target)))
				target.location().show(target,null,null,CMMsg.MASK_ALWAYS|CMMsg.MSG_NOISE,L("<S-NAME> avoid(s) the water bomb!"));
			else
			if(target.location().show(invoker(),target,this,CMMsg.MASK_ALWAYS|CMMsg.MSG_NOISE,L("@x1 explodes water all over <T-NAME>!",affected.name())))
			{
				super.spring(target);
				CMLib.utensils().extinguish(invoker(),target,true);
			}
		}
	}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Helminthosporium microtrichum Corda

### Remarks
null


text:
name: Bug report
about: Something that doesn't work as documented or expected
title: ''
labels: ''
assignees: ''

---

**Describe the bug**
A clear and concise description of what the bug is.

**To Reproduce**
Steps to reproduce the behavior:
1. ...

**Expected behavior**
A clear and concise description of what you expected to happen.

**Screenshots**
If applicable, add screenshots to help explain your problem.

**Environment**
 - OS: [e.g. Windows/Linux]
 - Version [e.g. 1.0.2]