text:
package com.intellij.codeInspection.uncheckedWarnings;

import com.intellij.codeInsight.daemon.JavaErrorMessages;
import com.intellij.codeInsight.daemon.impl.analysis.JavaGenericsUtil;
import com.intellij.codeInsight.daemon.impl.analysis.JavaHighlightUtil;
import com.intellij.codeInsight.daemon.impl.quickfix.GenerifyFileFix;
import com.intellij.codeInsight.daemon.impl.quickfix.VariableArrayTypeFix;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.intention.QuickFixFactory;
import com.intellij.codeInsight.quickfix.ChangeVariableTypeQuickFixProvider;
import com.intellij.codeInspection.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.projectRoots.JavaVersionService;
import com.intellij.openapi.util.Pass;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.resolve.graphInference.PsiPolyExpressionUtil;
import com.intellij.psi.util.*;
import com.intellij.util.ui.JBUI;
import org.intellij.lang.annotations.Pattern;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Supplier;

public class UncheckedWarningLocalInspection extends AbstractBaseJavaLocalInspectionTool {
  @NonNls public static final String SHORT_NAME = "UNCHECKED_WARNING";
  public static final String DISPLAY_NAME = InspectionsBundle.message("unchecked.warning");
  @NonNls private static final String ID = "unchecked";
  private static final Logger LOG = Logger.getInstance("#" + UncheckedWarningLocalInspection.class);
  public boolean IGNORE_UNCHECKED_ASSIGNMENT;
  public boolean IGNORE_UNCHECKED_GENERICS_ARRAY_CREATION;
  public boolean IGNORE_UNCHECKED_CALL;
  public boolean IGNORE_UNCHECKED_CAST;
  public boolean IGNORE_UNCHECKED_OVERRIDING;

  @NotNull

  protected LocalQuickFix[] createFixes() {
    return new LocalQuickFix[]{new GenerifyFileFix()};
  }

  @Override
  public JComponent createOptionsPanel() {
    final JPanel panel = new JPanel(new GridBagLayout());
    final GridBagConstraints gc = new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
                                                         JBUI.emptyInsets(), 0, 0);

    panel.add(createSetting("Ignore unchecked assignment", IGNORE_UNCHECKED_ASSIGNMENT, new Pass<JCheckBox>() {
      @Override
      public void pass(JCheckBox cb) {
        IGNORE_UNCHECKED_ASSIGNMENT = cb.isSelected();
      }
    }), gc);

    panel.add(createSetting("Ignore unchecked generics array creation for vararg parameter", IGNORE_UNCHECKED_GENERICS_ARRAY_CREATION, new Pass<JCheckBox>() {
      @Override
      public void pass(JCheckBox cb) {
          IGNORE_UNCHECKED_GENERICS_ARRAY_CREATION = cb.isSelected();
      }
    }), gc);

    panel.add(createSetting("Ignore unchecked call as member of raw type", IGNORE_UNCHECKED_CALL, new Pass<JCheckBox>() {
      @Override
      public void pass(JCheckBox cb) {
        IGNORE_UNCHECKED_CALL = cb.isSelected();
      }
    }), gc);

    panel.add(createSetting("Ignore unchecked cast", IGNORE_UNCHECKED_CAST, new Pass<JCheckBox>() {
      @Override
      public void pass(JCheckBox cb) {
        IGNORE_UNCHECKED_CAST = cb.isSelected();
      }
    }), gc);

    panel.add(createSetting("Ignore unchecked overriding", IGNORE_UNCHECKED_OVERRIDING, new Pass<JCheckBox>() {
      @Override
      public void pass(JCheckBox cb) {
        IGNORE_UNCHECKED_OVERRIDING = cb.isSelected();
      }
    }), gc);

    gc.fill = GridBagConstraints.BOTH;
    gc.weighty = 1;
    panel.add(Box.createVerticalBox(), gc);

    return panel;
  }

  @NotNull
  static JCheckBox createSetting(@NotNull String cbText, final boolean option, @NotNull Pass<? super JCheckBox> pass) {
    final JCheckBox uncheckedCb = new JCheckBox(cbText, option);
    uncheckedCb.addActionListener(e -> pass.pass(uncheckedCb));
    return uncheckedCb;
  }

  @NotNull
  private static LocalQuickFix[] getChangeVariableTypeFixes(@NotNull PsiVariable parameter, @Nullable PsiType itemType, LocalQuickFix[] generifyFixes) {
    if (itemType instanceof PsiMethodReferenceType) return generifyFixes;
    LOG.assertTrue(parameter.isValid());
    final List<LocalQuickFix> result = new ArrayList<>();
    if (itemType != null) {
      for (ChangeVariableTypeQuickFixProvider fixProvider : ChangeVariableTypeQuickFixProvider.EP_NAME.getExtensionList()) {
        for (IntentionAction action : fixProvider.getFixes(parameter, itemType)) {
          if (action instanceof LocalQuickFix) {
            result.add((LocalQuickFix)action);
          }
        }
      }
    }

    if (generifyFixes.length > 0) {
      Collections.addAll(result, generifyFixes);
    }
    return result.toArray(LocalQuickFix.EMPTY_ARRAY);
  }

  @Override
  @NotNull
  public String getGroupDisplayName() {
    return "";
  }

  @Override
  @NotNull
  public String getDisplayName() {
    return DISPLAY_NAME;
  }

  @Override
  @NotNull
  @NonNls
  public String getShortName() {
    return SHORT_NAME;
  }

  @Override
  @Pattern(VALID_ID_PATTERN)
  @NotNull
  @NonNls
  public String getID() {
    return ID;
  }

  @Override
  public boolean isEnabledByDefault() {
    return true;
  }

  @Override
  public void writeSettings(@NotNull Element node) throws WriteExternalException {
    if (IGNORE_UNCHECKED_ASSIGNMENT ||
        IGNORE_UNCHECKED_CALL ||
        IGNORE_UNCHECKED_CAST ||
        IGNORE_UNCHECKED_OVERRIDING ||
        IGNORE_UNCHECKED_GENERICS_ARRAY_CREATION) {
      super.writeSettings(node);
    }
  }

  @NotNull
  @Override
  public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder,
                                        boolean isOnTheFly,
                                        @NotNull LocalInspectionToolSession session) {
    LanguageLevel languageLevel = PsiUtil.getLanguageLevel(session.getFile());
    if (!languageLevel.isAtLeast(LanguageLevel.JDK_1_5)) return super.buildVisitor(holder, isOnTheFly, session);

    return new UncheckedWarningsVisitor(isOnTheFly, languageLevel){
      @Override
      protected void registerProblem(@NotNull String message,
                                     @Nullable PsiElement callExpression,
                                     @NotNull PsiElement psiElement,
                                     @NotNull LocalQuickFix[] quickFixes) {
        final String rawExpression = isMethodCalledOnRawType(callExpression);
        if (rawExpression != null) {
          final String referenceName = ((PsiMethodCallExpression)callExpression).getMethodExpression().getReferenceName();
          message += ". Reason: '" + rawExpression + "' has raw type, so result of " + referenceName + " is erased";
        }
        holder.registerProblem(psiElement, message, quickFixes);
      }
    };
  }

  private static String isMethodCalledOnRawType(PsiElement expression) {
    if (expression instanceof PsiMethodCallExpression) {
      final PsiExpression qualifierExpression = ((PsiMethodCallExpression)expression).getMethodExpression().getQualifierExpression();
      if (qualifierExpression != null) {
        final PsiClass qualifierClass = PsiUtil.resolveClassInClassTypeOnly(qualifierExpression.getType());
        if (qualifierClass != null) {
          if (PsiUtil.isRawSubstitutor(qualifierClass, ((PsiMethodCallExpression)expression).resolveMethodGenerics().getSubstitutor())) {
            return qualifierExpression.getText();
          }
        }
      }
    }
    return null;
  }

  private abstract class UncheckedWarningsVisitor extends JavaElementVisitor {
    private final boolean myOnTheFly;
    @NotNull private final LanguageLevel myLanguageLevel;
    private final LocalQuickFix[] myGenerifyFixes;

    UncheckedWarningsVisitor(boolean onTheFly, @NotNull LanguageLevel level) {
      myOnTheFly = onTheFly;
      myLanguageLevel = level;
      myGenerifyFixes = onTheFly ? createFixes() : LocalQuickFix.EMPTY_ARRAY;
    }

    protected abstract void registerProblem(@NotNull String message,
                                            PsiElement callExpression,
                                            @NotNull PsiElement psiElement,
                                            @NotNull LocalQuickFix[] quickFixes);

    @Override
    public void visitReferenceExpression(PsiReferenceExpression expression) {
      if (IGNORE_UNCHECKED_GENERICS_ARRAY_CREATION) return;
      final JavaResolveResult result = expression.advancedResolve(false);
      if (JavaGenericsUtil.isUncheckedWarning(expression, result, myLanguageLevel)) {
        registerProblem("Unchecked generics array creation for varargs parameter", null, expression, LocalQuickFix.EMPTY_ARRAY);
      }
    }

    @Override
    public void visitNewExpression(PsiNewExpression expression) {
      super.visitNewExpression(expression);
      if (IGNORE_UNCHECKED_GENERICS_ARRAY_CREATION) return;
      final PsiJavaCodeReferenceElement classReference = expression.getClassOrAnonymousClassReference();
      if (classReference != null && JavaGenericsUtil.isUncheckedWarning(classReference, expression.resolveMethodGenerics(), myLanguageLevel)) {
        registerProblem("Unchecked generics array creation for varargs parameter", expression, classReference, LocalQuickFix.EMPTY_ARRAY);
      }
    }

    @Override
    public void visitTypeCastExpression(PsiTypeCastExpression expression) {
      super.visitTypeCastExpression(expression);
      if (IGNORE_UNCHECKED_CAST) return;
      final PsiTypeElement typeElement = expression.getCastType();
      if (typeElement == null) return;
      final PsiType castType = typeElement.getType();
      final PsiExpression operand = expression.getOperand();
      if (operand == null) return;
      final PsiType exprType = operand.getType();
      if (exprType == null) return;
      if (!TypeConversionUtil.areTypesConvertible(exprType, castType)) return;
      if (JavaGenericsUtil.isUncheckedCast(castType, exprType)) {
        final String description =
          JavaErrorMessages.message("generics.unchecked.cast", JavaHighlightUtil.formatType(exprType), JavaHighlightUtil
            .formatType(castType));
        registerProblem(description, operand, expression, myGenerifyFixes);
      }
    }

    @Override
    public void visitMethodReferenceExpression(PsiMethodReferenceExpression expression) {
      super.visitMethodReferenceExpression(expression);
      if (IGNORE_UNCHECKED_CALL) return;
      final JavaResolveResult result = expression.advancedResolve(false);
      final String description = getUncheckedCallDescription(expression, result);
      if (description != null) {
        final PsiElement referenceNameElement = expression.getReferenceNameElement();
        registerProblem(description, expression, referenceNameElement != null ? referenceNameElement : expression, myGenerifyFixes);
      }
    }

    @Override
    public void visitCallExpression(PsiCallExpression callExpression) {
      super.visitCallExpression(callExpression);
      final JavaResolveResult result = callExpression.resolveMethodGenerics();
      final String description = getUncheckedCallDescription(callExpression, result);
      if (description != null) {
        if (IGNORE_UNCHECKED_CALL) return;
        final PsiExpression element = callExpression instanceof PsiMethodCallExpression
                                         ? ((PsiMethodCallExpression)callExpression).getMethodExpression()
                                         : callExpression;
        registerProblem(description, null, element, myGenerifyFixes);
      }
      else {
        if (IGNORE_UNCHECKED_ASSIGNMENT) return;
        final PsiSubstitutor substitutor = result.getSubstitutor();
        final PsiExpressionList argumentList = callExpression.getArgumentList();
        if (argumentList != null) {
          final PsiMethod method = (PsiMethod)result.getElement();
          if (method != null) {
            final PsiExpression[] expressions = argumentList.getExpressions();
            final PsiParameter[] parameters = method.getParameterList().getParameters();
            if (parameters.length != 0) {
              for (int i = 0; i < expressions.length; i++) {
                PsiParameter parameter = parameters[Math.min(i, parameters.length - 1)];
                final PsiExpression expression = expressions[i];
                final PsiType parameterType = substitutor.substitute(parameter.getType());
                final PsiType expressionType = expression.getType();
                if (expressionType != null) {
                  checkRawToGenericsAssignment(expression, expression, parameterType, expressionType, () -> myGenerifyFixes);
                }
              }
            }
          }
        }
      }
    }

    @Override
    public void visitVariable(PsiVariable variable) {
      super.visitVariable(variable);
      if (IGNORE_UNCHECKED_ASSIGNMENT) return;
      PsiExpression initializer = variable.getInitializer();
      if (initializer == null || initializer instanceof PsiArrayInitializerExpression) return;
      final PsiType initializerType = initializer.getType();
      checkRawToGenericsAssignment(initializer, initializer, variable.getType(), initializerType,
                                   () -> myOnTheFly ? getChangeVariableTypeFixes(variable, initializerType, myGenerifyFixes) : LocalQuickFix.EMPTY_ARRAY);
    }

    @Override
    public void visitForeachStatement(PsiForeachStatement statement) {
      super.visitForeachStatement(statement);
      if (IGNORE_UNCHECKED_ASSIGNMENT) return;
      final PsiParameter parameter = statement.getIterationParameter();
      final PsiType parameterType = parameter.getType();
      final PsiExpression iteratedValue = statement.getIteratedValue();
      if (iteratedValue == null) return;
      final PsiType itemType = JavaGenericsUtil.getCollectionItemType(iteratedValue);
      checkRawToGenericsAssignment(parameter, iteratedValue, parameterType, itemType,
                                   () -> myOnTheFly ? getChangeVariableTypeFixes(parameter, itemType, myGenerifyFixes) : LocalQuickFix.EMPTY_ARRAY);
    }

    @Override
    public void visitAssignmentExpression(PsiAssignmentExpression expression) {
      super.visitAssignmentExpression(expression);
      if (IGNORE_UNCHECKED_ASSIGNMENT) return;
      if (!"=".equals(expression.getOperationSign().getText())) return;
      PsiExpression lExpr = expression.getLExpression();
      PsiExpression rExpr = expression.getRExpression();
      if (rExpr == null) return;
      PsiType lType = lExpr.getType();
      PsiType rType = rExpr.getType();
      if (rType == null) return;

      checkRawToGenericsAssignment(rExpr, rExpr, lType, rType, () -> {
        if (myOnTheFly && lExpr instanceof PsiReferenceExpression) {
          PsiElement element = ((PsiReferenceExpression)lExpr).resolve();
          if (element instanceof PsiVariable) {
            return getChangeVariableTypeFixes((PsiVariable)element, rType, myGenerifyFixes);
          }
        }

        return LocalQuickFix.EMPTY_ARRAY;
      });
    }

    @Override
    public void visitConditionalExpression(PsiConditionalExpression expression) {
      super.visitConditionalExpression(expression);
      if (PsiUtil.isLanguageLevel8OrHigher(expression) && PsiPolyExpressionUtil.isPolyExpression(expression)) {
        PsiType targetType = expression.getType();
        if (targetType == null) return;
        processConditionalPart(targetType, expression.getThenExpression());
        processConditionalPart(targetType, expression.getElseExpression());
      }
    }

    private void processConditionalPart(PsiType targetType, PsiExpression thenExpression) {
      if (thenExpression != null) {
        PsiType thenType = thenExpression.getType();
        if (thenType != null) {
          checkRawToGenericsAssignment(thenExpression, thenExpression, targetType, thenType, () -> myOnTheFly ? myGenerifyFixes : LocalQuickFix.EMPTY_ARRAY);
        }
      }
    }

    @Override
    public void visitArrayInitializerExpression(PsiArrayInitializerExpression arrayInitializer) {
      super.visitArrayInitializerExpression(arrayInitializer);
      if (IGNORE_UNCHECKED_ASSIGNMENT) return;
      final PsiType type = arrayInitializer.getType();
      if (!(type instanceof PsiArrayType)) return;
      final PsiType componentType = ((PsiArrayType)type).getComponentType();

      boolean arrayTypeFixChecked = false;
      VariableArrayTypeFix fix = null;

      final PsiExpression[] initializers = arrayInitializer.getInitializers();
      for (PsiExpression expression : initializers) {
        final PsiType itemType = expression.getType();

        if (itemType == null) continue;
        if (!TypeConversionUtil.isAssignable(componentType, itemType)) continue;
        if (JavaGenericsUtil.isRawToGeneric(componentType, itemType)) {
          String description = JavaErrorMessages.message("generics.unchecked.assignment",
                                                         JavaHighlightUtil.formatType(itemType),
                                                         JavaHighlightUtil.formatType(componentType));
          if (!arrayTypeFixChecked) {
            final PsiType checkResult = JavaHighlightUtil.sameType(initializers);
            fix = checkResult != null ? VariableArrayTypeFix.createFix(arrayInitializer, checkResult) : null;
            arrayTypeFixChecked = true;
          }

          if (fix != null) {
            registerProblem(description, null, expression, new LocalQuickFix[]{fix});
          }
        }
      }
    }

    private void checkRawToGenericsAssignment(@NotNull PsiElement parameter,
                                              PsiExpression expression, PsiType parameterType,
                                              PsiType itemType,
                                              final Supplier<LocalQuickFix[]> fixesSupplier) {
      if (parameterType == null || itemType == null) return;
      if (!TypeConversionUtil.isAssignable(parameterType, itemType)) return;
      if (JavaGenericsUtil.isRawToGeneric(parameterType, itemType)) {
        String description = JavaErrorMessages.message("generics.unchecked.assignment",
                                                       JavaHighlightUtil.formatType(itemType),
                                                       JavaHighlightUtil.formatType(parameterType));
        registerProblem(description, expression, parameter, fixesSupplier.get());
      }
    }

    @Override
    public void visitMethod(PsiMethod method) {
      super.visitMethod(method);
      if (IGNORE_UNCHECKED_OVERRIDING) return;
      if (!method.isConstructor()) {
        List<HierarchicalMethodSignature> superMethodSignatures = method.getHierarchicalMethodSignature().getSuperSignatures();
        if (!superMethodSignatures.isEmpty() && !method.hasModifierProperty(PsiModifier.STATIC)) {
          final MethodSignature signature = method.getSignature(PsiSubstitutor.EMPTY);
          for (MethodSignatureBackedByPsiMethod superSignature : superMethodSignatures) {
            PsiMethod baseMethod = superSignature.getMethod();
            PsiSubstitutor substitutor = MethodSignatureUtil.getSuperMethodSignatureSubstitutor(signature, superSignature);
            if (substitutor == null) substitutor = superSignature.getSubstitutor();
            if (PsiUtil.isRawSubstitutor(baseMethod, superSignature.getSubstitutor())) continue;
            final PsiType baseReturnType = substitutor.substitute(baseMethod.getReturnType());
            final PsiType overriderReturnType = method.getReturnType();
            if (baseReturnType == null || overriderReturnType == null) return;
            if (JavaGenericsUtil.isRawToGeneric(baseReturnType, overriderReturnType)) {
              final String message = JavaErrorMessages.message("unchecked.overriding.incompatible.return.type",
                                                               JavaHighlightUtil.formatType(overriderReturnType),
                                                               JavaHighlightUtil.formatType(baseReturnType));

              final PsiTypeElement returnTypeElement = method.getReturnTypeElement();
              LOG.assertTrue(returnTypeElement != null);
              registerProblem(message, null, returnTypeElement, LocalQuickFix.EMPTY_ARRAY);
            }
          }
        }
      }
    }

    @Override
    public void visitReturnStatement(PsiReturnStatement statement) {
      super.visitReturnStatement(statement);
      if (IGNORE_UNCHECKED_ASSIGNMENT) return;
      final PsiType returnType = PsiTypesUtil.getMethodReturnType(statement);
      if (returnType != null && !PsiType.VOID.equals(returnType)) {
        final PsiExpression returnValue = statement.getReturnValue();
        if (returnValue != null) {
          final PsiType valueType = returnValue.getType();
          if (valueType != null) {
            checkRawToGenericsAssignment(returnValue, returnValue, returnType, valueType, () -> {
              final PsiElement psiElement = PsiTreeUtil.getParentOfType(statement, PsiMethod.class, PsiLambdaExpression.class);
              return psiElement instanceof PsiMethod
                     ? new LocalQuickFix[]{QuickFixFactory.getInstance().createMethodReturnFix((PsiMethod)psiElement, valueType, true)}
                     : LocalQuickFix.EMPTY_ARRAY;
            });
          }
        }
      }
    }

    @Override
    public void visitLambdaExpression(PsiLambdaExpression expression) {
      super.visitLambdaExpression(expression);

      if (IGNORE_UNCHECKED_ASSIGNMENT) return;
      PsiElement body = expression.getBody();
      if (body instanceof PsiExpression) {
        PsiType interfaceReturnType = LambdaUtil.getFunctionalInterfaceReturnType(expression);
        if (interfaceReturnType != null && !PsiType.VOID.equals(interfaceReturnType)) {
          PsiType type = ((PsiExpression)body).getType();
          if (type != null) {
            checkRawToGenericsAssignment(body, (PsiExpression)body, interfaceReturnType, type, () -> LocalQuickFix.EMPTY_ARRAY);
          }
        }
      }
    }

    @Nullable
    private String getUncheckedCallDescription(PsiElement place, JavaResolveResult resolveResult) {
      final PsiElement element = resolveResult.getElement();
      if (!(element instanceof PsiMethod)) return null;
      final PsiMethod method = (PsiMethod)element;
      final PsiSubstitutor substitutor = resolveResult.getSubstitutor();
      if (!PsiUtil.isRawSubstitutor(method, substitutor)) {
        if (JavaVersionService.getInstance().isAtLeast(place, JavaSdkVersion.JDK_1_8)) {
          for (PsiTypeParameter parameter : method.getTypeParameters()) {
            final PsiClassType[] extendsListTypes = parameter.getExtendsListTypes();
            if (extendsListTypes.length > 0) {
              final PsiType subst = substitutor.substitute(parameter);
              for (PsiClassType classType : extendsListTypes) {
                if (JavaGenericsUtil.isRawToGeneric(substitutor.substitute(classType), subst)) {
                  return JavaErrorMessages.message("generics.unchecked.call", JavaHighlightUtil.formatMethod(method));
                }
              }
            }
          }
        }
        return null;
      }
      final PsiParameter[] parameters = method.getParameterList().getParameters();
      for (final PsiParameter parameter : parameters) {
        final PsiType parameterType = parameter.getType();
        if (parameterType.accept(new PsiTypeVisitor<Boolean>() {
          @Override
          public Boolean visitPrimitiveType(PsiPrimitiveType primitiveType) {
            return Boolean.FALSE;
          }

          @Override
          public Boolean visitArrayType(PsiArrayType arrayType) {
            return arrayType.getComponentType().accept(this);
          }

          @Override
          public Boolean visitClassType(PsiClassType classType) {
            PsiClassType.ClassResolveResult result = classType.resolveGenerics();
            PsiClass psiClass = result.getElement();
            if (psiClass instanceof PsiTypeParameter) {
              if (((PsiTypeParameter)psiClass).getOwner() == method) return Boolean.FALSE;
              return substitutor.substitute((PsiTypeParameter)psiClass) == null ? Boolean.TRUE : Boolean.FALSE;
            }
            if (psiClass != null) {
              PsiSubstitutor typeSubstitutor = result.getSubstitutor();
              for (PsiTypeParameter parameter : PsiUtil.typeParametersIterable(psiClass)) {
                PsiType psiType = typeSubstitutor.substitute(parameter);
                if (psiType != null && psiType.accept(this).booleanValue()) return Boolean.TRUE;
              }
            }
            return Boolean.FALSE;
          }

          @Override
          public Boolean visitWildcardType(PsiWildcardType wildcardType) {
            PsiType bound = wildcardType.getBound();
            if (bound != null) return bound.accept(this);
            return Boolean.TRUE;
          }

          @Override
          public Boolean visitEllipsisType(PsiEllipsisType ellipsisType) {
            return ellipsisType.getComponentType().accept(this);
          }
        }).booleanValue()) {
          final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(method.getProject());
          PsiType type = elementFactory.createType(method.getContainingClass(), substitutor);
          return JavaErrorMessages.message("generics.unchecked.call.to.member.of.raw.type",
                                                         JavaHighlightUtil.formatMethod(method),
                                                         JavaHighlightUtil.formatType(type));
        }
      }
      return null;
    }
  }
}


text:
<?php
/* @var $this ArticleCategoryController */
/* @var $model ArticleCategory */

$this->breadcrumbs=array(
	'Article Categories'=>array('index'),
	'Create',
);

$this->menu=array(
	array('label'=>'List ArticleCategory', 'url'=>array('index')),
	array('label'=>'Manage ArticleCategory', 'url'=>array('admin')),
);
?>

Create ArticleCategory

<?php echo $this->renderPartial('_form', array('model'=>$model)); ?>

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Amathista - PHP Framework
 *
 * @author Alex J. Rondón <arondn2@gmail.com>
 *
 */

/**
 * Clase para excepciones en Amathista
 */
class AmError extends Exception{

}


text:
package com.jk.util.model.table;

import java.util.Vector;

// TODO: Auto-generated Javadoc
/**
 * The Class JKColumnFilter.
 *
 * @author Jalal Kiswani
 */
public class JKColumnFilter {

	/**
	 * The Enum FilterType.
	 */
	enum FilterType {

	/** The equals. */
	EQUALS,
	/** The contains. */
	CONTAINS,
	/** The more than. */
	MORE_THAN,
	/** The less than. */
	LESS_THAN,
	/** The between. */
	BETWEEN,
	/** The doesnot contains. */
	DOESNOT_CONTAINS,
	/** The starts width. */
	STARTS_WIDTH,
	/** The ends with. */
	ENDS_WITH;

		/**
		 * Required fields count.
		 *
		 * @return the int
		 */
		public int requiredFieldsCount() {
			if (this == BETWEEN) {
				return 2;
			}
			return 1;
		}
	}

	/** The type. */
	FilterType type = FilterType.CONTAINS;

	/** The values. */
	Vector values = new Vector();

	/** The column. */
	JKTableColumn column;

	/** The required. */
	boolean required;

	/**
	 * Instantiates a new JK column filter.
	 *
	 * @param column the column
	 */
	public JKColumnFilter(final JKTableColumn column) {
		this.column = column;
	}

	/**
	 * Gets the column.
	 *
	 * @return the column
	 */
	public JKTableColumn getColumn() {
		return this.column;
	}

	/**
	 * Gets the type.
	 *
	 * @return the type
	 */
	public FilterType getType() {
		return this.type;
	}

	/**
	 * Gets the values.
	 *
	 * @return the values
	 */
	public Vector getValues() {
		return this.values;
	}

	/**
	 * Checks if is required.
	 *
	 * @return true, if is required
	 */
	public boolean isRequired() {
		return this.required;
	}

	/**
	 * Sets the column.
	 *
	 * @param column the new column
	 */
	public void setColumn(final JKTableColumn column) {
		this.column = column;
	}

	/**
	 * Sets the required.
	 *
	 * @param required the new required
	 */
	public void setRequired(final boolean required) {
		this.required = required;
	}

	/**
	 * Sets the type.
	 *
	 * @param type the new type
	 */
	public void setType(final FilterType type) {
		this.type = type;
	}

	/**
	 * Sets the values.
	 *
	 * @param values the new values
	 */
	public void setValues(final Vector values) {
		this.values = values;
	}

	/**
	 * To query string.
	 *
	 * @return the string
	 */
	public String toQueryString() {
		final StringBuffer buf = new StringBuffer();
		final Object value1 = this.values.get(0);
		buf.append(this.column.getName());
		switch (this.type) {
		case STARTS_WIDTH:
			buf.append(" like '" + value1 + "%'");
			break;
		case CONTAINS:
			buf.append(" like '%" + value1 + "%'");
			break;
		case ENDS_WITH:
			buf.append(" like '%" + value1 + "'");
			break;
		case DOESNOT_CONTAINS:
			buf.append(" not like '%" + value1 + "%'");
			break;
		case MORE_THAN:
			buf.append(" > '" + value1 + "'");
			break;
		case LESS_THAN:
			buf.append(" < '" + value1 + "'");
			break;
		}
		return buf.toString();
	}
}


text:
from django.contrib import admin

from grades.models import *

class CourseAdmin(admin.ModelAdmin):
    model = Course

class GradeAdmin(admin.ModelAdmin):
    list_display = ('course', 'semester_code', 'average_grade')
    model = Grade

class TagAdmin(admin.ModelAdmin):
    list_display = ('tag', 'course_list')
    model = Tag

    def course_list(self, obj):
        return ", ".join([c.code for c in obj.courses.all()])

admin.site.register(Course, CourseAdmin)
admin.site.register(Grade, GradeAdmin)
admin.site.register(Tag, TagAdmin)


text:
package ecs

import (
	"sort"
)

// World contains a bunch of Entities, and a bunch of Systems. It is the
// recommended way to run ecs.
type World struct {
	systems systems
}

// AddSystem adds the given System to the World, sorted by priority.
func (w *World) AddSystem(system System) {
	if initializer, ok := system.(Initializer); ok {
		initializer.New(w)
	}

	w.systems = append(w.systems, system)
	sort.Sort(w.systems)
}

// Systems returns the list of Systems managed by the World.
func (w *World) Systems() []System {
	return w.systems
}

// Update updates each System managed by the World. It is invoked by the engine
// once every frame, with dt being the duration since the previous update.
func (w *World) Update(dt float32) {
	for _, system := range w.Systems() {
		system.Update(dt)
	}
}

// RemoveEntity removes the entity across all systems.
func (w *World) RemoveEntity(e BasicEntity) {
	for _, sys := range w.systems {
		sys.Remove(e)
	}
}


text:
const gulp = require('gulp');
const eslint = require('gulp-eslint');
const webserver = require('gulp-webserver');
const webpack = require('webpack');

const dest = __dirname + '/dist';

gulp.task('default', ['webpack', 'lint'], () => {});

gulp.task('lint', function () {
    return gulp.src(['js/**/*.js'])
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

gulp.task('webpack', function(callback) {
    webpack({
        context: __dirname + '/js',
        entry: './app.js',
        output: {
            path: dest,
            filename: 'bundle.js'
        },
        module: {
            loaders: [{
                test: /\.js$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'babel',
                query: {
                    presets: ['react', 'es2015']
                }
            }]
        }
    }, (err) => {
        if (err) console.dir(err);
    });
    callback();
});

gulp.task('webserver', ['webpack'], function() {
    gulp.src('./')
        .pipe(webserver({
            livereload: {
                enable: true,
                filter: function (name) {
                    return name.match(new RegExp(dest));
                }
            },
            open: 'index.html'
        }));
    gulp.watch(['js/**/*.js', 'index.html'], ['lint', 'webpack']);
});


text:
require "translate/version"

module Translate
end
require File.join(File.dirname(__FILE__), "translate_controller")
require File.join(File.dirname(__FILE__), "translate_helper")
Dir[File.join(File.dirname(__FILE__), "translate", "*.rb")].each do |file|
  require file
end


text:
Rails.application.routes.draw do

  #constraints FeatureConstraint.new(:address_book) do
    resources :users, only: :none do
      resources :contact_lists
      resources :address_cards
    end
  #end
  resources :addresses, only: [:show, :edit, :update]
  resources :emails, only: [:show, :edit, :update]
  resources :phones, only: [:show, :edit, :update]
end


text:
using System;
using System.Text;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using System.Runtime.InteropServices;

using Internal.Cryptography;
using Internal.Cryptography.Pal.Native;

using FILETIME = Internal.Cryptography.Pal.Native.FILETIME;

using System.Security.Cryptography;
using SafeX509ChainHandle = Microsoft.Win32.SafeHandles.SafeX509ChainHandle;
using SafePasswordHandle = Microsoft.Win32.SafeHandles.SafePasswordHandle;
using System.Security.Cryptography.X509Certificates;

using static Interop.Crypt32;

namespace Internal.Cryptography.Pal
{
    internal sealed partial class CertificatePal : IDisposable, ICertificatePal
    {
        private SafeCertContextHandle _certContext;

        public static ICertificatePal FromHandle(IntPtr handle)
        {
            if (handle == IntPtr.Zero)
                throw new ArgumentException(SR.Arg_InvalidHandle, nameof(handle));

            SafeCertContextHandle safeCertContextHandle = Interop.crypt32.CertDuplicateCertificateContext(handle);
            if (safeCertContextHandle.IsInvalid)
                throw ErrorCode.HRESULT_INVALID_HANDLE.ToCryptographicException();

            CRYPTOAPI_BLOB dataBlob;
            int cbData = 0;
            bool deleteKeyContainer = Interop.crypt32.CertGetCertificateContextProperty(safeCertContextHandle, CertContextPropId.CERT_CLR_DELETE_KEY_PROP_ID, out dataBlob, ref cbData);
            return new CertificatePal(safeCertContextHandle, deleteKeyContainer);
        }

        /// <summary>
        /// Returns the SafeCertContextHandle. Use this instead of FromHandle() when
        /// creating another X509Certificate object based on this one to ensure the underlying
        /// cert context is not released at the wrong time.
        /// </summary>
        public static ICertificatePal FromOtherCert(X509Certificate copyFrom)
        {
            CertificatePal pal = new CertificatePal((CertificatePal)copyFrom.Pal);
            return pal;
        }

        public IntPtr Handle
        {
            get { return _certContext.DangerousGetHandle(); }
        }

        public string Issuer => GetIssuerOrSubject(issuer: true, reverse: true);

        public string Subject => GetIssuerOrSubject(issuer: false, reverse: true);

        public string LegacyIssuer => GetIssuerOrSubject(issuer: true, reverse: false);

        public string LegacySubject => GetIssuerOrSubject(issuer: false, reverse: false);

        public byte[] Thumbprint
        {
            get
            {
                int cbData = 0;
                if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_SHA1_HASH_PROP_ID, null, ref cbData))
                    throw Marshal.GetHRForLastWin32Error().ToCryptographicException();

                byte[] thumbprint = new byte[cbData];
                if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_SHA1_HASH_PROP_ID, thumbprint, ref cbData))
                    throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
                return thumbprint;
            }
        }

        public string KeyAlgorithm
        {
            get
            {
                unsafe
                {
                    CERT_CONTEXT* pCertContext = _certContext.CertContext;
                    string keyAlgorithm = Marshal.PtrToStringAnsi(pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId);
                    GC.KeepAlive(this);
                    return keyAlgorithm;
                }
            }
        }

        public byte[] KeyAlgorithmParameters
        {
            get
            {
                unsafe
                {
                    CERT_CONTEXT* pCertContext = _certContext.CertContext;
                    string keyAlgorithmOid = Marshal.PtrToStringAnsi(pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId);

                    int algId;
                    if (keyAlgorithmOid == Oids.Rsa)
                        algId = AlgId.CALG_RSA_KEYX;  // Fast-path for the most common case.
                    else
                        algId = Interop.Crypt32.FindOidInfo(CryptOidInfoKeyType.CRYPT_OID_INFO_OID_KEY, keyAlgorithmOid, OidGroup.PublicKeyAlgorithm, fallBackToAllGroups: true).AlgId;

                    unsafe
                    {
                        byte* NULL_ASN_TAG = (byte*)0x5;

                        byte[] keyAlgorithmParameters;

                        if (algId == AlgId.CALG_DSS_SIGN
                            && pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.Parameters.cbData == 0
                            && pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.Parameters.pbData == NULL_ASN_TAG)
                        {
                            //
                            // DSS certificates may not have the DSS parameters in the certificate. In this case, we try to build
                            // the certificate chain and propagate the parameters down from the certificate chain.
                            //
                            keyAlgorithmParameters = PropagateKeyAlgorithmParametersFromChain();
                        }
                        else
                        {
                            keyAlgorithmParameters = pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.Parameters.ToByteArray();
                        }

                        GC.KeepAlive(this);
                        return keyAlgorithmParameters;
                    }
                }
            }
        }

        private byte[] PropagateKeyAlgorithmParametersFromChain()
        {
            unsafe
            {
                SafeX509ChainHandle certChainContext = null;
                try
                {
                    int cbData = 0;
                    if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_PUBKEY_ALG_PARA_PROP_ID, null, ref cbData))
                    {
                        CERT_CHAIN_PARA chainPara = new CERT_CHAIN_PARA();
                        chainPara.cbSize = sizeof(CERT_CHAIN_PARA);
                        if (!Interop.crypt32.CertGetCertificateChain(ChainEngine.HCCE_CURRENT_USER, _certContext, (FILETIME*)null, SafeCertStoreHandle.InvalidHandle, ref chainPara, CertChainFlags.None, IntPtr.Zero, out certChainContext))
                            throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
                        if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_PUBKEY_ALG_PARA_PROP_ID, null, ref cbData))
                            throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
                    }

                    byte[] keyAlgorithmParameters = new byte[cbData];
                    if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_PUBKEY_ALG_PARA_PROP_ID, keyAlgorithmParameters, ref cbData))
                        throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;

                    return keyAlgorithmParameters;
                }
                finally
                {
                    if (certChainContext != null)
                        certChainContext.Dispose();
                }
            }
        }

        public byte[] PublicKeyValue
        {
            get
            {
                unsafe
                {
                    CERT_CONTEXT* pCertContext = _certContext.CertContext;
                    byte[] publicKey = pCertContext->pCertInfo->SubjectPublicKeyInfo.PublicKey.ToByteArray();
                    GC.KeepAlive(this);
                    return publicKey;
                }
            }
        }

        public byte[] SerialNumber
        {
            get
            {
                unsafe
                {
                    CERT_CONTEXT* pCertContext = _certContext.CertContext;
                    byte[] serialNumber = pCertContext->pCertInfo->SerialNumber.ToByteArray();
                    Array.Reverse(serialNumber);
                    GC.KeepAlive(this);
                    return serialNumber;
                }
            }
        }

        public string SignatureAlgorithm
        {
            get
            {
                unsafe
                {
                    CERT_CONTEXT* pCertContext = _certContext.CertContext;
                    string signatureAlgorithm = Marshal.PtrToStringAnsi(pCertContext->pCertInfo->SignatureAlgorithm.pszObjId);
                    GC.KeepAlive(this);
                    return signatureAlgorithm;
                }
            }
        }

        public DateTime NotAfter
        {
            get
            {
                unsafe
                {
                    CERT_CONTEXT* pCertContext = _certContext.CertContext;
                    DateTime notAfter = pCertContext->pCertInfo->NotAfter.ToDateTime();
                    GC.KeepAlive(this);
                    return notAfter;
                }
            }
        }

        public DateTime NotBefore
        {
            get
            {
                unsafe
                {
                    CERT_CONTEXT* pCertContext = _certContext.CertContext;
                    DateTime notBefore = pCertContext->pCertInfo->NotBefore.ToDateTime();
                    GC.KeepAlive(this);
                    return notBefore;
                }
            }
        }

        public byte[] RawData
        {
            get
            {
                unsafe
                {
                    CERT_CONTEXT* pCertContext = _certContext.CertContext;
                    byte[] rawData = new Span<byte>(pCertContext->pbCertEncoded, pCertContext->cbCertEncoded).ToArray();
                    GC.KeepAlive(this);
                    return rawData;
                }
            }
        }

        public int Version
        {
            get
            {
                unsafe
                {
                    CERT_CONTEXT* pCertContext = _certContext.CertContext;
                    int version = pCertContext->pCertInfo->dwVersion + 1;
                    GC.KeepAlive(this);
                    return version;
                }
            }
        }

        public bool Archived
        {
            get
            {
                int uninteresting = 0;
                bool archivePropertyExists = Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_ARCHIVED_PROP_ID, null, ref uninteresting);
                return archivePropertyExists;
            }

            set
            {
                unsafe
                {
                    CRYPTOAPI_BLOB blob = new CRYPTOAPI_BLOB(0, (byte*)null);
                    CRYPTOAPI_BLOB* pValue = value ? &blob : (CRYPTOAPI_BLOB*)null;
                    if (!Interop.crypt32.CertSetCertificateContextProperty(_certContext, CertContextPropId.CERT_ARCHIVED_PROP_ID, CertSetPropertyFlags.None, pValue))
                        throw Marshal.GetLastWin32Error().ToCryptographicException();
                }
            }
        }

        public string FriendlyName
        {
            get
            {
                unsafe
                {
                    int cbData = 0;
                    if (!Interop.crypt32.CertGetCertificateContextPropertyString(_certContext, CertContextPropId.CERT_FRIENDLY_NAME_PROP_ID, null, ref cbData))
                        return string.Empty;

                    int spanLength = (cbData + 1) / 2;
                    Span<char> buffer = spanLength <= 256 ? stackalloc char[spanLength] : new char[spanLength];
                    fixed (char* ptr = &MemoryMarshal.GetReference(buffer))
                    {
                        if (!Interop.crypt32.CertGetCertificateContextPropertyString(_certContext, CertContextPropId.CERT_FRIENDLY_NAME_PROP_ID, (byte*)ptr, ref cbData))
                            return string.Empty;
                    }

                    return new string(buffer.Slice(0, (cbData / 2) - 1));
                }
            }

            set
            {
                string friendlyName = (value == null) ? string.Empty : value;
                unsafe
                {
                    IntPtr pFriendlyName = Marshal.StringToHGlobalUni(friendlyName);
                    try
                    {
                        CRYPTOAPI_BLOB blob = new CRYPTOAPI_BLOB(checked(2 * (friendlyName.Length + 1)), (byte*)pFriendlyName);
                        if (!Interop.crypt32.CertSetCertificateContextProperty(_certContext, CertContextPropId.CERT_FRIENDLY_NAME_PROP_ID, CertSetPropertyFlags.None, &blob))
                            throw Marshal.GetLastWin32Error().ToCryptographicException();
                    }
                    finally
                    {
                        Marshal.FreeHGlobal(pFriendlyName);
                    }
                }
            }
        }

        public X500DistinguishedName SubjectName
        {
            get
            {
                unsafe
                {
                    byte[] encodedSubjectName = _certContext.CertContext->pCertInfo->Subject.ToByteArray();
                    X500DistinguishedName subjectName = new X500DistinguishedName(encodedSubjectName);
                    GC.KeepAlive(this);
                    return subjectName;
                }
            }
        }

        public X500DistinguishedName IssuerName
        {
            get
            {
                unsafe
                {
                    byte[] encodedIssuerName = _certContext.CertContext->pCertInfo->Issuer.ToByteArray();
                    X500DistinguishedName issuerName = new X500DistinguishedName(encodedIssuerName);
                    GC.KeepAlive(this);
                    return issuerName;
                }
            }
        }

        public IEnumerable<X509Extension> Extensions
        {
            get
            {
                unsafe
                {
                    CERT_INFO* pCertInfo = _certContext.CertContext->pCertInfo;
                    int numExtensions = pCertInfo->cExtension;
                    X509Extension[] extensions = new X509Extension[numExtensions];
                    for (int i = 0; i < numExtensions; i++)
                    {
                        CERT_EXTENSION* pCertExtension = pCertInfo->rgExtension + i;
                        string oidValue = Marshal.PtrToStringAnsi(pCertExtension->pszObjId);
                        Oid oid = new Oid(oidValue);
                        bool critical = pCertExtension->fCritical != 0;
                        byte[] rawData = pCertExtension->Value.ToByteArray();

                        extensions[i] = new X509Extension(oid, rawData, critical);
                    }
                    GC.KeepAlive(this);
                    return extensions;
                }
            }
        }

        public unsafe string GetNameInfo(X509NameType nameType, bool forIssuer) =>
            Interop.crypt32.CertGetNameString(
                _certContext,
                MapNameType(nameType),
                forIssuer ? CertNameFlags.CERT_NAME_ISSUER_FLAG : CertNameFlags.None,
                CertNameStringType.CERT_X500_NAME_STR | CertNameStringType.CERT_NAME_STR_REVERSE_FLAG);

        public void AppendPrivateKeyInfo(StringBuilder sb)
        {
            if (!HasPrivateKey)
            {
                return;
            }

            // UWP, Windows CNG persisted, and Windows Ephemeral keys will all acknowledge that
            // a private key exists, but detailed printing is limited to Windows CAPI persisted.
            // (This is the same thing we do in Unix)
            sb.AppendLine();
            sb.AppendLine();
            sb.AppendLine("[Private Key]");

            CspKeyContainerInfo cspKeyContainerInfo = null;
            try
            {
                CspParameters parameters = GetPrivateKeyCsp();

                if (parameters != null)
                {
                    cspKeyContainerInfo = new CspKeyContainerInfo(parameters);
                }
            }
            // We could not access the key container. Just return.
            catch (CryptographicException) { }

            // Ephemeral keys will not have container information.
            if (cspKeyContainerInfo == null)
                return;

            sb.Append(Environment.NewLine + "  Key Store: ");
            sb.Append(cspKeyContainerInfo.MachineKeyStore ? "Machine" : "User");
            sb.Append(Environment.NewLine + "  Provider Name: ");
            sb.Append(cspKeyContainerInfo.ProviderName);
            sb.Append(Environment.NewLine + "  Provider type: ");
            sb.Append(cspKeyContainerInfo.ProviderType);
            sb.Append(Environment.NewLine + "  Key Spec: ");
            sb.Append(cspKeyContainerInfo.KeyNumber);
            sb.Append(Environment.NewLine + "  Key Container Name: ");
            sb.Append(cspKeyContainerInfo.KeyContainerName);

            try
            {
                string uniqueKeyContainer = cspKeyContainerInfo.UniqueKeyContainerName;
                sb.Append(Environment.NewLine + "  Unique Key Container Name: ");
                sb.Append(uniqueKeyContainer);
            }
            catch (CryptographicException) { }
            catch (NotSupportedException) { }

            bool b = false;
            try
            {
                b = cspKeyContainerInfo.HardwareDevice;
                sb.Append(Environment.NewLine + "  Hardware Device: ");
                sb.Append(b);
            }
            catch (CryptographicException) { }

            try
            {
                b = cspKeyContainerInfo.Removable;
                sb.Append(Environment.NewLine + "  Removable: ");
                sb.Append(b);
            }
            catch (CryptographicException) { }

            try
            {
                b = cspKeyContainerInfo.Protected;
                sb.Append(Environment.NewLine + "  Protected: ");
                sb.Append(b);
            }
            catch (CryptographicException) { }
            catch (NotSupportedException) { }
        }

        public void Dispose()
        {
            SafeCertContextHandle certContext = _certContext;
            _certContext = null;
            if (certContext != null && !certContext.IsInvalid)
            {
                certContext.Dispose();
            }
        }

        internal SafeCertContextHandle CertContext
        {
            get
            {
                SafeCertContextHandle certContext = Interop.crypt32.CertDuplicateCertificateContext(_certContext.DangerousGetHandle());
                GC.KeepAlive(_certContext);
                return certContext;
            }
        }

        private static CertNameType MapNameType(X509NameType nameType)
        {
            switch (nameType)
            {
                case X509NameType.SimpleName:
                    return CertNameType.CERT_NAME_SIMPLE_DISPLAY_TYPE;

                case X509NameType.EmailName:
                    return CertNameType.CERT_NAME_EMAIL_TYPE;

                case X509NameType.UpnName:
                    return CertNameType.CERT_NAME_UPN_TYPE;

                case X509NameType.DnsName:
                case X509NameType.DnsFromAlternativeName:
                    return CertNameType.CERT_NAME_DNS_TYPE;

                case X509NameType.UrlName:
                    return CertNameType.CERT_NAME_URL_TYPE;

                default:
                    throw new ArgumentException(SR.Argument_InvalidNameType);
            }
        }

        private unsafe string GetIssuerOrSubject(bool issuer, bool reverse) =>
            Interop.crypt32.CertGetNameString(
                _certContext,
                CertNameType.CERT_NAME_RDN_TYPE,
                issuer ? CertNameFlags.CERT_NAME_ISSUER_FLAG : CertNameFlags.None,
                CertNameStringType.CERT_X500_NAME_STR | (reverse ? CertNameStringType.CERT_NAME_STR_REVERSE_FLAG : 0));

        private CertificatePal(CertificatePal copyFrom)
        {
            // Use _certContext (instead of CertContext) to keep the original context handle from being
            // finalized until all cert copies are no longer referenced.
            _certContext = new SafeCertContextHandle(copyFrom._certContext);
        }

        private CertificatePal(SafeCertContextHandle certContext, bool deleteKeyContainer)
        {
            if (deleteKeyContainer)
            {
                // We need to delete any associated key container upon disposition. Thus, replace the safehandle we got with a safehandle whose
                // Release() method performs the key container deletion.
                SafeCertContextHandle oldCertContext = certContext;
                certContext = Interop.crypt32.CertDuplicateCertificateContextWithKeyContainerDeletion(oldCertContext.DangerousGetHandle());
                GC.KeepAlive(oldCertContext);
            }
            _certContext = certContext;
        }

        public byte[] Export(X509ContentType contentType, SafePasswordHandle password)
        {
            using (IExportPal storePal = StorePal.FromCertificate(this))
            {
                return storePal.Export (contentType, password);
            }
        }
    }
}


text:
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
var config = require('laravel-elixir').config;
var utilities = require('./Utilities');
var Notification = require('./Notification');

module.exports = function(options) {

    var name = options.compiler.toLowerCase();

    var src = utilities.buildGulpSrc(
        options.src, config.assetsDir + name, options.search
    );

    var triggerSass = function(src) {
        var toMaps = plugins.if(config.sourcemaps, plugins.sourcemaps.init());

        if (options.plugin == 'gulp-ruby-sass') {
            return require('gulp-ruby-sass')(src, options.pluginOptions).pipe(toMaps);
        }

        return gulp.src(src).pipe(toMaps).pipe(
            plugins[options.plugin](options.pluginOptions)
        );
    };

    var onError = function(e) {
        new Notification().error(e, options.compiler + ' Compilation Failed!');

        this.emit('end');
    };

    gulp.task(name, function() {
        return triggerSass(src).on('error', onError)
            .pipe(plugins.autoprefixer())
            .pipe(plugins.if(config.production, plugins.minifyCss()))
            .pipe(plugins.if(config.sourcemaps, plugins.sourcemaps.write('.')))
            .pipe(gulp.dest(options.output || config.cssOutput))
            .pipe(new Notification().message(options.compiler + ' Compiled!'));
    });

    config.registerWatcher(
        name,
        config.assetsDir + name + '/' + options.search
    );

    return config.queueTask(name);

};


text:
// This file implements lowering of TF dialect to TFRT data kernels.
#include "tensorflow/compiler/mlir/tfrt/transforms/tf_to_tfrt_data.h"

#include "mlir/Dialect/StandardOps/IR/Ops.h"  // from @llvm-project
#include "mlir/IR/OperationSupport.h"  // from @llvm-project
#include "mlir/IR/Types.h"  // from @llvm-project
#include "mlir/Pass/Pass.h"  // from @llvm-project
#include "mlir/Pass/PassManager.h"  // from @llvm-project
#include "mlir/Transforms/DialectConversion.h"  // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_types.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/import_model.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/mlir_roundtrip_flags.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/protobuf/graph_debug_info.pb.h"
#include "tfrt/basic_kernels/opdefs/basic_kernels.h"  // from @tf_runtime
#include "tfrt/bef_converter/mlir_to_bef.h"  // from @tf_runtime
#include "tfrt/data/opdefs/data_ops.h"  // from @tf_runtime
#include "tfrt/data/opdefs/types.h"  // from @tf_runtime

#define DEBUG_TYPE "tf-to-tfrt-data"

namespace tensorflow {
namespace {

bool isIntScalar(Type t, size_t width) {
  if (auto ttype = t.dyn_cast<RankedTensorType>()) {
    if (ttype.hasStaticShape() && ttype.getNumElements() == 1 &&
        ttype.getRank() == 0 && ttype.getElementType().isSignlessInteger(width))
      return true;
  }
  return false;
}

// Converts `value_attr` from a TF Const node to the required type attr type `U`
template <typename T>
T ConstAttrToTypeAttr(ElementsAttr value_attr) {
  if (T type_attr = value_attr.dyn_cast<T>()) {
    return type_attr;
  } else if (auto v = value_attr.dyn_cast<SplatElementsAttr>()) {
    return v.getSplatValue<Attribute>().dyn_cast<T>();
  }
  return T(nullptr);
}

template <typename T>
LogicalResult ReplaceConst(TF::ConstOp &op, ConversionPatternRewriter &rewriter,
                           Type type) {
  IntegerAttr newAttr = ConstAttrToTypeAttr<IntegerAttr>(op.value());

  if (!newAttr) {
    return failure();
  }

  auto tfrtConst = rewriter.create<T>(op.getLoc(), type, newAttr);
  rewriter.replaceOp(op.getOperation(), tfrtConst.getResult());
  return success();
}

mlir::Type CreateDatasetType(mlir::Builder *builder) {
  return builder->getType<tfrt::data::DatasetType>();
}

// A helper class for converting data-specific types and attributes
class DataConverter : public mlir::TypeConverter {
 public:
  explicit DataConverter(mlir::MLIRContext *context) {
    addConversion([](Type type) { return type; });
    addConversion([context](TensorType type) {
      mlir::Builder builder(context);
      // tf.data datasets are represented by DT_VARIANT tensors in TF.
      // TODO(rachelim): Identify datasets more accurately.
      if (type.getElementType().dyn_cast<TF::VariantType>()) {
        return CreateDatasetType(&builder);
      }
      return type.dyn_cast<Type>();
    });
  }
};  // namespace

struct ConstOpConversion : public mlir::OpConversionPattern<TF::ConstOp> {
  explicit ConstOpConversion(MLIRContext *context)
      : OpConversionPattern<TF::ConstOp>(context) {}

  LogicalResult matchAndRewrite(
      TF::ConstOp op, OpAdaptor adaptor,
      ConversionPatternRewriter &rewriter) const override {
    if (isIntScalar(op.getType(), 64)) {
      return ReplaceConst<tfrt::compiler::ConstantI64Op>(op, rewriter,
                                                         rewriter.getI64Type());
    }
    if (isIntScalar(op.getType(), 1)) {
      return ReplaceConst<tfrt::compiler::ConstantI1Op>(op, rewriter,
                                                        rewriter.getI1Type());
    }
    // TODO(rachelim): Support converting other const types.
    return failure();
  }
};

struct ReturnOpConversion : public mlir::OpConversionPattern<mlir::ReturnOp> {
  explicit ReturnOpConversion(MLIRContext *context)
      : OpConversionPattern<mlir::ReturnOp>(context) {}

  LogicalResult matchAndRewrite(
      mlir::ReturnOp op, OpAdaptor adaptor,
      ConversionPatternRewriter &rewriter) const override {
    rewriter.replaceOpWithNewOp<tfrt::compiler::ReturnOp>(
        op, adaptor.getOperands());
    return success();
  }
};

class RangeDatasetOpConversion
    : public OpConversionPattern<TF::RangeDatasetOp> {
 public:
  explicit RangeDatasetOpConversion(MLIRContext *context)
      : OpConversionPattern<TF::RangeDatasetOp>(context),
        builder_(context),
        dataset_type_(CreateDatasetType(&builder_)) {}

  LogicalResult matchAndRewrite(
      TF::RangeDatasetOp op, OpAdaptor adaptor,
      ConversionPatternRewriter &rewriter) const override {
    if (op.output_types().size() != 1) {
      // Range dataset should only have one output type.
      return failure();
    }
    if (auto output_type = op.output_types().begin()->cast<TypeAttr>()) {
      rewriter.replaceOpWithNewOp<tfrt::data::RangeDatasetOp>(
          op, dataset_type_, adaptor.start(), adaptor.stop(), adaptor.step(),
          output_type);
      return success();
    }
    return failure();
  }

 private:
  mlir::Builder builder_;
  mlir::Type dataset_type_;
};

class BatchDatasetV2OpConversion
    : public OpConversionPattern<TF::BatchDatasetV2Op> {
 public:
  explicit BatchDatasetV2OpConversion(MLIRContext *context)
      : OpConversionPattern<TF::BatchDatasetV2Op>(context),
        builder_(context),
        dataset_type_(CreateDatasetType(&builder_)) {}

  LogicalResult matchAndRewrite(
      TF::BatchDatasetV2Op op, OpAdaptor adaptor,
      ConversionPatternRewriter &rewriter) const override {
    // Since TFRT's BatchDataset doesn't have a drop_remainder=True option,
    // we only convert this op if its drop_remainder input is statically known
    // to be false.
    auto drop_remainder_op = op.drop_remainder().getDefiningOp<TF::ConstOp>();
    if (!drop_remainder_op) return failure();
    BoolAttr drop_remainder_val =
        ConstAttrToTypeAttr<BoolAttr>(drop_remainder_op.value());
    if (!drop_remainder_val || drop_remainder_val.getValue()) {
      return failure();
    }

    // TODO(b/155892156): Support converting non-unary BatchDataset
    if (op.output_types().size() != 1) return failure();

    // TODO(b/155892156): Support converting BatchDataset with unknown rank
    auto output_shape = op.output_shapes()[0].cast<TF::ShapeAttr>();
    if (!output_shape.hasRank()) {
      return failure();
    }

    if (output_shape.getRank() >= 2) {  // Input is a tensor
      rewriter.replaceOpWithNewOp<tfrt::data::BatchDatasetTensorOp>(
          op, dataset_type_, adaptor.input_dataset(), adaptor.batch_size(),
          /*same_input_metadata=*/rewriter.getBoolAttr(false));
      return success();
    }

    auto output_type = op.output_types()[0].cast<TypeAttr>().getValue();

    if (output_type.isInteger(32)) {
      rewriter.replaceOpWithNewOp<tfrt::data::BatchDatasetI32Op>(
          op, dataset_type_, adaptor.input_dataset(), adaptor.batch_size(),
          /*same_input_metadata=*/rewriter.getBoolAttr(false));
      return success();
    }
    if (output_type.isInteger(64)) {
      rewriter.replaceOpWithNewOp<tfrt::data::BatchDatasetI64Op>(
          op, dataset_type_, adaptor.input_dataset(), adaptor.batch_size(),
          /*same_input_metadata=*/rewriter.getBoolAttr(false));
      return success();
    }
    return failure();
  }

 private:
  mlir::Builder builder_;
  mlir::Type dataset_type_;
};

// This rewrite converts a tf.data function that returns a tf.data dataset (in
// the TF dialect) to the equivalent function in the TFRT and Data dialects that
// returns a `!tfrt.dataset`.
//
// For now, this can only lower a RangeDataset op and its inputs. As we add more
// native TFRT datasets, we add the corresponding lowering pattern here.
class TFToTFRTDataRewritePass
    : public mlir::PassWrapper<TFToTFRTDataRewritePass,
                               mlir::OperationPass<mlir::ModuleOp>> {
  llvm::StringRef getArgument() const final { return "tf-to-tfrt-data"; }
  llvm::StringRef getDescription() const final {
    return "Convert Tensorflow dialect to TFRT's data dialect.";
  }

  void getDependentDialects(DialectRegistry &registry) const override {
    registry.insert<tfrt::compiler::TFRTDialect, tfrt::data::DataDialect>();
  }

  void runOnOperation() override {
    auto module = getOperation();
    auto *context = &getContext();
    mlir::ConversionTarget target(*context);
    DataConverter data_converter(context);
    target.addIllegalDialect<TF::TensorFlowDialect>();
    target.addLegalDialect<tfrt::data::DataDialect>();
    target.addLegalDialect<tfrt::compiler::TFRTDialect>();
    target.addDynamicallyLegalOp<mlir::FuncOp>([&data_converter](FuncOp op) {
      return data_converter.isSignatureLegal(op.getType());
    });
    mlir::RewritePatternSet patterns(&getContext());
    patterns.add<RangeDatasetOpConversion, BatchDatasetV2OpConversion,
                 ConstOpConversion, ReturnOpConversion>(context);
    mlir::populateFunctionOpInterfaceTypeConversionPattern<FuncOp>(
        patterns, data_converter);

    auto result =
        mlir::applyPartialConversion(module, target, std::move(patterns));
    if (failed(result)) {
      signalPassFailure();
    }
  }
};

// Creates a pipeline of passes that converts MLIR TF Executor dialect to
// Hex and Data dialect.
void CreateTFExecutorToTFRTDataPipeline(mlir::OpPassManager &pm) {
  // Prune unused operations.
  pm.addPass(mlir::tf_executor::CreateTFExecutorGraphPruningPass());

  // Run the TF standard pipeline
  mlir::TF::StandardPipelineOptions tf_options;
  tf_options.enable_inliner = true;
  mlir::TF::CreateTFStandardPipeline(pm, tf_options);

  // After all the standard passes, lower to TFRT Data.
  pm.addPass(CreateTFToTFRTDataConversionPass());
}

Status TFDataGraphDefToTFDataMLIR(
    const GraphDef &graph_def, mlir::MLIRContext *mlir_ctx,
    mlir::OwningOpRef<mlir::ModuleOp> *module_ref) {
  // Import to TF dialect
  string output_node;
  for (const auto &node : graph_def.node()) {
    if (node.op() == "_Retval") {
      output_node = node.input(0);
      VLOG(2) << "Output node: " << output_node;
      break;
    }
  }
  auto import_config = tensorflow::GraphImportConfig();
  import_config.outputs.push_back(std::move(output_node));
  import_config.prune_unused_nodes = true;
  TF_ASSIGN_OR_RETURN(*module_ref, ConvertGraphdefToMlir(
                                       graph_def, tensorflow::GraphDebugInfo(),
                                       std::move(import_config), mlir_ctx));

  return Status::OK();
}

Status CompileTFDataMLIRToBEF(mlir::ModuleOp module,
                              tfrt::BefBuffer *bef_buffer) {
  VLOG(1) << "TF Dialect: " << MlirModuleToString(module);

  mlir::PassManager pm(module.getContext());
  CreateTFExecutorToTFRTDataPipeline(pm);

  mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext());
  if (mlir::failed(pm.run(module)))
    return diag_handler.Combine(
        errors::Internal("failed to lower TF Dialect to TFRT Data dialect."));

  VLOG(1) << "TFRT Dialect: " << MlirModuleToString(module);

  *bef_buffer =
      tfrt::ConvertMLIRToBEF(module, /*disable_optional_sections=*/false);
  if (bef_buffer->empty())
    return diag_handler.Combine(
        errors::Internal("failed to convert MLIR to BEF."));

  return Status::OK();
}

}  // namespace

std::unique_ptr<mlir::Pass> CreateTFToTFRTDataConversionPass() {
  return std::make_unique<TFToTFRTDataRewritePass>();
}

Status TFDataGraphDefToHostBEF(const GraphDef &graph_def,
                               tfrt::BefBuffer *bef) {
  mlir::MLIRContext mlir_ctx;
  mlir::OwningOpRef<mlir::ModuleOp> module_ref;
  TF_RETURN_IF_ERROR(
      TFDataGraphDefToTFDataMLIR(graph_def, &mlir_ctx, &module_ref));
  TF_RETURN_IF_ERROR(CompileTFDataMLIRToBEF(module_ref.get(), bef));

  return Status::OK();
}

static mlir::PassRegistration<TFToTFRTDataRewritePass> pass;

}  // namespace tensorflow


text:
namespace offline_pages {

DownloadUIItem::DownloadUIItem()
    : total_bytes(0) {
}

DownloadUIItem::DownloadUIItem(const OfflinePageItem& page)
    : guid(page.client_id.id),
      url(page.url),
      target_path(page.file_path),
      start_time(page.creation_time),
      total_bytes(page.file_size) {}

DownloadUIItem::~DownloadUIItem() {
}

}  // namespace offline_pages


text:
package com.qualogy.qafe.mgwt.client.vo.functions.execute;

public class SetMaskHelper {

	public static native void setMaskEnable(final String componentId, final boolean mask) /*-{
   	var mask_postfix = "-disabled";
   	var escapedComponentId = componentId.replace(/\|/g, "\\|");
   	// for selecting items usind id we need to use #
   	escapedComponentId = '#' + escapedComponentId;

   	$wnd.jQuery(escapedComponentId + mask_postfix).remove();

   	if(!mask) {
   		var width = $wnd.jQuery(escapedComponentId).width();
		var height = $wnd.jQuery(escapedComponentId).height();
		var top = $wnd.jQuery(escapedComponentId).position().top;
		var left = $wnd.jQuery(escapedComponentId).position().left;
		$el = $wnd.jQuery('

').appendTo(escapedComponentId);
			$el.css('background-color', 'white');
			$el.css('position', 'absolute');
			$el.css('z-index', '2000');
			$el.css('width', width);
			$el.css('height', height);
			$el.css('top', top);
			$el.css('left', left);
			$el.css('opacity', .20);
			$el.attr('id', componentId + mask_postfix);
   	}

	}-*/;

}


text:
namespace blink {
namespace {

// Minimum preload buffer.
const int64_t kMinBufferPreload = 2 << 20;  // 2 Mb
// Maxmimum preload buffer.
const int64_t kMaxBufferPreload = 50 << 20;  // 50 Mb

// If preload_ == METADATA, preloading size will be
// shifted down this many bits. This shift turns
// one Mb into one 32k block.
// This seems to be the smallest amount of preload we can do without
// ending up repeatedly closing and re-opening the connection
// due to read calls after OnBufferingHaveEnough have been called.
const int64_t kMetadataShift = 6;

// Preload this much extra, then stop preloading until we fall below the
// preload_seconds_.value().
const int64_t kPreloadHighExtra = 1 << 20;  // 1 Mb

// Default pin region size.
// Note that we go over this if preload is calculated high enough.
const int64_t kDefaultPinSize = 25 << 20;  // 25 Mb

// If bitrate is not known, use this.
const int64_t kDefaultBitrate = 200 * 8 << 10;  // 200 Kbps.

// Maximum bitrate for buffer calculations.
const int64_t kMaxBitrate = 20 * 8 << 20;  // 20 Mbps.

// Maximum playback rate for buffer calculations.
const double kMaxPlaybackRate = 25.0;

// Extra buffer accumulation speed, in terms of download buffer.
const int kSlowPreloadPercentage = 10;

// Update buffer sizes every 32 progress updates.
const int kUpdateBufferSizeFrequency = 32;

// How long to we delay a seek after a read?
constexpr base::TimeDelta kSeekDelay = base::Milliseconds(20);

}  // namespace

class MultiBufferDataSource::ReadOperation {
 public:
  ReadOperation() = delete;
  ReadOperation(int64_t position,
                int size,
                uint8_t* data,
                media::DataSource::ReadCB callback);
  ReadOperation(const ReadOperation&) = delete;
  ReadOperation& operator=(const ReadOperation&) = delete;
  ~ReadOperation();

  // Runs |callback_| with the given |result|, deleting the operation
  // afterwards.
  static void Run(std::unique_ptr<ReadOperation> read_op, int result);

  int64_t position() { return position_; }
  int size() { return size_; }
  uint8_t* data() { return data_; }

 private:
  const int64_t position_;
  const int size_;
  uint8_t* data_;
  media::DataSource::ReadCB callback_;
};

MultiBufferDataSource::ReadOperation::ReadOperation(
    int64_t position,
    int size,
    uint8_t* data,
    media::DataSource::ReadCB callback)
    : position_(position),
      size_(size),
      data_(data),
      callback_(std::move(callback)) {
  DCHECK(!callback_.is_null());
}

MultiBufferDataSource::ReadOperation::~ReadOperation() {
  DCHECK(callback_.is_null());
}

// static
void MultiBufferDataSource::ReadOperation::Run(
    std::unique_ptr<ReadOperation> read_op,
    int result) {
  std::move(read_op->callback_).Run(result);
}

MultiBufferDataSource::MultiBufferDataSource(
    const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
    scoped_refptr<UrlData> url_data_arg,
    media::MediaLog* media_log,
    BufferedDataSourceHost* host,
    DownloadingCB downloading_cb)
    : total_bytes_(kPositionNotSpecified),
      streaming_(false),
      loading_(false),
      failed_(false),
      render_task_runner_(task_runner),
      url_data_(std::move(url_data_arg)),
      stop_signal_received_(false),
      media_has_played_(false),
      single_origin_(true),
      cancel_on_defer_(false),
      preload_(AUTO),
      bitrate_(0),
      playback_rate_(0.0),
      media_log_(media_log),
      host_(host),
      downloading_cb_(std::move(downloading_cb)) {
  weak_ptr_ = weak_factory_.GetWeakPtr();
  DCHECK(host_);
  DCHECK(downloading_cb_);
  DCHECK(render_task_runner_->BelongsToCurrentThread());
  DCHECK(url_data_.get());
  url_data_->Use();
  url_data_->OnRedirect(
      base::BindOnce(&MultiBufferDataSource::OnRedirected, weak_ptr_));
}

MultiBufferDataSource::~MultiBufferDataSource() {
  DCHECK(render_task_runner_->BelongsToCurrentThread());
}

bool MultiBufferDataSource::media_has_played() const {
  return media_has_played_;
}

bool MultiBufferDataSource::AssumeFullyBuffered() const {
  DCHECK(url_data_);
  return !url_data_->url().SchemeIsHTTPOrHTTPS();
}

void MultiBufferDataSource::SetReader(MultiBufferReader* reader) {
  DCHECK(render_task_runner_->BelongsToCurrentThread());
  base::AutoLock auto_lock(lock_);
  reader_.reset(reader);
}

void MultiBufferDataSource::CreateResourceLoader(int64_t first_byte_position,
                                                 int64_t last_byte_position) {
  DCHECK(render_task_runner_->BelongsToCurrentThread());

  SetReader(new MultiBufferReader(
      url_data_->multibuffer(), first_byte_position, last_byte_position,
      base::BindRepeating(&MultiBufferDataSource::ProgressCallback, weak_ptr_),
      render_task_runner_));
  reader_->SetIsClientAudioElement(is_client_audio_element_);
  UpdateBufferSizes();
}

void MultiBufferDataSource::CreateResourceLoader_Locked(
    int64_t first_byte_position,
    int64_t last_byte_position) {
  DCHECK(render_task_runner_->BelongsToCurrentThread());
  lock_.AssertAcquired();

  reader_ = std::make_unique<MultiBufferReader>(
      url_data_->multibuffer(), first_byte_position, last_byte_position,
      base::BindRepeating(&MultiBufferDataSource::ProgressCallback, weak_ptr_),
      render_task_runner_);
  UpdateBufferSizes();
}

void MultiBufferDataSource::Initialize(InitializeCB init_cb) {
  DCHECK(render_task_runner_->BelongsToCurrentThread());
  DCHECK(init_cb);
  DCHECK(!reader_.get());

  init_cb_ = std::move(init_cb);

  CreateResourceLoader(0, kPositionNotSpecified);

  // We're not allowed to call Wait() if data is already available.
  if (reader_->Available()) {
    render_task_runner_->PostTask(
        FROM_HERE,
        base::BindOnce(&MultiBufferDataSource::StartCallback, weak_ptr_));

    // When the entire file is already in the cache, we won't get any more
    // progress callbacks, which breaks some expectations. Post a task to
    // make sure that the client gets at least one call each for the progress
    // and loading callbacks.
    render_task_runner_->PostTask(
        FROM_HERE, base::BindOnce(&MultiBufferDataSource::UpdateProgress,
                                  weak_factory_.GetWeakPtr()));
  } else {
    reader_->Wait(
        1, base::BindOnce(&MultiBufferDataSource::StartCallback, weak_ptr_));
  }
}

void MultiBufferDataSource::OnRedirected(
    const scoped_refptr<UrlData>& new_destination) {
  if (!new_destination) {
    // A failure occurred.
    failed_ = true;
    if (init_cb_) {
      render_task_runner_->PostTask(
          FROM_HERE,
          base::BindOnce(&MultiBufferDataSource::StartCallback, weak_ptr_));
    } else {
      base::AutoLock auto_lock(lock_);
      StopInternal_Locked();
    }
    StopLoader();
    return;
  }
  if (url_data_->url().DeprecatedGetOriginAsURL() !=
      new_destination->url().DeprecatedGetOriginAsURL()) {
    single_origin_ = false;
  }
  SetReader(nullptr);
  url_data_ = std::move(new_destination);

  url_data_->OnRedirect(
      base::BindOnce(&MultiBufferDataSource::OnRedirected, weak_ptr_));

  if (init_cb_) {
    CreateResourceLoader(0, kPositionNotSpecified);
    if (reader_->Available()) {
      render_task_runner_->PostTask(
          FROM_HERE,
          base::BindOnce(&MultiBufferDataSource::StartCallback, weak_ptr_));
    } else {
      reader_->Wait(
          1, base::BindOnce(&MultiBufferDataSource::StartCallback, weak_ptr_));
    }
  } else if (read_op_) {
    CreateResourceLoader(read_op_->position(), kPositionNotSpecified);
    if (reader_->Available()) {
      render_task_runner_->PostTask(
          FROM_HERE,
          base::BindOnce(&MultiBufferDataSource::ReadTask, weak_ptr_));
    } else {
      reader_->Wait(
          1, base::BindOnce(&MultiBufferDataSource::ReadTask, weak_ptr_));
    }
  }

  if (redirect_cb_)
    redirect_cb_.Run();
}

void MultiBufferDataSource::SetPreload(media::DataSource::Preload preload) {
  DVLOG(1) << __func__ << "(" << preload << ")";
  DCHECK(render_task_runner_->BelongsToCurrentThread());
  preload_ = preload;
  UpdateBufferSizes();
}

bool MultiBufferDataSource::HasSingleOrigin() {
  DCHECK(render_task_runner_->BelongsToCurrentThread());
  // Before initialization completes there is no risk of leaking data. Callers
  // are required to order checks such that this isn't a race.
  return single_origin_;
}

bool MultiBufferDataSource::IsCorsCrossOrigin() const {
  return url_data_->is_cors_cross_origin();
}

void MultiBufferDataSource::OnRedirect(RedirectCB callback) {
  redirect_cb_ = std::move(callback);
}

bool MultiBufferDataSource::HasAccessControl() const {
  return url_data_->has_access_control();
}

bool MultiBufferDataSource::PassedTimingAllowOriginCheck() {
  return url_data_->passed_timing_allow_origin_check();
}

bool MultiBufferDataSource::WouldTaintOrigin() {
  // When the resource is redirected to another origin we think of it as
  // tainted. This is actually not specified, and is under discussion.
  // See https://github.com/whatwg/fetch/issues/737.
  if (!HasSingleOrigin() && cors_mode() == UrlData::CORS_UNSPECIFIED)
    return true;
  return IsCorsCrossOrigin();
}

UrlData::CorsMode MultiBufferDataSource::cors_mode() const {
  return url_data_->cors_mode();
}

void MultiBufferDataSource::OnMediaPlaybackRateChanged(double playback_rate) {
  DCHECK(render_task_runner_->BelongsToCurrentThread());
  if (playback_rate < 0 || playback_rate == playback_rate_)
    return;

  playback_rate_ = playback_rate;
  cancel_on_defer_ = false;
  UpdateBufferSizes();
}

void MultiBufferDataSource::OnMediaIsPlaying() {
  DCHECK(render_task_runner_->BelongsToCurrentThread());

  // Always clear this since it can be set by OnBufferingHaveEnough() calls at
  // any point in time.
  cancel_on_defer_ = false;

  if (media_has_played_)
    return;

  media_has_played_ = true;

  // Once we start playing, we need preloading.
  preload_ = AUTO;
  UpdateBufferSizes();
}

/////////////////////////////////////////////////////////////////////////////
// DataSource implementation.
void MultiBufferDataSource::Stop() {
  {
    base::AutoLock auto_lock(lock_);
    StopInternal_Locked();

    // Cleanup resources immediately if we're already on the right thread.
    if (render_task_runner_->BelongsToCurrentThread()) {
      reader_.reset();
      url_data_.reset();
      return;
    }
  }

  render_task_runner_->PostTask(
      FROM_HERE, base::BindOnce(&MultiBufferDataSource::StopLoader,
                                weak_factory_.GetWeakPtr()));
}

void MultiBufferDataSource::Abort() {
  base::AutoLock auto_lock(lock_);
  DCHECK(!init_cb_);
  if (read_op_)
    ReadOperation::Run(std::move(read_op_), kAborted);

  // Abort does not call StopLoader() since it is typically called prior to a
  // seek or suspend. Let the loader logic make the decision about whether a new
  // loader is necessary upon the seek or resume.
}

void MultiBufferDataSource::SetBitrate(int bitrate) {
  render_task_runner_->PostTask(
      FROM_HERE, base::BindOnce(&MultiBufferDataSource::SetBitrateTask,
                                weak_factory_.GetWeakPtr(), bitrate));
}

void MultiBufferDataSource::OnBufferingHaveEnough(bool always_cancel) {
  DCHECK(render_task_runner_->BelongsToCurrentThread());
  if (reader_ && (always_cancel || (preload_ == METADATA &&
                                    !media_has_played_ && !IsStreaming()))) {
    cancel_on_defer_ = true;
    if (!loading_) {
      base::AutoLock auto_lock(lock_);
      if (read_op_) {
        // We can't destroy the reader if a read operation is pending.
        // UpdateLoadingState_Locked will take care of it after the
        // operation is done.
        return;
      }
      // Already locked, no need to use SetReader().
      reader_.reset(nullptr);
    }
  }
}

int64_t MultiBufferDataSource::GetMemoryUsage() {
  // TODO(hubbe): Make more accurate when url_data_ is shared.
  return base::checked_cast<int64_t>(url_data_->CachedSize())
         << url_data_->multibuffer()->block_size_shift();
}

GURL MultiBufferDataSource::GetUrlAfterRedirects() const {
  return url_data_->url();
}

void MultiBufferDataSource::Read(int64_t position,
                                 int size,
                                 uint8_t* data,
                                 media::DataSource::ReadCB read_cb) {
  DVLOG(1) << "Read: " << position << " offset, " << size << " bytes";
  // Reading is not allowed until after initialization.
  DCHECK(!init_cb_);
  DCHECK(read_cb);

  {
    base::AutoLock auto_lock(lock_);
    DCHECK(!read_op_);

    if (stop_signal_received_) {
      std::move(read_cb).Run(kReadError);
      return;
    }

    // Optimization: Try reading from the cache here to get back to
    // muxing as soon as possible. This works because TryReadAt is
    // thread-safe.
    if (reader_) {
      int64_t bytes_read = reader_->TryReadAt(position, data, size);
      if (bytes_read > 0) {
        bytes_read_ += bytes_read;
        seek_positions_.push_back(position + bytes_read);
        if (seek_positions_.size() == 1) {
          render_task_runner_->PostDelayedTask(
              FROM_HERE,
              base::BindOnce(&MultiBufferDataSource::SeekTask,
                             weak_factory_.GetWeakPtr()),
              kSeekDelay);
        }

        std::move(read_cb).Run(static_cast<int>(bytes_read));
        return;
      }
    }
    read_op_ = std::make_unique<ReadOperation>(position, size, data,
                                               std::move(read_cb));
  }

  render_task_runner_->PostTask(FROM_HERE,
                                base::BindOnce(&MultiBufferDataSource::ReadTask,
                                               weak_factory_.GetWeakPtr()));
}

bool MultiBufferDataSource::GetSize(int64_t* size_out) {
  base::AutoLock auto_lock(lock_);
  if (total_bytes_ != kPositionNotSpecified) {
    *size_out = total_bytes_;
    return true;
  }
  *size_out = 0;
  return false;
}

bool MultiBufferDataSource::IsStreaming() {
  return streaming_;
}

/////////////////////////////////////////////////////////////////////////////
// This method is the place where actual read happens,
void MultiBufferDataSource::ReadTask() {
  DCHECK(render_task_runner_->BelongsToCurrentThread());

  base::AutoLock auto_lock(lock_);
  if (stop_signal_received_ || !read_op_)
    return;
  DCHECK(read_op_->size());

  if (!reader_)
    CreateResourceLoader_Locked(read_op_->position(), kPositionNotSpecified);

  int64_t available = reader_->AvailableAt(read_op_->position());
  if (available < 0) {
    // A failure has occured.
    ReadOperation::Run(std::move(read_op_), kReadError);
    return;
  }
  if (available) {
    int64_t bytes_read = std::min<int64_t>(available, read_op_->size());
    bytes_read =
        reader_->TryReadAt(read_op_->position(), read_op_->data(), bytes_read);

    bytes_read_ += bytes_read;
    seek_positions_.push_back(read_op_->position() + bytes_read);

    if (bytes_read == 0 && total_bytes_ == kPositionNotSpecified) {
      // We've reached the end of the file and we didn't know the total size
      // before. Update the total size so Read()s past the end of the file will
      // fail like they would if we had known the file size at the beginning.
      total_bytes_ = read_op_->position() + bytes_read;
      if (total_bytes_ != kPositionNotSpecified)
        host_->SetTotalBytes(total_bytes_);
    }

    ReadOperation::Run(std::move(read_op_), static_cast<int>(bytes_read));

    SeekTask_Locked();
  } else {
    reader_->Seek(read_op_->position());
    reader_->Wait(1, base::BindOnce(&MultiBufferDataSource::ReadTask,
                                    weak_factory_.GetWeakPtr()));
    UpdateLoadingState_Locked(false);
  }
}

void MultiBufferDataSource::SeekTask() {
  DCHECK(render_task_runner_->BelongsToCurrentThread());
  base::AutoLock auto_lock(lock_);
  SeekTask_Locked();
}

void MultiBufferDataSource::SeekTask_Locked() {
  DCHECK(render_task_runner_->BelongsToCurrentThread());
  lock_.AssertAcquired();

  if (stop_signal_received_)
    return;

  // A read operation is pending, which will call SeekTask_Locked when
  // it's done. We'll defer any seeking until the read op is done.
  if (read_op_)
    return;

  url_data_->AddBytesRead(bytes_read_);
  bytes_read_ = 0;

  if (reader_) {
    // If we're seeking to a new location, (not just slightly further
    // in the file) and we have more data buffered in that new location
    // than in our current location, then we don't actually seek anywhere.
    // Instead we keep preloading at the old location a while longer.

    int64_t pos = reader_->Tell();
    int64_t available = reader_->Available();

    // Iterate backwards, because if two positions have the same
    // amount of buffered data, we probably want to prefer the latest
    // one in the array.
    for (const auto& new_pos : base::Reversed(seek_positions_)) {
      int64_t available_at_new_pos = reader_->AvailableAt(new_pos);

      if (total_bytes_ != kPositionNotSpecified) {
        if (new_pos + available_at_new_pos >= total_bytes_) {
          // Buffer reaches end of file, no need to seek here.
          continue;
        }
      }
      if (available_at_new_pos < available) {
        pos = new_pos;
        available = available_at_new_pos;
      }
    }
    reader_->Seek(pos);
  }
  seek_positions_.clear();

  UpdateLoadingState_Locked(false);
}

void MultiBufferDataSource::StopInternal_Locked() {
  lock_.AssertAcquired();
  if (stop_signal_received_)
    return;

  stop_signal_received_ = true;

  // Initialize() isn't part of the DataSource interface so don't call it in
  // response to Stop().
  init_cb_.Reset();

  if (read_op_)
    ReadOperation::Run(std::move(read_op_), kReadError);
}

void MultiBufferDataSource::StopLoader() {
  DCHECK(render_task_runner_->BelongsToCurrentThread());
  SetReader(nullptr);
}

void MultiBufferDataSource::SetBitrateTask(int bitrate) {
  DCHECK(render_task_runner_->BelongsToCurrentThread());

  bitrate_ = bitrate;
  UpdateBufferSizes();
}

/////////////////////////////////////////////////////////////////////////////
// BufferedResourceLoader callback methods.
void MultiBufferDataSource::StartCallback() {
  DCHECK(render_task_runner_->BelongsToCurrentThread());

  if (!init_cb_) {
    SetReader(nullptr);
    return;
  }

  // All responses must be successful. Resources that are assumed to be fully
  // buffered must have a known content length.
  bool success =
      reader_ && reader_->Available() > 0 && url_data_ &&
      (!AssumeFullyBuffered() || url_data_->length() != kPositionNotSpecified);

  if (success) {
    {
      base::AutoLock auto_lock(lock_);
      total_bytes_ = url_data_->length();
    }
    streaming_ =
        !AssumeFullyBuffered() && (total_bytes_ == kPositionNotSpecified ||
                                   !url_data_->range_supported());

    media_log_->SetProperty<media::MediaLogProperty::kTotalBytes>(total_bytes_);
    media_log_->SetProperty<media::MediaLogProperty::kIsStreaming>(streaming_);
  } else {
    SetReader(nullptr);
  }

  // TODO(scherkus): we shouldn't have to lock to signal host(), see
  // http://crbug.com/113712 for details.
  base::AutoLock auto_lock(lock_);
  if (stop_signal_received_)
    return;

  if (success) {
    if (total_bytes_ != kPositionNotSpecified) {
      host_->SetTotalBytes(total_bytes_);
      if (AssumeFullyBuffered())
        host_->AddBufferedByteRange(0, total_bytes_);
    }

    // Progress callback might be called after the start callback,
    // make sure that we update single_origin_ now.
    media_log_->SetProperty<media::MediaLogProperty::kIsSingleOrigin>(
        single_origin_);
    media_log_->SetProperty<media::MediaLogProperty::kIsRangeHeaderSupported>(
        url_data_->range_supported());
  }

  render_task_runner_->PostTask(FROM_HERE,
                                base::BindOnce(std::move(init_cb_), success));

  UpdateBufferSizes();

  // Even if data is cached, say that we're loading at this point for
  // compatibility.
  UpdateLoadingState_Locked(true);
}

void MultiBufferDataSource::ProgressCallback(int64_t begin, int64_t end) {
  DVLOG(1) << __func__ << "(" << begin << ", " << end << ")";
  DCHECK(render_task_runner_->BelongsToCurrentThread());

  base::AutoLock auto_lock(lock_);
  if (stop_signal_received_)
    return;

  if (AssumeFullyBuffered())
    return;

  if (end > begin)
    host_->AddBufferedByteRange(begin, end);

  if (buffer_size_update_counter_ > 0)
    buffer_size_update_counter_--;
  else
    UpdateBufferSizes();

  UpdateLoadingState_Locked(false);
}

void MultiBufferDataSource::UpdateLoadingState_Locked(bool force_loading) {
  DVLOG(1) << __func__;
  lock_.AssertAcquired();
  if (AssumeFullyBuffered())
    return;
  // Update loading state.
  bool is_loading = !!reader_ && reader_->IsLoading();
  if (force_loading || is_loading != loading_) {
    bool loading = is_loading || force_loading;

    if (!loading && cancel_on_defer_) {
      if (read_op_) {
        // We can't destroy the reader if a read operation is pending.
        // UpdateLoadingState_Locked will be called again when the read
        // operation is done.
        return;
      }
      // Already locked, no need to use SetReader().
      reader_.reset(nullptr);
    }

    loading_ = loading;
    downloading_cb_.Run(loading_);
  }
}

void MultiBufferDataSource::UpdateProgress() {
  DCHECK(render_task_runner_->BelongsToCurrentThread());
  if (reader_) {
    uint64_t available = reader_->Available();
    uint64_t pos = reader_->Tell();
    ProgressCallback(pos, pos + available);
  }
}

void MultiBufferDataSource::UpdateBufferSizes() {
  DVLOG(1) << __func__;
  if (!reader_)
    return;

  buffer_size_update_counter_ = kUpdateBufferSizeFrequency;

  // Use a default bit rate if unknown and clamp to prevent overflow.
  int64_t bitrate = base::clamp<int64_t>(bitrate_, 0, kMaxBitrate);
  if (bitrate == 0)
    bitrate = kDefaultBitrate;

  // Only scale the buffer window for playback rates greater than 1.0 in
  // magnitude and clamp to prevent overflow.
  double playback_rate = playback_rate_;

  playback_rate = std::max(playback_rate, 1.0);
  playback_rate = std::min(playback_rate, kMaxPlaybackRate);

  int64_t bytes_per_second = (bitrate / 8.0) * playback_rate;

  // Preload 10 seconds of data, clamped to some min/max value.
  int64_t preload = base::clamp(preload_seconds_.value() * bytes_per_second,
                                kMinBufferPreload, kMaxBufferPreload);

  // Increase buffering slowly at a rate of 10% of data downloaded so
  // far, maxing out at the preload size.
  int64_t extra_buffer = std::min(
      preload, url_data_->BytesReadFromCache() * kSlowPreloadPercentage / 100);

  // Add extra buffer to preload.
  preload += extra_buffer;

  // We preload this much, then we stop unil we read |preload| before resuming.
  int64_t preload_high = preload + kPreloadHighExtra;

  // We pin a few seconds of data behind the current reading position.
  int64_t pin_backward =
      base::clamp(keep_after_playback_seconds_.value() * bytes_per_second,
                  kMinBufferPreload, kMaxBufferPreload);

  // We always pin at least kDefaultPinSize ahead of the read position.
  // Normally, the extra space between preload_high and kDefaultPinSize will
  // not actually have any data in it, but if it does, we don't want to throw it
  // away right before we need it.
  int64_t pin_forward = std::max(preload_high, kDefaultPinSize);

  // Note that the buffer size is advisory as only non-pinned data is allowed
  // to be thrown away. Most of the time we pin a region that is larger than
  // |buffer_size|, which only makes sense because most of the time, some of
  // the data in pinned region is not present in the cache.
  int64_t buffer_size = std::min(
      (preload_seconds_.value() + keep_after_playback_seconds_.value()) *
              bytes_per_second +
          extra_buffer * 3,
      preload_high + pin_backward + extra_buffer);

  if (url_data_->FullyCached() ||
      (url_data_->length() != kPositionNotSpecified &&
       url_data_->length() < kDefaultPinSize)) {
    // We just make pin_forwards/backwards big enough to encompass the
    // whole file regardless of where we are, with some extra margins.
    pin_forward = std::max(pin_forward, url_data_->length() * 2);
    pin_backward = std::max(pin_backward, url_data_->length() * 2);
    buffer_size = url_data_->length();
  }

  reader_->SetMaxBuffer(buffer_size);
  reader_->SetPinRange(pin_backward, pin_forward);

  if (preload_ == METADATA) {
    preload_high >>= kMetadataShift;
    preload >>= kMetadataShift;
  }
  reader_->SetPreload(preload_high, preload);
}

}  // namespace blink


text:
 .. Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

 ..   http://www.apache.org/licenses/LICENSE-2.0

 .. Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.

How-to Guides
=============

Setting up the sandbox in the :doc:`/start` section was easy;
building a production-grade environment requires a bit more work!

These how-to guides will step you through common tasks in using and
configuring an Airflow environment.

.. toctree::
    :maxdepth: 2

    add-dag-tags
    add-owner-links
    set-config
    set-up-database
    operator/index
    timetable
    custom-view-plugin
    customize-ui
    custom-operator
    create-custom-decorator
    export-more-env-vars
    connection
    variable
    run-behind-proxy
    run-with-systemd
    use-test-config
    define_extra_link
    email-config
    dynamic-dag-generation
    docker-compose/index


text:
package org.voodoo144.faker.core;

public interface IFakerDict {
    String[] getWords();
    String[] getFirstNames();
    String[] getLastNames();
    String[] getMiddleNames();
    String[] getCityPrefixes();
    String[] getRegionSuffixes();
    String[] getStreetPrefixes();
    String[] getCountries();
    String[] getRegionsOrStates();
    String[] getCities();
    String[] getStreets();
    String[] getNamePrefixes();
    String[] getNameSuffixes();

    String getPostCodeFormat();
}