text:
package lombok.javac.handlers;

import static lombok.core.handlers.HandlerUtil.*;
import static lombok.javac.Javac.*;
import static lombok.javac.handlers.JavacHandlerUtil.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

import lombok.ConfigurationKeys;
import lombok.EqualsAndHashCode;
import lombok.core.AST.Kind;
import lombok.core.AnnotationValues;
import lombok.core.handlers.HandlerUtil;
import lombok.javac.Javac;
import lombok.javac.JavacAnnotationHandler;
import lombok.javac.JavacNode;
import lombok.javac.JavacTreeMaker;
import lombok.javac.handlers.JavacHandlerUtil.FieldAccess;
import lombok.javac.handlers.JavacHandlerUtil.MemberExistsResult;

import org.mangosdk.spi.ProviderFor;

import com.sun.tools.javac.code.BoundKind;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCArrayTypeTree;
import com.sun.tools.javac.tree.JCTree.JCBinary;
import com.sun.tools.javac.tree.JCTree.JCBlock;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCExpressionStatement;
import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
import com.sun.tools.javac.tree.JCTree.JCModifiers;
import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.tree.JCTree.JCTypeParameter;
import com.sun.tools.javac.tree.JCTree.JCUnary;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Name;

/**
 * Handles the {@code lombok.EqualsAndHashCode} annotation for javac.
 */
@ProviderFor(JavacAnnotationHandler.class)
public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHashCode> {
	private static final String RESULT_NAME = "result";
	private static final String PRIME_NAME = "PRIME";

	public void checkForBogusFieldNames(JavacNode type, AnnotationValues<EqualsAndHashCode> annotation) {
		if (annotation.isExplicit("exclude")) {
			for (int i : createListOfNonExistentFields(List.from(annotation.getInstance().exclude()), type, true, true)) {
				annotation.setWarning("exclude", "This field does not exist, or would have been excluded anyway.", i);
			}
		}
		if (annotation.isExplicit("of")) {
			for (int i : createListOfNonExistentFields(List.from(annotation.getInstance().of()), type, false, false)) {
				annotation.setWarning("of", "This field does not exist.", i);
			}
		}
	}

	@Override public void handle(AnnotationValues<EqualsAndHashCode> annotation, JCAnnotation ast, JavacNode annotationNode) {
		handleFlagUsage(annotationNode, ConfigurationKeys.EQUALS_AND_HASH_CODE_FLAG_USAGE, "@EqualsAndHashCode");

		deleteAnnotationIfNeccessary(annotationNode, EqualsAndHashCode.class);
		EqualsAndHashCode ann = annotation.getInstance();
		List<String> excludes = List.from(ann.exclude());
		List<String> includes = List.from(ann.of());
		JavacNode typeNode = annotationNode.up();
		List<JCAnnotation> onParam = unboxAndRemoveAnnotationParameter(ast, "onParam", "@EqualsAndHashCode(onParam=", annotationNode);
		checkForBogusFieldNames(typeNode, annotation);

		Boolean callSuper = ann.callSuper();
		if (!annotation.isExplicit("callSuper")) callSuper = null;
		if (!annotation.isExplicit("exclude")) excludes = null;
		if (!annotation.isExplicit("of")) includes = null;

		if (excludes != null && includes != null) {
			excludes = null;
			annotation.setWarning("exclude", "exclude and of are mutually exclusive; the 'exclude' parameter will be ignored.");
		}

		Boolean doNotUseGettersConfiguration = annotationNode.getAst().readConfiguration(ConfigurationKeys.EQUALS_AND_HASH_CODE_DO_NOT_USE_GETTERS);
		boolean doNotUseGetters = annotation.isExplicit("doNotUseGetters") || doNotUseGettersConfiguration == null ? ann.doNotUseGetters() : doNotUseGettersConfiguration;
		FieldAccess fieldAccess = doNotUseGetters ? FieldAccess.PREFER_FIELD : FieldAccess.GETTER;

		generateMethods(typeNode, annotationNode, excludes, includes, callSuper, true, fieldAccess, onParam);
	}

	public void generateEqualsAndHashCodeForType(JavacNode typeNode, JavacNode source) {
		if (hasAnnotation(EqualsAndHashCode.class, typeNode)) {
			//The annotation will make it happen, so we can skip it.
			return;
		}

		generateMethods(typeNode, source, null, null, null, false, FieldAccess.GETTER, List.<JCAnnotation>nil());
	}

	public void generateMethods(JavacNode typeNode, JavacNode source, List<String> excludes, List<String> includes,
			Boolean callSuper, boolean whineIfExists, FieldAccess fieldAccess, List<JCAnnotation> onParam) {
		boolean notAClass = true;
		if (typeNode.get() instanceof JCClassDecl) {
			long flags = ((JCClassDecl)typeNode.get()).mods.flags;
			notAClass = (flags & (Flags.INTERFACE | Flags.ANNOTATION | Flags.ENUM)) != 0;
		}

		if (notAClass) {
			source.addError("@EqualsAndHashCode is only supported on a class.");
			return;
		}

		boolean isDirectDescendantOfObject = true;
		boolean implicitCallSuper = callSuper == null;
		if (callSuper == null) {
			try {
				callSuper = ((Boolean)EqualsAndHashCode.class.getMethod("callSuper").getDefaultValue()).booleanValue();
			} catch (Exception ignore) {
				throw new InternalError("Lombok bug - this cannot happen - can't find callSuper field in EqualsAndHashCode annotation.");
			}
		}

		JCTree extending = Javac.getExtendsClause((JCClassDecl)typeNode.get());
		if (extending != null) {
			String p = extending.toString();
			isDirectDescendantOfObject = p.equals("Object") || p.equals("java.lang.Object");
		}

		if (isDirectDescendantOfObject && callSuper) {
			source.addError("Generating equals/hashCode with a supercall to java.lang.Object is pointless.");
			return;
		}

		if (!isDirectDescendantOfObject && !callSuper && implicitCallSuper) {
			source.addWarning("Generating equals/hashCode implementation but without a call to superclass, even though this class does not extend java.lang.Object. If this is intentional, add '@EqualsAndHashCode(callSuper=false)' to your type.");
		}

		ListBuffer<JavacNode> nodesForEquality = new ListBuffer<JavacNode>();
		if (includes != null) {
			for (JavacNode child : typeNode.down()) {
				if (child.getKind() != Kind.FIELD) continue;
				JCVariableDecl fieldDecl = (JCVariableDecl) child.get();
				if (includes.contains(fieldDecl.name.toString())) nodesForEquality.append(child);
			}
		} else {
			for (JavacNode child : typeNode.down()) {
				if (child.getKind() != Kind.FIELD) continue;
				JCVariableDecl fieldDecl = (JCVariableDecl) child.get();
				//Skip static fields.
				if ((fieldDecl.mods.flags & Flags.STATIC) != 0) continue;
				//Skip transient fields.
				if ((fieldDecl.mods.flags & Flags.TRANSIENT) != 0) continue;
				//Skip excluded fields.
				if (excludes != null && excludes.contains(fieldDecl.name.toString())) continue;
				//Skip fields that start with $
				if (fieldDecl.name.toString().startsWith("$")) continue;
				nodesForEquality.append(child);
			}
		}

		boolean isFinal = (((JCClassDecl)typeNode.get()).mods.flags & Flags.FINAL) != 0;
		boolean needsCanEqual = !isFinal || !isDirectDescendantOfObject;
		MemberExistsResult equalsExists = methodExists("equals", typeNode, 1);
		MemberExistsResult hashCodeExists = methodExists("hashCode", typeNode, 0);
		MemberExistsResult canEqualExists = methodExists("canEqual", typeNode, 1);
		switch (Collections.max(Arrays.asList(equalsExists, hashCodeExists))) {
		case EXISTS_BY_LOMBOK:
			return;
		case EXISTS_BY_USER:
			if (whineIfExists) {
				String msg = "Not generating equals and hashCode: A method with one of those names already exists. (Either both or none of these methods will be generated).";
				source.addWarning(msg);
			} else if (equalsExists == MemberExistsResult.NOT_EXISTS || hashCodeExists == MemberExistsResult.NOT_EXISTS) {
				// This means equals OR hashCode exists and not both.
				// Even though we should suppress the message about not generating these, this is such a weird and surprising situation we should ALWAYS generate a warning.
				// The user code couldn't possibly (barring really weird subclassing shenanigans) be in a shippable state anyway; the implementations of these 2 methods are
				// all inter-related and should be written by the same entity.
				String msg = String.format("Not generating %s: One of equals or hashCode exists. " +
						"You should either write both of these or none of these (in the latter case, lombok generates them).",
						equalsExists == MemberExistsResult.NOT_EXISTS ? "equals" : "hashCode");
				source.addWarning(msg);
			}
			return;
		case NOT_EXISTS:
		default:
			//fallthrough
		}

		JCMethodDecl equalsMethod = createEquals(typeNode, nodesForEquality.toList(), callSuper, fieldAccess, needsCanEqual, source.get(), onParam);
		injectMethod(typeNode, equalsMethod);

		if (needsCanEqual && canEqualExists == MemberExistsResult.NOT_EXISTS) {
			JCMethodDecl canEqualMethod = createCanEqual(typeNode, source.get(), onParam);
			injectMethod(typeNode, canEqualMethod);
		}

		JCMethodDecl hashCodeMethod = createHashCode(typeNode, nodesForEquality.toList(), callSuper, fieldAccess, source.get());
		injectMethod(typeNode, hashCodeMethod);
	}

	public JCMethodDecl createHashCode(JavacNode typeNode, List<JavacNode> fields, boolean callSuper, FieldAccess fieldAccess, JCTree source) {
		JavacTreeMaker maker = typeNode.getTreeMaker();

		JCAnnotation overrideAnnotation = maker.Annotation(genJavaLangTypeRef(typeNode, "Override"), List.<JCExpression>nil());
		JCModifiers mods = maker.Modifiers(Flags.PUBLIC, List.of(overrideAnnotation));
		JCExpression returnType = maker.TypeIdent(CTC_INT);
		ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();

		Name primeName = typeNode.toName(PRIME_NAME);
		Name resultName = typeNode.toName(RESULT_NAME);
		long finalFlag = JavacHandlerUtil.addFinalIfNeeded(0L, typeNode.getContext());

		/* final int PRIME = X; */ {
			if (!fields.isEmpty() || callSuper) {
				statements.append(maker.VarDef(maker.Modifiers(finalFlag), primeName, maker.TypeIdent(CTC_INT), maker.Literal(HandlerUtil.primeForHashcode())));
			}
		}

		/* int result = 1; */ {
			statements.append(maker.VarDef(maker.Modifiers(0), resultName, maker.TypeIdent(CTC_INT), maker.Literal(1)));
		}

		if (callSuper) {
			JCMethodInvocation callToSuper = maker.Apply(List.<JCExpression>nil(),
					maker.Select(maker.Ident(typeNode.toName("super")), typeNode.toName("hashCode")),
					List.<JCExpression>nil());
			statements.append(createResultCalculation(typeNode, callToSuper));
		}

		Name dollar = typeNode.toName("$");
		for (JavacNode fieldNode : fields) {
			JCExpression fType = getFieldType(fieldNode, fieldAccess);
			JCExpression fieldAccessor = createFieldAccessor(maker, fieldNode, fieldAccess);
			if (fType instanceof JCPrimitiveTypeTree) {
				switch (((JCPrimitiveTypeTree)fType).getPrimitiveTypeKind()) {
				case BOOLEAN:
					/* this.fieldName ? X : Y */
					statements.append(createResultCalculation(typeNode, maker.Conditional(fieldAccessor,
							maker.Literal(HandlerUtil.primeForTrue()), maker.Literal(HandlerUtil.primeForFalse()))));
					break;
				case LONG: {
						Name dollarFieldName = dollar.append(((JCVariableDecl)fieldNode.get()).name);
						statements.append(maker.VarDef(maker.Modifiers(finalFlag), dollarFieldName, maker.TypeIdent(CTC_LONG), fieldAccessor));
						statements.append(createResultCalculation(typeNode, longToIntForHashCode(maker, maker.Ident(dollarFieldName), maker.Ident(dollarFieldName))));
					}
					break;
				case FLOAT:
					/* Float.floatToIntBits(this.fieldName) */
					statements.append(createResultCalculation(typeNode, maker.Apply(
							List.<JCExpression>nil(),
							genJavaLangTypeRef(typeNode, "Float", "floatToIntBits"),
							List.of(fieldAccessor))));
					break;
				case DOUBLE: {
						/* longToIntForHashCode(Double.doubleToLongBits(this.fieldName)) */
						Name dollarFieldName = dollar.append(((JCVariableDecl)fieldNode.get()).name);
						JCExpression init = maker.Apply(
								List.<JCExpression>nil(),
								genJavaLangTypeRef(typeNode, "Double", "doubleToLongBits"),
								List.of(fieldAccessor));
						statements.append(maker.VarDef(maker.Modifiers(finalFlag), dollarFieldName, maker.TypeIdent(CTC_LONG), init));
						statements.append(createResultCalculation(typeNode, longToIntForHashCode(maker, maker.Ident(dollarFieldName), maker.Ident(dollarFieldName))));
					}
					break;
				default:
				case BYTE:
				case SHORT:
				case INT:
				case CHAR:
					/* just the field */
					statements.append(createResultCalculation(typeNode, fieldAccessor));
					break;
				}
			} else if (fType instanceof JCArrayTypeTree) {
				/* java.util.Arrays.deepHashCode(this.fieldName) //use just hashCode() for primitive arrays. */
				boolean multiDim = ((JCArrayTypeTree)fType).elemtype instanceof JCArrayTypeTree;
				boolean primitiveArray = ((JCArrayTypeTree)fType).elemtype instanceof JCPrimitiveTypeTree;
				boolean useDeepHC = multiDim || !primitiveArray;

				JCExpression hcMethod = chainDots(typeNode, "java", "util", "Arrays", useDeepHC ? "deepHashCode" : "hashCode");
				statements.append(createResultCalculation(typeNode, maker.Apply(List.<JCExpression>nil(), hcMethod, List.of(fieldAccessor))));
			} else /* objects */ {
				/* final java.lang.Object $fieldName = this.fieldName; */
				/* $fieldName == null ? NULL_PRIME : $fieldName.hashCode() */

				Name dollarFieldName = dollar.append(((JCVariableDecl)fieldNode.get()).name);
				statements.append(maker.VarDef(maker.Modifiers(finalFlag), dollarFieldName, genJavaLangTypeRef(typeNode, "Object"), fieldAccessor));

				JCExpression hcCall = maker.Apply(List.<JCExpression>nil(), maker.Select(maker.Ident(dollarFieldName), typeNode.toName("hashCode")),
						List.<JCExpression>nil());
				JCExpression thisEqualsNull = maker.Binary(CTC_EQUAL, maker.Ident(dollarFieldName), maker.Literal(CTC_BOT, null));
				statements.append(createResultCalculation(typeNode, maker.Conditional(thisEqualsNull, maker.Literal(HandlerUtil.primeForNull()), hcCall)));
			}
		}

		/* return result; */ {
			statements.append(maker.Return(maker.Ident(resultName)));
		}

		JCBlock body = maker.Block(0, statements.toList());
		return recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName("hashCode"), returnType,
				List.<JCTypeParameter>nil(), List.<JCVariableDecl>nil(), List.<JCExpression>nil(), body, null), source, typeNode.getContext());
	}

	public JCExpressionStatement createResultCalculation(JavacNode typeNode, JCExpression expr) {
		/* result = result * PRIME + (expr); */
		JavacTreeMaker maker = typeNode.getTreeMaker();
		Name resultName = typeNode.toName(RESULT_NAME);
		JCExpression mult = maker.Binary(CTC_MUL, maker.Ident(resultName), maker.Ident(typeNode.toName(PRIME_NAME)));
		JCExpression add = maker.Binary(CTC_PLUS, mult, expr);
		return maker.Exec(maker.Assign(maker.Ident(resultName), add));
	}

	/** The 2 references must be clones of each other. */
	public JCExpression longToIntForHashCode(JavacTreeMaker maker, JCExpression ref1, JCExpression ref2) {
		/* (int)(ref >>> 32 ^ ref) */
		JCExpression shift = maker.Binary(CTC_UNSIGNED_SHIFT_RIGHT, ref1, maker.Literal(32));
		JCExpression xorBits = maker.Binary(CTC_BITXOR, shift, ref2);
		return maker.TypeCast(maker.TypeIdent(CTC_INT), xorBits);
	}

	public JCExpression createTypeReference(JavacNode type) {
		java.util.List<String> list = new ArrayList<String>();
		list.add(type.getName());
		JavacNode tNode = type.up();
		while (tNode != null && tNode.getKind() == Kind.TYPE) {
			list.add(tNode.getName());
			tNode = tNode.up();
		}
		Collections.reverse(list);

		JavacTreeMaker maker = type.getTreeMaker();
		JCExpression chain = maker.Ident(type.toName(list.get(0)));

		for (int i = 1; i < list.size(); i++) {
			chain = maker.Select(chain, type.toName(list.get(i)));
		}

		return chain;
	}

	public JCMethodDecl createEquals(JavacNode typeNode, List<JavacNode> fields, boolean callSuper, FieldAccess fieldAccess, boolean needsCanEqual, JCTree source, List<JCAnnotation> onParam) {
		JavacTreeMaker maker = typeNode.getTreeMaker();
		JCClassDecl type = (JCClassDecl) typeNode.get();

		Name oName = typeNode.toName("o");
		Name otherName = typeNode.toName("other");
		Name thisName = typeNode.toName("this");

		JCAnnotation overrideAnnotation = maker.Annotation(genJavaLangTypeRef(typeNode, "Override"), List.<JCExpression>nil());
		JCModifiers mods = maker.Modifiers(Flags.PUBLIC, List.of(overrideAnnotation));
		JCExpression objectType = genJavaLangTypeRef(typeNode, "Object");
		JCExpression returnType = maker.TypeIdent(CTC_BOOLEAN);

		long finalFlag = JavacHandlerUtil.addFinalIfNeeded(0L, typeNode.getContext());

		ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
		final List<JCVariableDecl> params = List.of(maker.VarDef(maker.Modifiers(finalFlag | Flags.PARAMETER, onParam), oName, objectType, null));

		/* if (o == this) return true; */ {
			statements.append(maker.If(maker.Binary(CTC_EQUAL, maker.Ident(oName),
					maker.Ident(thisName)), returnBool(maker, true), null));
		}

		/* if (!(o instanceof Outer.Inner.MyType) return false; */ {

			JCUnary notInstanceOf = maker.Unary(CTC_NOT, maker.TypeTest(maker.Ident(oName), createTypeReference(typeNode)));
			statements.append(maker.If(notInstanceOf, returnBool(maker, false), null));
		}

		/* MyType<?> other = (MyType<?>) o; */ {
			if (!fields.isEmpty() || needsCanEqual) {
				final JCExpression selfType1, selfType2;
				ListBuffer<JCExpression> wildcards1 = new ListBuffer<JCExpression>();
				ListBuffer<JCExpression> wildcards2 = new ListBuffer<JCExpression>();
				for (int i = 0 ; i < type.typarams.length() ; i++) {
					wildcards1.append(maker.Wildcard(maker.TypeBoundKind(BoundKind.UNBOUND), null));
					wildcards2.append(maker.Wildcard(maker.TypeBoundKind(BoundKind.UNBOUND), null));
				}

				if (type.typarams.isEmpty()) {
					selfType1 = maker.Ident(type.name);
					selfType2 = maker.Ident(type.name);
				} else {
					selfType1 = maker.TypeApply(maker.Ident(type.name), wildcards1.toList());
					selfType2 = maker.TypeApply(maker.Ident(type.name), wildcards2.toList());
				}

				statements.append(
						maker.VarDef(maker.Modifiers(finalFlag), otherName, selfType1, maker.TypeCast(selfType2, maker.Ident(oName))));
			}
		}

		/* if (!other.canEqual((java.lang.Object) this)) return false; */ {
			if (needsCanEqual) {
				List<JCExpression> exprNil = List.nil();
				JCExpression thisRef = maker.Ident(thisName);
				JCExpression castThisRef = maker.TypeCast(genJavaLangTypeRef(typeNode, "Object"), thisRef);
				JCExpression equalityCheck = maker.Apply(exprNil,
						maker.Select(maker.Ident(otherName), typeNode.toName("canEqual")),
						List.of(castThisRef));
				statements.append(maker.If(maker.Unary(CTC_NOT, equalityCheck), returnBool(maker, false), null));
			}
		}

		/* if (!super.equals(o)) return false; */
		if (callSuper) {
			JCMethodInvocation callToSuper = maker.Apply(List.<JCExpression>nil(),
					maker.Select(maker.Ident(typeNode.toName("super")), typeNode.toName("equals")),
					List.<JCExpression>of(maker.Ident(oName)));
			JCUnary superNotEqual = maker.Unary(CTC_NOT, callToSuper);
			statements.append(maker.If(superNotEqual, returnBool(maker, false), null));
		}

		Name thisDollar = typeNode.toName("this$");
		Name otherDollar = typeNode.toName("other$");
		for (JavacNode fieldNode : fields) {
			JCExpression fType = getFieldType(fieldNode, fieldAccess);
			JCExpression thisFieldAccessor = createFieldAccessor(maker, fieldNode, fieldAccess);
			JCExpression otherFieldAccessor = createFieldAccessor(maker, fieldNode, fieldAccess, maker.Ident(otherName));
			if (fType instanceof JCPrimitiveTypeTree) {
				switch (((JCPrimitiveTypeTree)fType).getPrimitiveTypeKind()) {
				case FLOAT:
					/* if (Float.compare(this.fieldName, other.fieldName) != 0) return false; */
					statements.append(generateCompareFloatOrDouble(thisFieldAccessor, otherFieldAccessor, maker, typeNode, false));
					break;
				case DOUBLE:
					/* if (Double.compare(this.fieldName, other.fieldName) != 0) return false; */
					statements.append(generateCompareFloatOrDouble(thisFieldAccessor, otherFieldAccessor, maker, typeNode, true));
					break;
				default:
					/* if (this.fieldName != other.fieldName) return false; */
					statements.append(
							maker.If(maker.Binary(CTC_NOT_EQUAL, thisFieldAccessor, otherFieldAccessor), returnBool(maker, false), null));
					break;
				}
			} else if (fType instanceof JCArrayTypeTree) {
				/* if (!java.util.Arrays.deepEquals(this.fieldName, other.fieldName)) return false; //use equals for primitive arrays. */
				boolean multiDim = ((JCArrayTypeTree)fType).elemtype instanceof JCArrayTypeTree;
				boolean primitiveArray = ((JCArrayTypeTree)fType).elemtype instanceof JCPrimitiveTypeTree;
				boolean useDeepEquals = multiDim || !primitiveArray;

				JCExpression eqMethod = chainDots(typeNode, "java", "util", "Arrays", useDeepEquals ? "deepEquals" : "equals");
				List<JCExpression> args = List.of(thisFieldAccessor, otherFieldAccessor);
				statements.append(maker.If(maker.Unary(CTC_NOT,
						maker.Apply(List.<JCExpression>nil(), eqMethod, args)), returnBool(maker, false), null));
			} else /* objects */ {
				/* final java.lang.Object this$fieldName = this.fieldName; */
				/* final java.lang.Object other$fieldName = other.fieldName; */
				/* if (this$fieldName == null ? other$fieldName != null : !this$fieldName.equals(other$fieldName)) return false;; */
				Name fieldName = ((JCVariableDecl)fieldNode.get()).name;
				Name thisDollarFieldName = thisDollar.append(fieldName);
				Name otherDollarFieldName = otherDollar.append(fieldName);

				statements.append(maker.VarDef(maker.Modifiers(finalFlag), thisDollarFieldName, genJavaLangTypeRef(typeNode, "Object"), thisFieldAccessor));
				statements.append(maker.VarDef(maker.Modifiers(finalFlag), otherDollarFieldName, genJavaLangTypeRef(typeNode, "Object"), otherFieldAccessor));

				JCExpression thisEqualsNull = maker.Binary(CTC_EQUAL, maker.Ident(thisDollarFieldName), maker.Literal(CTC_BOT, null));
				JCExpression otherNotEqualsNull = maker.Binary(CTC_NOT_EQUAL, maker.Ident(otherDollarFieldName), maker.Literal(CTC_BOT, null));
				JCExpression thisEqualsThat = maker.Apply(List.<JCExpression>nil(),
						maker.Select(maker.Ident(thisDollarFieldName), typeNode.toName("equals")),
						List.<JCExpression>of(maker.Ident(otherDollarFieldName)));
				JCExpression fieldsAreNotEqual = maker.Conditional(thisEqualsNull, otherNotEqualsNull, maker.Unary(CTC_NOT, thisEqualsThat));
				statements.append(maker.If(fieldsAreNotEqual, returnBool(maker, false), null));
			}
		}

		/* return true; */ {
			statements.append(returnBool(maker, true));
		}

		JCBlock body = maker.Block(0, statements.toList());
		return recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName("equals"), returnType, List.<JCTypeParameter>nil(), params, List.<JCExpression>nil(), body, null), source, typeNode.getContext());
	}

	public JCMethodDecl createCanEqual(JavacNode typeNode, JCTree source, List<JCAnnotation> onParam) {
		/* public boolean canEqual(final java.lang.Object other) {
		 *     return other instanceof Outer.Inner.MyType;
		 * }
		 */
		JavacTreeMaker maker = typeNode.getTreeMaker();

		JCModifiers mods = maker.Modifiers(Flags.PROTECTED, List.<JCAnnotation>nil());
		JCExpression returnType = maker.TypeIdent(CTC_BOOLEAN);
		Name canEqualName = typeNode.toName("canEqual");
		JCExpression objectType = genJavaLangTypeRef(typeNode, "Object");
		Name otherName = typeNode.toName("other");
		long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, typeNode.getContext());
		List<JCVariableDecl> params = List.of(maker.VarDef(maker.Modifiers(flags, onParam), otherName, objectType, null));

		JCBlock body = maker.Block(0, List.<JCStatement>of(
				maker.Return(maker.TypeTest(maker.Ident(otherName), createTypeReference(typeNode)))));

		return recursiveSetGeneratedBy(maker.MethodDef(mods, canEqualName, returnType, List.<JCTypeParameter>nil(), params, List.<JCExpression>nil(), body, null), source, typeNode.getContext());
	}

	public JCStatement generateCompareFloatOrDouble(JCExpression thisDotField, JCExpression otherDotField,
			JavacTreeMaker maker, JavacNode node, boolean isDouble) {
		/* if (Float.compare(fieldName, other.fieldName) != 0) return false; */
		JCExpression clazz = genJavaLangTypeRef(node, isDouble ? "Double" : "Float");
		List<JCExpression> args = List.of(thisDotField, otherDotField);
		JCBinary compareCallEquals0 = maker.Binary(CTC_NOT_EQUAL, maker.Apply(
				List.<JCExpression>nil(), maker.Select(clazz, node.toName("compare")), args), maker.Literal(0));
		return maker.If(compareCallEquals0, returnBool(maker, false), null);
	}

	public JCStatement returnBool(JavacTreeMaker maker, boolean bool) {
		return maker.Return(maker.Literal(CTC_BOOLEAN, bool ? 1 : 0));
	}
}


text:
layout: post
title: Where's the disney castle??
categories:
- Learning
---

Our fairy tale castle - the disney castle where we have seen the dancing beauty and the beast, cinderella and sleeping beauty...

![](/img/disneycastle.jpg)

And it is actually inspired from the [Neuschwanstein Castle](http://en.wikipedia.org/wiki/Neuschwanstein)... well fairy tales _do_ exist right here ;)

![](/img/neuschwansteincastle.jpg)

[picture credit here](http://www.texasgirlschoir.org/lgtr00/NeuschwansteinCastle1.jpg)

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<!--

-->

<configuration supports_final="false">
  <property>
    <name>content</name>
    <description>Describe all the Flume agent configurations</description>
    <value>
# Flume agent config
    </value>
  </property>
</configuration>


text:
package com.rockwellcollins.atc.agree.analysis.realtime;

import org.eclipse.emf.ecore.EObject;

import jkind.lustre.Expr;
import jkind.lustre.IdExpr;

public class AgreePeriodicPattern extends AgreeRealtimePattern {

	public AgreePeriodicPattern(String string, EObject reference, IdExpr event, Expr period, Expr jitter) {
		super(string, reference, event, period, jitter);
	}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Selenophoma vaccinii Vlassova

### Remarks
null


text:
//
//   Copyright 2018  SenX S.A.S.
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//

package io.warp10.script.mapper;

/**
 * Triangular kernel
 *
 * @see http://en.wikipedia.org/wiki/Kernel_%28statistics%29
 */
public class MapperKernelTriangular extends MapperKernel {

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

  @Override
  double[] getWeights(long step, int width) {
    double[] weights = new double[1 + (width >>> 1)];

    for (int i = 0; i < weights.length; i++) {
      weights[i] = 1.0D - i / (weights.length - 1.0D);
    }

    return weights;
  }
}


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

import java.io.Serializable;

/**
 *

 * A source file for the input sidecar captions used during the transcoding
 * process.
 *

 */
public class CaptionSource implements Serializable, Cloneable {

    /**
     *

     * The name of the sidecar caption file that you want Elastic Transcoder to
     * include in the output file.
     *

     */
    private String key;
    /**
     *

     * A string that specifies the language of the caption. Specify this as one
     * of:
     *

     *

     *

     *

     * 2-character ISO 639-1 code
     *

     *

     *

     *

     * 3-character ISO 639-2 code
     *

     *

     *

     *

     * For more information on ISO language codes and language names, see the
     * List of ISO 639-1 codes.
     *

     */
    private String language;
    /**
     *

     * For clip generation or captions that do not start at the same time as the
     * associated video file, the TimeOffset tells Elastic
     * Transcoder how much of the video to encode before including captions.
     *

     *

     * Specify the TimeOffset in the form [+-]SS.sss or [+-]HH:mm:SS.ss.
     *

     */
    private String timeOffset;
    /**
     *

     * The label of the caption shown in the player when choosing a language. We
     * recommend that you put the caption language name here, in the language of
     * the captions.
     *

     */
    private String label;
    /**
     *

     * The encryption settings, if any, that you want Elastic Transcoder to
     * apply to your caption sources.
     *

     */
    private Encryption encryption;

    /**
     *

     * The name of the sidecar caption file that you want Elastic Transcoder to
     * include in the output file.
     *

     *
     * @param key
     *        The name of the sidecar caption file that you want Elastic
     *        Transcoder to include in the output file.
     */

    public void setKey(String key) {
        this.key = key;
    }

    /**
     *

     * The name of the sidecar caption file that you want Elastic Transcoder to
     * include in the output file.
     *

     *
     * @return The name of the sidecar caption file that you want Elastic
     *         Transcoder to include in the output file.
     */

    public String getKey() {
        return this.key;
    }

    /**
     *

     * The name of the sidecar caption file that you want Elastic Transcoder to
     * include in the output file.
     *

     *
     * @param key
     *        The name of the sidecar caption file that you want Elastic
     *        Transcoder to include in the output file.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public CaptionSource withKey(String key) {
        setKey(key);
        return this;
    }

    /**
     *

     * A string that specifies the language of the caption. Specify this as one
     * of:
     *

     *

     *

     *

     * 2-character ISO 639-1 code
     *

     *

     *

     *

     * 3-character ISO 639-2 code
     *

     *

     *

     *

     * For more information on ISO language codes and language names, see the
     * List of ISO 639-1 codes.
     *

     *
     * @param language
     *        A string that specifies the language of the caption. Specify this
     *        as one of:

     *

     *

     *

     *        2-character ISO 639-1 code
     *

     *

     *

     *

     *        3-character ISO 639-2 code
     *

     *

     *

     *

     *        For more information on ISO language codes and language names, see
     *        the List of ISO 639-1 codes.
     */

    public void setLanguage(String language) {
        this.language = language;
    }

    /**
     *

     * A string that specifies the language of the caption. Specify this as one
     * of:
     *

     *

     *

     *

     * 2-character ISO 639-1 code
     *

     *

     *

     *

     * 3-character ISO 639-2 code
     *

     *

     *

     *

     * For more information on ISO language codes and language names, see the
     * List of ISO 639-1 codes.
     *

     *
     * @return A string that specifies the language of the caption. Specify this
     *         as one of:

     *

     *

     *

     *         2-character ISO 639-1 code
     *

     *

     *

     *

     *         3-character ISO 639-2 code
     *

     *

     *

     *

     *         For more information on ISO language codes and language names,
     *         see the List of ISO 639-1 codes.
     */

    public String getLanguage() {
        return this.language;
    }

    /**
     *

     * A string that specifies the language of the caption. Specify this as one
     * of:
     *

     *

     *

     *

     * 2-character ISO 639-1 code
     *

     *

     *

     *

     * 3-character ISO 639-2 code
     *

     *

     *

     *

     * For more information on ISO language codes and language names, see the
     * List of ISO 639-1 codes.
     *

     *
     * @param language
     *        A string that specifies the language of the caption. Specify this
     *        as one of:

     *

     *

     *

     *        2-character ISO 639-1 code
     *

     *

     *

     *

     *        3-character ISO 639-2 code
     *

     *

     *

     *

     *        For more information on ISO language codes and language names, see
     *        the List of ISO 639-1 codes.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public CaptionSource withLanguage(String language) {
        setLanguage(language);
        return this;
    }

    /**
     *

     * For clip generation or captions that do not start at the same time as the
     * associated video file, the TimeOffset tells Elastic
     * Transcoder how much of the video to encode before including captions.
     *

     *

     * Specify the TimeOffset in the form [+-]SS.sss or [+-]HH:mm:SS.ss.
     *

     *
     * @param timeOffset
     *        For clip generation or captions that do not start at the same time
     *        as the associated video file, the TimeOffset tells
     *        Elastic Transcoder how much of the video to encode before
     *        including captions.

     *

     *        Specify the TimeOffset in the form [+-]SS.sss or [+-]HH:mm:SS.ss.
     */

    public void setTimeOffset(String timeOffset) {
        this.timeOffset = timeOffset;
    }

    /**
     *

     * For clip generation or captions that do not start at the same time as the
     * associated video file, the TimeOffset tells Elastic
     * Transcoder how much of the video to encode before including captions.
     *

     *

     * Specify the TimeOffset in the form [+-]SS.sss or [+-]HH:mm:SS.ss.
     *

     *
     * @return For clip generation or captions that do not start at the same
     *         time as the associated video file, the TimeOffset
     *         tells Elastic Transcoder how much of the video to encode before
     *         including captions.

     *

     *         Specify the TimeOffset in the form [+-]SS.sss or [+-]HH:mm:SS.ss.
     */

    public String getTimeOffset() {
        return this.timeOffset;
    }

    /**
     *

     * For clip generation or captions that do not start at the same time as the
     * associated video file, the TimeOffset tells Elastic
     * Transcoder how much of the video to encode before including captions.
     *

     *

     * Specify the TimeOffset in the form [+-]SS.sss or [+-]HH:mm:SS.ss.
     *

     *
     * @param timeOffset
     *        For clip generation or captions that do not start at the same time
     *        as the associated video file, the TimeOffset tells
     *        Elastic Transcoder how much of the video to encode before
     *        including captions.

     *

     *        Specify the TimeOffset in the form [+-]SS.sss or [+-]HH:mm:SS.ss.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public CaptionSource withTimeOffset(String timeOffset) {
        setTimeOffset(timeOffset);
        return this;
    }

    /**
     *

     * The label of the caption shown in the player when choosing a language. We
     * recommend that you put the caption language name here, in the language of
     * the captions.
     *

     *
     * @param label
     *        The label of the caption shown in the player when choosing a
     *        language. We recommend that you put the caption language name
     *        here, in the language of the captions.
     */

    public void setLabel(String label) {
        this.label = label;
    }

    /**
     *

     * The label of the caption shown in the player when choosing a language. We
     * recommend that you put the caption language name here, in the language of
     * the captions.
     *

     *
     * @return The label of the caption shown in the player when choosing a
     *         language. We recommend that you put the caption language name
     *         here, in the language of the captions.
     */

    public String getLabel() {
        return this.label;
    }

    /**
     *

     * The label of the caption shown in the player when choosing a language. We
     * recommend that you put the caption language name here, in the language of
     * the captions.
     *

     *
     * @param label
     *        The label of the caption shown in the player when choosing a
     *        language. We recommend that you put the caption language name
     *        here, in the language of the captions.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public CaptionSource withLabel(String label) {
        setLabel(label);
        return this;
    }

    /**
     *

     * The encryption settings, if any, that you want Elastic Transcoder to
     * apply to your caption sources.
     *

     *
     * @param encryption
     *        The encryption settings, if any, that you want Elastic Transcoder
     *        to apply to your caption sources.
     */

    public void setEncryption(Encryption encryption) {
        this.encryption = encryption;
    }

    /**
     *

     * The encryption settings, if any, that you want Elastic Transcoder to
     * apply to your caption sources.
     *

     *
     * @return The encryption settings, if any, that you want Elastic Transcoder
     *         to apply to your caption sources.
     */

    public Encryption getEncryption() {
        return this.encryption;
    }

    /**
     *

     * The encryption settings, if any, that you want Elastic Transcoder to
     * apply to your caption sources.
     *

     *
     * @param encryption
     *        The encryption settings, if any, that you want Elastic Transcoder
     *        to apply to your caption sources.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public CaptionSource withEncryption(Encryption encryption) {
        setEncryption(encryption);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getKey() != null)
            sb.append("Key: " + getKey() + ",");
        if (getLanguage() != null)
            sb.append("Language: " + getLanguage() + ",");
        if (getTimeOffset() != null)
            sb.append("TimeOffset: " + getTimeOffset() + ",");
        if (getLabel() != null)
            sb.append("Label: " + getLabel() + ",");
        if (getEncryption() != null)
            sb.append("Encryption: " + getEncryption());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof CaptionSource == false)
            return false;
        CaptionSource other = (CaptionSource) obj;
        if (other.getKey() == null ^ this.getKey() == null)
            return false;
        if (other.getKey() != null
                && other.getKey().equals(this.getKey()) == false)
            return false;
        if (other.getLanguage() == null ^ this.getLanguage() == null)
            return false;
        if (other.getLanguage() != null
                && other.getLanguage().equals(this.getLanguage()) == false)
            return false;
        if (other.getTimeOffset() == null ^ this.getTimeOffset() == null)
            return false;
        if (other.getTimeOffset() != null
                && other.getTimeOffset().equals(this.getTimeOffset()) == false)
            return false;
        if (other.getLabel() == null ^ this.getLabel() == null)
            return false;
        if (other.getLabel() != null
                && other.getLabel().equals(this.getLabel()) == false)
            return false;
        if (other.getEncryption() == null ^ this.getEncryption() == null)
            return false;
        if (other.getEncryption() != null
                && other.getEncryption().equals(this.getEncryption()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode
                + ((getKey() == null) ? 0 : getKey().hashCode());
        hashCode = prime * hashCode
                + ((getLanguage() == null) ? 0 : getLanguage().hashCode());
        hashCode = prime * hashCode
                + ((getTimeOffset() == null) ? 0 : getTimeOffset().hashCode());
        hashCode = prime * hashCode
                + ((getLabel() == null) ? 0 : getLabel().hashCode());
        hashCode = prime * hashCode
                + ((getEncryption() == null) ? 0 : getEncryption().hashCode());
        return hashCode;
    }

    @Override
    public CaptionSource clone() {
        try {
            return (CaptionSource) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                            + "even though we're Cloneable!", e);
        }
    }
}


text:
namespace cpp_client
{

namespace spiders
{

bool Cutter_::cut(const Web& web)
{
    std::string order = R"({"event": "run", "data": {"functionName": "cut", "caller": {"id": ")";
    order += this->id + R"("}, "args": {)";

    order += std::string("\"web\":") + (web ? (std::string("{\"id\":\"") + web->id + "\"}") : std::string("null"));

    order += "}}}";
    Spiders::instance()->send(order);
    //Go until not a delta
    std::unique_ptr<Any> info;
    //until a not bool is seen (i.e., the delta has been processed)
    do
    {
        info = Spiders::instance()->handle_response();
    } while(info->type() == typeid(bool));
    auto doc = info->as<rapidjson::Document*>();
    auto loc = doc->FindMember("data");
    if(loc == doc->MemberEnd())
    {
       return {};
    }
    auto& val = loc->value;
    Any to_return;
    morph_any(to_return, val);
    return to_return.as<bool>();
}

Cutter_::Cutter_(std::initializer_list<std::pair<std::string, Any&&>> init) :
    Spiderling_{
        {"cuttingWeb", Any{std::decay<decltype(cutting_web)>::type{}}},
    },
    cutting_web(variables_["cuttingWeb"].as<std::decay<decltype(cutting_web)>::type>())
{
    for(auto&& obj : init)
    {
      variables_.emplace(std::make_pair(std::move(obj.first), std::move(obj.second)));
    }
}

Cutter_::~Cutter_() = default;

void Cutter_::resize(const std::string& name, std::size_t size)
{
    try
    {
        Spiderling_::resize(name, size);
        return;
    }
    catch(...){}
    throw Bad_manipulation(name + " in Cutter treated as a vector, but it is not a vector.");
}

void Cutter_::change_vec_values(const std::string& name, std::vector<std::pair<std::size_t, Any>>& values)
{
    try
    {
        Spiderling_::change_vec_values(name, values);
        return;
    }
    catch(...){}
    throw Bad_manipulation(name + " in Cutter treated as a vector, but it is not a vector.");
}

void Cutter_::remove_key(const std::string& name, Any& key)
{
    try
    {
        Spiderling_::remove_key(name, key);
        return;
    }
    catch(...){}
    throw Bad_manipulation(name + " in Cutter treated as a map, but it is not a map.");
}

std::unique_ptr<Any> Cutter_::add_key_value(const std::string& name, Any& key, Any& value)
{
    try
    {
        return Spiderling_::add_key_value(name, key, value);
    }
    catch(...){}
    throw Bad_manipulation(name + " in Cutter treated as a map, but it is not a map.");
}

bool Cutter_::is_map(const std::string& name)
{
    try
    {
        return Spiderling_::is_map(name);
    }
    catch(...){}
    return false;
}

void Cutter_::rebind_by_name(Any* to_change, const std::string& member, std::shared_ptr<Base_object> ref)
{
   if(member == "cuttingWeb")
   {
      to_change->as<Web>() = std::static_pointer_cast<Web_>(ref);
      return;
   }
   try
   {
      Spiderling_::rebind_by_name(to_change, member, ref);
      return;
   }
   catch(...){}
   throw Bad_manipulation(member + " in Cutter treated as a reference, but it is not a reference.");
}

} // spiders

} // cpp_client


text:
'use strict';

var gulp = require('gulp');
var karma = require('gulp-karma');
var config = require('../config');

gulp.task('unit', ['views', 'lib'], function() {

    // Nonsensical source to fall back to files listed in karma.conf.js,
    // see https://github.com/lazd/gulp-karma/issues/9
    return gulp.src('./thisdoesntexist')
        .pipe(karma({
            configFile: config.test.karma,
            //action: 'watch', // note: remove action:'watch' if you want to execute more tasks afterwards.
            showStack: true
        }))
        .on('error', function(err) {
            // Make sure failed tests cause gulp to exit non-zero
            throw err;
        });

});


text:
Keynotes.
=========

### Keynote: president.

* Interesting perspective on what the

### Keynote: social data analytics

* Apply magic sauce. https://applymagicsauce.com
* www.sandramatz.com
* www.psychometrics.cam.ac.uk
* Digital Psychometrics - facebook (7 million people)


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911
// .1802
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.07.16 at 03:24:22 PM EEST
//

package org.ecloudmanager.tmrk.cloudapi.model;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;

/**
 *
Java class for VirtualMachineMemoryUsageDetailType complex type.
 *

 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <complexType name="VirtualMachineMemoryUsageDetailType">
 *   <complexContent>
 *     <extension base="{}ReferenceType">
 *       <sequence>
 *         <element name="Usage" type="{}ResourceUnitType" minOccurs="0"/>
 *         <element name="Utilization" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
 *         <element name="Deleted" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "VirtualMachineMemoryUsageDetailType", propOrder = {
    "usage",
    "utilization",
    "deleted"
})
public class VirtualMachineMemoryUsageDetailType
    extends ReferenceType {

    /**
     *
     */
    private static final long serialVersionUID = 7557124203365315877L;
    @XmlElementRef(name = "Usage", type = JAXBElement.class, required = false)
    protected JAXBElement<ResourceUnitType> usage;
    @XmlElement(name = "Utilization")
    protected Integer utilization;
    @XmlElementRef(name = "Deleted", type = JAXBElement.class, required = false)
    protected JAXBElement<Boolean> deleted;

    /**
     * Gets the value of the usage property.
     *
     * @return possible object is
     * {@link JAXBElement }{@code <}{@link ResourceUnitType }{@code >}
     */
    public JAXBElement<ResourceUnitType> getUsage() {
        return usage;
    }

    /**
     * Sets the value of the usage property.
     *
     * @param value allowed object is
     *              {@link JAXBElement }{@code <}{@link ResourceUnitType }{@code >}
     */
    public void setUsage(JAXBElement<ResourceUnitType> value) {
        this.usage = value;
    }

    /**
     * Gets the value of the utilization property.
     *
     * @return possible object is
     * {@link Integer }
     */
    public Integer getUtilization() {
        return utilization;
    }

    /**
     * Sets the value of the utilization property.
     *
     * @param value allowed object is
     *              {@link Integer }
     */
    public void setUtilization(Integer value) {
        this.utilization = value;
    }

    /**
     * Gets the value of the deleted property.
     *
     * @return possible object is
     * {@link JAXBElement }{@code <}{@link Boolean }{@code >}
     */
    public JAXBElement<Boolean> getDeleted() {
        return deleted;
    }

    /**
     * Sets the value of the deleted property.
     *
     * @param value allowed object is
     *              {@link JAXBElement }{@code <}{@link Boolean }{@code >}
     */
    public void setDeleted(JAXBElement<Boolean> value) {
        this.deleted = value;
    }

}


text:
vde.primitives.Mark = (function() {
    var mark = function(name) {
        vde.Primitive.call(this, name);

        this.spec.from = null;

        this.spec.properties = {
            enter:  {},
            update: {},
            hover:  {}
        };

        this.fullClass = 'vde.primitives.Mark';

        return this;
    };

    mark.prototype = new vde.Primitive();
    var prototype = mark.prototype;

    prototype.getClass = function(full) { return full ? this.fullClass : this.spec.type.charAt(0).toUpperCase() + this.spec.type.slice(1);}

    prototype.init = function() {
        if(!this.group) {
            this.group = new vde.primitives.marks.Group("group_" + Date.now());
            this.group.init();
        }

        this.group.marks[this.getName()] = this;

        return this;
    };

    prototype.enter = function(k, v) {
        return this.prop('enter', k, v);
    };

    prototype.update = function(k, v) {
        return this.prop('update', k, v);
    };

    prototype.hover = function(k, v) {
        return this.prop('hover', k, v);
    };

    prototype.prop = function(type, k, v) {
        if(!v) return this.spec.properties[type][k];

        this.spec.properties[type][k] = v;
        return this;
    };

    prototype.getDef = function() {
        var path = [], p = this,
            defs = vde.view.model().defs(),
            d = defs.marks;

        while(p) {
            path.push(p.getName());
            p = p.group;
        }

        var findMarkDef = function(def, name) {
            if(def.name == name)
                return def;

            for(var i = 0; i < def.marks.length; i++) {
                if(def.marks[i].name == name)
                    return def.marks[i];
            }

            return null;
        }

        while(p = path.pop()) {
            if(d.name == p)
                continue;

            d = findMarkDef(d, p);
            if(!d)
                return null;
        }

        return d;
    };

    prototype.updateProps = function() {
        var def  = this.getDef(),
            spec = this.getSpec();

        def.properties.enter  = vg.parse.properties(spec.properties.enter);
        def.properties.update = vg.parse.properties(spec.properties.update);
    };

    return mark;
})();


text:
module Market
  class ApplicationJob < ActiveJob::Base
  end
end


text:
extern "C"
{
  JNIEXPORT void JNICALL
  Java_com_mapswithme_maps_location_LocationHelper_nativeOnLocationError(JNIEnv * env, jclass clazz, int errorCode)
  {
    g_framework->OnLocationError(errorCode);
  }

  JNIEXPORT void JNICALL
  Java_com_mapswithme_maps_location_LocationHelper_nativeLocationUpdated(JNIEnv * env, jclass clazz, jlong time,
                                                                         jdouble lat, jdouble lon, jfloat accuracy,
                                                                         jdouble altitude, jfloat speed, jfloat bearing)
  {
    location::GpsInfo info;
    info.m_source = location::EAndroidNative;

    info.m_timestamp = static_cast<double>(time) / 1000.0;
    info.m_latitude = lat;
    info.m_longitude = lon;

    if (accuracy > 0.0)
      info.m_horizontalAccuracy = accuracy;

    if (altitude != 0.0)
    {
      info.m_altitude = altitude;
      info.m_verticalAccuracy = accuracy;
    }

    if (bearing > 0.0)
      info.m_bearing = bearing;

    if (speed > 0.0)
      info.m_speed = speed;

    LOG_MEMORY_INFO();
    if (g_framework)
      g_framework->OnLocationUpdated(info);
    GpsTracker::Instance().OnLocationUpdated(info);
  }

  JNIEXPORT jfloatArray JNICALL
  Java_com_mapswithme_maps_location_LocationHelper_nativeUpdateCompassSensor(JNIEnv * env, jclass clazz, jint ind, jfloatArray arr)
  {
    int const kCoordsCount = 3;

    // Extract coords
    jfloat coords[kCoordsCount];
    env->GetFloatArrayRegion(arr, 0, kCoordsCount, coords);
    g_framework->UpdateCompassSensor(ind, coords);

    // Put coords back to java result array
    jfloatArray ret = (jfloatArray)env->NewFloatArray(kCoordsCount);
    env->SetFloatArrayRegion(ret, 0, kCoordsCount, coords);
    return ret;
  }
}


text:
package styx

import (
	"crypto/tls"
	"net"
	"time"

	"aqwari.net/net/styx/internal/util"
	"aqwari.net/retry"
)

// Types implementing the Logger interface can receive
// diagnostic information during a Server's operation.
// The Logger interface is implemented by *log.Logger.
type Logger interface {
	Printf(string, ...interface{})
}

type AuthOpenFunc func() (interface{}, error)

// A Server defines parameters for running a 9P server. The
// zero value of a Server is usable as a 9P server, and will
// use the defaults set by the styx package.
type Server struct {
	// Address to listen on, ":9pfs" if empty.
	Addr string

	// maximum wait before timing out write of the response.
	WriteTimeout time.Duration

	// maximum wait before closing an idle connection.
	IdleTimeout time.Duration

	// maximum size of a 9P message, DefaultMsize if unset.
	MaxSize int64

	// optional TLS config, used by ListenAndServeTLS
	TLSConfig *tls.Config

	// Handler to invoke for each session
	Handler Handler

	// Auth is used to authenticate user sessions. If nil,
	// authentication is disabled.
	Auth AuthFunc

	// OpenAuth is used to open file to authentication agent
	OpenAuth AuthOpenFunc

	// If not nil, ErrorLog will be used to log unexpected
	// errors accepting or handling connections. TraceLog,
	// if not nil, will receive detailed protocol tracing
	// information.
	ErrorLog, TraceLog Logger
}

// Types implementing the Handler interface can receive and respond to 9P
// requests from clients.
//
// When a client connects to the server and starts a session, a new goroutine
// is created running the handler's Serve9P method. Each 9P message can
// be retrieved using the Session's Next and Request methods. Serve9P is
// expected to last for the duration of the 9P session; if the client ends
// the session, the Session's Next method will return false. If the Serve9P
// method exits prematurely, all open files and other resources associated
// with that session are released, and any further requests for that session
// will result in an error.
//
// The Serve9P method is not required to answer every type of 9P message.
// If an existing request is unanswered when Serve9P fetches the next
// request, the styx package will reply to the client with a default
// response. The documentation for each request type notes its default
// response.
//
// In practice, a Handler is usually composed of a for loop and a type switch,
// like so:
//
// 	func (srv *Srv) Serve9P(s *styx.Session) {
// 		for s.Next() {
// 			switch msg := s.Request().(type) {
// 			case styx.Twalk:
// 				if (srv.exists(msg.Path()) {
// 					msg.Rwalk(srv.filemode(msg.Path())
// 				} else {
// 					msg.Rerror("%s does not exist", msg.Path())
// 				}
// 			case styx.Topen:
//				msg.Ropen(srv.getfile(msg.Path()))
// 			case styx.Tcreate:
// 				msg.Rcreate(srv.newfile(msg.Path())
// 			}
// 		}
// 	}
//
// Possible message types are listed in the documentation for the Request type.
//
type Handler interface {
	Serve9P(*Session)
}

// The HandlerFunc provides a convenient adapter type that allows for normal
// functions to handle 9P sessions.
type HandlerFunc func(s *Session)

// Serve9P calls fn(s).
func (fn HandlerFunc) Serve9P(s *Session) {
	fn(s)
}

// Serve accepts connections on the listener l, creating a new service
// goroutine for each. The service goroutines read requests and relays
// them to the appropriate Handler goroutines.
func (srv *Server) Serve(l net.Listener) error {
	backoff := retry.Exponential(time.Millisecond * 10).Max(time.Second)
	try := 0

	srv.logf("listening on %s", l.Addr())
	for {
		rwc, err := l.Accept()
		if err != nil {
			if util.IsTempErr(err) {
				try++
				srv.logf("9p: Accept error: %v; retrying in %v", err, backoff(try))
				time.Sleep(backoff(try))
				continue
			}
			return err
		} else {
			try = 0
		}

		srv.logf("accepted connection from %s", rwc.RemoteAddr())
		conn := newConn(srv, rwc)
		go conn.serve()
	}
}

// ListenAndServe listens on the specified TCP address, and then
// calls Serve with handler to handle requests of incoming
// connections.
func ListenAndServe(addr string, handler Handler) error {
	srv := Server{Handler: handler, Addr: addr}
	return srv.ListenAndServe()
}

// ListenAndServeTLS listens on the specified TCP address for
// incoming TLS connections. certFile must be a valid x509
// certificate in PEM format, concatenated with any intermediate
// and CA certificates.
func ListenAndServeTLS(addr string, certFile, keyFile string, handler Handler) error {
	srv := Server{Handler: handler, Addr: addr}
	return srv.ListenAndServeTLS(certFile, keyFile)
}

// ListenAndServe listens on the TCP network address srv.Addr and
// calls Serve to handle requests on incoming connections.
// If srv.Addr is blank, :564 is used.
func (srv *Server) ListenAndServe() error {
	addr := srv.Addr
	if addr == "" {
		addr = ":9pfs"
	}
	ln, err := net.Listen("tcp", addr)
	if err != nil {
		return err
	}
	return srv.Serve(ln)
}

// ListenAndServeTLS listens on the TCP network address srv.Addr for
// incoming TLS connections.
func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {
	addr := srv.Addr
	if addr == "" {
		addr = ":564"
	}
	cfg := srv.TLSConfig
	if cfg == nil {
		cfg = new(tls.Config)
	}
	if len(cfg.Certificates) == 0 || certFile != "" || keyFile != "" {
		var err error
		cfg.Certificates = make([]tls.Certificate, 1)
		cfg.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
		if err != nil {
			return err
		}
	}

	ln, err := net.Listen("tcp", addr)
	if err != nil {
		return err
	}
	ln = tls.NewListener(ln, cfg)
	return srv.Serve(ln)
}

func (s *Server) logf(format string, v ...interface{}) {
	if s.ErrorLog != nil {
		s.ErrorLog.Printf(format, v...)
	}
}


text:
package com.smartstudio.deviceinfo.analytics.about;

import android.os.Bundle;

import com.google.firebase.analytics.FirebaseAnalytics;
import com.smartstudio.deviceinfo.analytics.FirebaseAnalyticsManagerImpl;

import javax.inject.Inject;
import javax.inject.Provider;

public class AboutFirebaseAnalyticsImpl extends FirebaseAnalyticsManagerImpl implements AboutAnalytics {
    static final String SCREEN_NAME = "About";
    static final String TAP_OPEN_SOURCE = "Tap open source link";
    static final String TAP_ATTRIBUTIONS = "Tap attributions";
    static final String TAP_ACTION_BAR_BACK = "Tap action bar back";

    /**
     * Creates an instance of the AnalyticsManagerImpl
     **/
    @Inject
    AboutFirebaseAnalyticsImpl(FirebaseAnalytics analytics, Provider<Bundle> bundleProvider) {
        super(analytics, bundleProvider);
    }

    @Override
    protected String getScreenName() {
        return SCREEN_NAME;
    }

    @Override
    public void reportOpenSourceTap() {
        reportEvent(TAP_OPEN_SOURCE);
    }

    @Override
    public void reportAttributionsTap() {
        reportEvent(TAP_ATTRIBUTIONS);
    }

    @Override
    public void reportActionBarBackTap() {
        reportEvent(TAP_ACTION_BAR_BACK);
    }
}


text:
#ifndef HALIDE_INLINE_H
#define HALIDE_INLINE_H

/** \file
 * Methods for replacing calls to functions with their definitions.
 */

#include "IR.h"

namespace Halide {
namespace Internal {

/** Inline a single named function, which must be pure. */
// @{
Stmt inline_function(Stmt, Function);
Expr inline_function(Expr, Function);
// @}

}
}

#endif


text:
/**
 * Provides PXF Rest API resources.
 */
package org.apache.hawq.pxf.service;


text:
<?php

/**
 * @category   PHP
 * @package    CodeCoverage
 * @author     Arne Blankerts <arne@blankerts.de>
 * @copyright  Sebastian Bergmann <sebastian@phpunit.de>
 * @license    http://www.opensource.org/licenses/BSD-3-Clause  The BSD 3-Clause License
 * @link       http://github.com/sebastianbergmann/php-code-coverage
 * @since      Class available since Release 2.0.0
 */
class PHP_CodeCoverage_Report_XML_Node
{
    /**
     * @var DOMDocument
     */
    private $dom;

    /**
     * @var DOMElement
     */
    private $contextNode;

    public function __construct(DOMElement $context)
    {
        $this->setContextNode($context);
    }

    protected function setContextNode(DOMElement $context)
    {
        $this->dom         = $context->ownerDocument;
        $this->contextNode = $context;
    }

    public function getDom()
    {
        return $this->dom;
    }

    protected function getContextNode()
    {
        return $this->contextNode;
    }

    public function getTotals()
    {
        $totalsContainer = $this->getContextNode()->firstChild;

        if (!$totalsContainer) {
            $totalsContainer = $this->getContextNode()->appendChild(
                $this->dom->createElementNS(
                    'http://schema.phpunit.de/coverage/1.0',
                    'totals'
                )
            );
        }

        return new PHP_CodeCoverage_Report_XML_Totals($totalsContainer);
    }

    public function addDirectory($name)
    {
        $dirNode = $this->getDom()->createElementNS(
            'http://schema.phpunit.de/coverage/1.0',
            'directory'
        );

        $dirNode->setAttribute('name', $name);
        $this->getContextNode()->appendChild($dirNode);

        return new PHP_CodeCoverage_Report_XML_Directory($dirNode);
    }

    public function addFile($name, $href)
    {
        $fileNode = $this->getDom()->createElementNS(
            'http://schema.phpunit.de/coverage/1.0',
            'file'
        );

        $fileNode->setAttribute('name', $name);
        $fileNode->setAttribute('href', $href);
        $this->getContextNode()->appendChild($fileNode);

        return new PHP_CodeCoverage_Report_XML_File($fileNode);
    }
}


text:
require "minitest_helper"

class AlternateNameTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.preferences.privacy;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.support.annotation.Nullable;
import android.widget.ListView;

import org.chromium.base.VisibleForTesting;
import org.chromium.base.metrics.RecordHistogram;
import org.chromium.base.metrics.RecordUserAction;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.ChromeFeatureList;
import org.chromium.chrome.browser.browsing_data.BrowsingDataType;
import org.chromium.chrome.browser.browsing_data.TimePeriod;
import org.chromium.chrome.browser.help.HelpAndFeedback;
import org.chromium.chrome.browser.multiwindow.MultiWindowUtils;
import org.chromium.chrome.browser.preferences.ButtonPreference;
import org.chromium.chrome.browser.preferences.ClearBrowsingDataCheckBoxPreference;
import org.chromium.chrome.browser.preferences.PrefServiceBridge;
import org.chromium.chrome.browser.preferences.SpinnerPreference;
import org.chromium.chrome.browser.preferences.TextMessageWithLinkAndIconPreference;
import org.chromium.chrome.browser.preferences.privacy.BrowsingDataCounterBridge.BrowsingDataCounterCallback;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.browser.tabmodel.TabModel.TabLaunchType;
import org.chromium.chrome.browser.tabmodel.document.TabDelegate;
import org.chromium.components.signin.ChromeSigninController;

import java.util.Arrays;
import java.util.EnumSet;

/**
 * Preference screen that allows the user to clear browsing data.
 * The user can choose which types of data to clear (history, cookies, etc), and the time range
 * from which to clear data.
 */
public class ClearBrowsingDataPreferences extends PreferenceFragment
        implements PrefServiceBridge.ImportantSitesCallback,
                   PrefServiceBridge.OnClearBrowsingDataListener,
                   PrefServiceBridge.OtherFormsOfBrowsingHistoryListener,
                   Preference.OnPreferenceClickListener, Preference.OnPreferenceChangeListener {
    /**
     * Represents a single item in the dialog.
     */
    private static class Item implements BrowsingDataCounterCallback,
                                         Preference.OnPreferenceClickListener {
        private final ClearBrowsingDataPreferences mParent;
        private final DialogOption mOption;
        private final ClearBrowsingDataCheckBoxPreference mCheckbox;
        private BrowsingDataCounterBridge mCounter;
        private boolean mShouldAnnounceCounterResult;

        public Item(ClearBrowsingDataPreferences parent,
                    DialogOption option,
                    ClearBrowsingDataCheckBoxPreference checkbox,
                    boolean selected,
                    boolean enabled) {
            super();
            mParent = parent;
            mOption = option;
            mCheckbox = checkbox;
            mCounter = new BrowsingDataCounterBridge(this, mOption.getDataType());

            mCheckbox.setOnPreferenceClickListener(this);
            mCheckbox.setEnabled(enabled);
            mCheckbox.setChecked(selected);
            mCheckbox.setSummaryOff("");  // No summary when unchecked.
        }

        public void destroy() {
            mCounter.destroy();
        }

        public DialogOption getOption() {
            return mOption;
        }

        public boolean isSelected() {
            return mCheckbox.isChecked();
        }

        @Override
        public boolean onPreferenceClick(Preference preference) {
            assert mCheckbox == preference;

            mParent.updateButtonState();
            mShouldAnnounceCounterResult = true;
            PrefServiceBridge.getInstance().setBrowsingDataDeletionPreference(
                    mOption.getDataType(), mCheckbox.isChecked());
            return true;
        }

        @Override
        public void onCounterFinished(String result) {
            mCheckbox.setSummaryOn(result);
            if (mShouldAnnounceCounterResult) {
                mCheckbox.announceForAccessibility(result);
            }
        }

        /**
         * Sets whether the BrowsingDataCounter result should be announced. This is when the counter
         * recalculation was caused by a checkbox state change (as opposed to fragment
         * initialization or time period change).
         */
        public void setShouldAnnounceCounterResult(boolean value) {
            mShouldAnnounceCounterResult = value;
        }
    }

    private static final String PREF_HISTORY = "clear_history_checkbox";
    private static final String PREF_COOKIES = "clear_cookies_checkbox";
    private static final String PREF_CACHE = "clear_cache_checkbox";
    private static final String PREF_PASSWORDS = "clear_passwords_checkbox";
    private static final String PREF_FORM_DATA = "clear_form_data_checkbox";

    @VisibleForTesting
    public static final String PREF_GOOGLE_SUMMARY = "google_summary";
    @VisibleForTesting
    public static final String PREF_GENERAL_SUMMARY = "general_summary";
    private static final String PREF_TIME_RANGE = "time_period_spinner";

    /** The "Clear" button preference. */
    @VisibleForTesting
    public static final String PREF_CLEAR_BUTTON = "clear_button";

    /** The tag used for logging. */
    public static final String TAG = "ClearBrowsingDataPreferences";

    /** The histogram for the dialog about other forms of browsing history. */
    private static final String DIALOG_HISTOGRAM =
            "History.ClearBrowsingData.ShownHistoryNoticeAfterClearing";

    /** The web history URL. */
    private static final String WEB_HISTORY_URL =
            "https://history.google.com/history/?utm_source=chrome_cbd";

    /**
     * Used for the onActivityResult pattern. The value is arbitrary, just to distinguish from other
     * activities that we might be using onActivityResult with as well.
     */
    private static final int IMPORTANT_SITES_DIALOG_CODE = 1;

    private static final int IMPORTANT_SITES_PERCENTAGE_BUCKET_COUNT = 20;

    /**
     * The various data types that can be cleared via this screen.
     */
    public enum DialogOption {
        CLEAR_HISTORY(BrowsingDataType.HISTORY, PREF_HISTORY),
        CLEAR_COOKIES_AND_SITE_DATA(BrowsingDataType.COOKIES, PREF_COOKIES),
        CLEAR_CACHE(BrowsingDataType.CACHE, PREF_CACHE),
        CLEAR_PASSWORDS(BrowsingDataType.PASSWORDS, PREF_PASSWORDS),
        CLEAR_FORM_DATA(BrowsingDataType.FORM_DATA, PREF_FORM_DATA);

        private final int mDataType;
        private final String mPreferenceKey;

        private DialogOption(int dataType, String preferenceKey) {
            mDataType = dataType;
            mPreferenceKey = preferenceKey;
        }

        public int getDataType() {
            return mDataType;
        }

        /**
         * @return String The key of the corresponding preference.
         */
        public String getPreferenceKey() {
            return mPreferenceKey;
        }
    }

    /**
     * An option to be shown in the time period spiner.
     */
    private static class TimePeriodSpinnerOption {
        private int mTimePeriod;
        private String mTitle;

        /**
         * Constructs this time period spinner option.
         * @param timePeriod The time period represented as an int from the shared enum
         *     {@link TimePeriod}.
         * @param title The text that will be used to represent this item in the spinner.
         */
        public TimePeriodSpinnerOption(int timePeriod, String title) {
            mTimePeriod = timePeriod;
            mTitle = title;
        }

        /**
         * @return The time period represented as an int from the shared enum {@link TimePeriod}
         */
        public int getTimePeriod() {
            return mTimePeriod;
        }

        @Override
        public String toString() {
            return mTitle;
        }
    }

    private OtherFormsOfHistoryDialogFragment mDialogAboutOtherFormsOfBrowsingHistory;
    private boolean mIsDialogAboutOtherFormsOfBrowsingHistoryEnabled;

    private ProgressDialog mProgressDialog;
    private Item[] mItems;

    // This is a constant on the C++ side.
    private int mMaxImportantSites;
    // This is the sorted list of important registerable domains. If null, then we haven't finished
    // fetching them yet.
    private String[] mSortedImportantDomains;
    // These are the reasons the above domains were chosen as important.
    private int[] mSortedImportantDomainReasons;
    // These are full url examples of the domains above. We use them for favicons.
    private String[] mSortedExampleOrigins;
    // This is the dialog we show to the user that lets them 'uncheck' (or exclude) the above
    // important domains from being cleared.
    private ConfirmImportantSitesDialogFragment mConfirmImportantSitesDialog;

    private final EnumSet<DialogOption> getSelectedOptions() {
        EnumSet<DialogOption> selected = EnumSet.noneOf(DialogOption.class);
        for (Item item : mItems) {
            if (item.isSelected()) selected.add(item.getOption());
        }
        return selected;
    }

    /**
     * Requests the browsing data corresponding to the given dialog options to be deleted.
     * @param options The dialog options whose corresponding data should be deleted.
     */
    private final void clearBrowsingData(EnumSet<DialogOption> options,
            @Nullable String[] blacklistedDomains, @Nullable int[] blacklistedDomainReasons,
            @Nullable String[] ignoredDomains, @Nullable int[] ignoredDomainReasons) {
        showProgressDialog();

        int[] dataTypes = new int[options.size()];
        int i = 0;
        for (DialogOption option : options) {
            dataTypes[i] = option.getDataType();
            ++i;
        }

        Object spinnerSelection =
                ((SpinnerPreference) findPreference(PREF_TIME_RANGE)).getSelectedOption();
        int timePeriod = ((TimePeriodSpinnerOption) spinnerSelection).getTimePeriod();
        if (blacklistedDomains != null && blacklistedDomains.length != 0) {
            PrefServiceBridge.getInstance().clearBrowsingDataExcludingDomains(this, dataTypes,
                    timePeriod, blacklistedDomains, blacklistedDomainReasons, ignoredDomains,
                    ignoredDomainReasons);
        } else {
            PrefServiceBridge.getInstance().clearBrowsingData(this, dataTypes, timePeriod);
        }
    }

    private void dismissProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
        mProgressDialog = null;
    }

    /**
     * Returns the Array of dialog options. Options are displayed in the same
     * order as they appear in the array.
     */
    private DialogOption[] getDialogOptions() {
        return new DialogOption[] {
                DialogOption.CLEAR_HISTORY,
                DialogOption.CLEAR_COOKIES_AND_SITE_DATA,
                DialogOption.CLEAR_CACHE,
                DialogOption.CLEAR_PASSWORDS,
                DialogOption.CLEAR_FORM_DATA
        };
    }

    /**
     * Returns the Array of time periods. Options are displayed in the same order as they appear
     * in the array.
     */
    private TimePeriodSpinnerOption[] getTimePeriodSpinnerOptions() {
        Activity activity = getActivity();

        TimePeriodSpinnerOption[] options = new TimePeriodSpinnerOption[] {
                new TimePeriodSpinnerOption(TimePeriod.LAST_HOUR,
                        activity.getString(R.string.clear_browsing_data_period_hour)),
                new TimePeriodSpinnerOption(TimePeriod.LAST_DAY,
                        activity.getString(R.string.clear_browsing_data_period_day)),
                new TimePeriodSpinnerOption(TimePeriod.LAST_WEEK,
                        activity.getString(R.string.clear_browsing_data_period_week)),
                new TimePeriodSpinnerOption(TimePeriod.FOUR_WEEKS,
                        activity.getString(R.string.clear_browsing_data_period_four_weeks)),
                new TimePeriodSpinnerOption(TimePeriod.ALL_TIME,
                        activity.getString(R.string.clear_browsing_data_period_everything))};

        return options;
    }

    /**
     * Decides whether a given dialog option should be selected when the dialog is initialized.
     * @param option The option in question.
     * @return boolean Whether the given option should be preselected.
     */
    private boolean isOptionSelectedByDefault(DialogOption option) {
        return PrefServiceBridge.getInstance().getBrowsingDataDeletionPreference(
                option.getDataType());
    }

    /**
     * Called when clearing browsing data completes.
     * Implements the ChromePreferences.OnClearBrowsingDataListener interface.
     */
    @Override
    public void onBrowsingDataCleared() {
        if (getActivity() == null) return;

        // If the user deleted their browsing history, the dialog about other forms of history
        // is enabled, and it has never been shown before, show it. Note that opening a new
        // DialogFragment is only possible if the Activity is visible.
        //
        // If conditions to show the dialog about other forms of history are not met, just close
        // this preference screen.
        if (MultiWindowUtils.isActivityVisible(getActivity())
                && getSelectedOptions().contains(DialogOption.CLEAR_HISTORY)
                && mIsDialogAboutOtherFormsOfBrowsingHistoryEnabled
                && !OtherFormsOfHistoryDialogFragment.wasDialogShown(getActivity())) {
            mDialogAboutOtherFormsOfBrowsingHistory = new OtherFormsOfHistoryDialogFragment();
            mDialogAboutOtherFormsOfBrowsingHistory.show(getActivity());
            dismissProgressDialog();
            RecordHistogram.recordBooleanHistogram(DIALOG_HISTOGRAM, true);
        } else {
            dismissProgressDialog();
            getActivity().finish();
            RecordHistogram.recordBooleanHistogram(DIALOG_HISTOGRAM, false);
        }
    }

    /**
     * Returns if we should show the important sites dialog. We check to see if
     *

     *
We've fetched the important sites,
     *
there are important sites,
     *
the feature is enabled, and
     *
we have cache or cookies selected.
     *

     */
    private boolean shouldShowImportantSitesDialog() {
        if (!ChromeFeatureList.isEnabled(ChromeFeatureList.IMPORTANT_SITES_IN_CBD)) return false;
        EnumSet<DialogOption> selectedOptions = getSelectedOptions();
        if (!selectedOptions.contains(DialogOption.CLEAR_CACHE)
                && !selectedOptions.contains(DialogOption.CLEAR_COOKIES_AND_SITE_DATA)) {
            return false;
        }
        boolean haveImportantSites =
                mSortedImportantDomains != null && mSortedImportantDomains.length != 0;
        RecordHistogram.recordBooleanHistogram(
                "History.ClearBrowsingData.ImportantDialogShown", haveImportantSites);
        return haveImportantSites;
    }

    @Override
    public boolean onPreferenceClick(Preference preference) {
        if (preference.getKey().equals(PREF_CLEAR_BUTTON)) {
            if (shouldShowImportantSitesDialog()) {
                showImportantDialogThenClear();
                return true;
            }
            // If sites haven't been fetched, just clear the browsing data regularly rather than
            // waiting to show the important sites dialog.
            clearBrowsingData(getSelectedOptions(), null, null, null, null);
            return true;
        }
        return false;
    }

    @Override
    public boolean onPreferenceChange(Preference preference, Object value) {
        if (preference.getKey().equals(PREF_TIME_RANGE)) {
            // Inform the items that a recalculation is going to happen as a result of the time
            // period change.
            for (Item item : mItems) {
                item.setShouldAnnounceCounterResult(false);
            }

            PrefServiceBridge.getInstance().setBrowsingDataDeletionTimePeriod(
                    ((TimePeriodSpinnerOption) value).getTimePeriod());
            return true;
        }
        return false;
    }

    /**
     * Disable the "Clear" button if none of the options are selected. Otherwise, enable it.
     */
    private void updateButtonState() {
        ButtonPreference clearButton = (ButtonPreference) findPreference(PREF_CLEAR_BUTTON);
        if (clearButton == null) return;
        boolean isEnabled = !getSelectedOptions().isEmpty();
        clearButton.setEnabled(isEnabled);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        RecordUserAction.record("ClearBrowsingData_DialogCreated");
        mMaxImportantSites = PrefServiceBridge.getMaxImportantSites();
        PrefServiceBridge.getInstance().requestInfoAboutOtherFormsOfBrowsingHistory(this);
        getActivity().setTitle(R.string.clear_browsing_data_title);
        addPreferencesFromResource(R.xml.clear_browsing_data_preferences);
        DialogOption[] options = getDialogOptions();
        mItems = new Item[options.length];
        for (int i = 0; i < options.length; i++) {
            boolean enabled = true;

            // It is possible to disable the deletion of browsing history.
            if (options[i] == DialogOption.CLEAR_HISTORY
                    && !PrefServiceBridge.getInstance().canDeleteBrowsingHistory()) {
                enabled = false;
                PrefServiceBridge.getInstance().setBrowsingDataDeletionPreference(
                        DialogOption.CLEAR_HISTORY.getDataType(), false);
            }

            mItems[i] = new Item(
                this,
                options[i],
                (ClearBrowsingDataCheckBoxPreference) findPreference(options[i].getPreferenceKey()),
                isOptionSelectedByDefault(options[i]),
                enabled);
        }

        // Not all checkboxes defined in the layout are necessarily handled by this class
        // or a particular subclass. Hide those that are not.
        EnumSet<DialogOption> unboundOptions = EnumSet.allOf(DialogOption.class);
        unboundOptions.removeAll(Arrays.asList(getDialogOptions()));
        for (DialogOption option : unboundOptions) {
            getPreferenceScreen().removePreference(findPreference(option.getPreferenceKey()));
        }

        // The time range selection spinner.
        SpinnerPreference spinner = (SpinnerPreference) findPreference(PREF_TIME_RANGE);
        spinner.setOnPreferenceChangeListener(this);
        TimePeriodSpinnerOption[] spinnerOptions = getTimePeriodSpinnerOptions();
        int selectedTimePeriod =
                PrefServiceBridge.getInstance().getBrowsingDataDeletionTimePeriod();
        int spinnerOptionIndex = -1;
        for (int i = 0; i < spinnerOptions.length; ++i) {
            if (spinnerOptions[i].getTimePeriod() == selectedTimePeriod) {
                spinnerOptionIndex = i;
                break;
            }
        }
        assert spinnerOptionIndex != -1;
        spinner.setOptions(spinnerOptions, spinnerOptionIndex);

        // The "Clear" button.
        ButtonPreference clearButton = (ButtonPreference) findPreference(PREF_CLEAR_BUTTON);
        clearButton.setOnPreferenceClickListener(this);
        clearButton.setShouldDisableView(true);

        // The general information footnote informs users about data that will not be deleted.
        // If the user is signed in, it also informs users about the behavior of synced deletions.
        // and we show an additional Google-specific footnote. This footnote informs users that they
        // will not be signed out of their Google account, and if the web history service indicates
        // that they have other forms of browsing history, then also about that.
        TextMessageWithLinkAndIconPreference google_summary =
                (TextMessageWithLinkAndIconPreference) findPreference(PREF_GOOGLE_SUMMARY);
        TextMessageWithLinkAndIconPreference general_summary =
                (TextMessageWithLinkAndIconPreference) findPreference(PREF_GENERAL_SUMMARY);

        google_summary.setLinkClickDelegate(new Runnable() {
            @Override
            public void run() {
                new TabDelegate(false /* incognito */).launchUrl(
                        WEB_HISTORY_URL, TabLaunchType.FROM_CHROME_UI);
            }
        });
        general_summary.setLinkClickDelegate(new Runnable() {
            @Override
            public void run() {
                HelpAndFeedback.getInstance(getActivity()).show(
                        getActivity(),
                        getResources().getString(R.string.help_context_clear_browsing_data),
                        Profile.getLastUsedProfile(),
                        null);
            }
        });
        if (ChromeSigninController.get(getActivity()).isSignedIn()) {
            general_summary.setSummary(
                    R.string.clear_browsing_data_footnote_sync_and_site_settings);
        } else {
            getPreferenceScreen().removePreference(google_summary);
            general_summary.setSummary(R.string.clear_browsing_data_footnote_site_settings);
        }
        if (ChromeFeatureList.isEnabled(ChromeFeatureList.IMPORTANT_SITES_IN_CBD)) {
            PrefServiceBridge.fetchImportantSites(this);
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Now that the dialog's view has been created, update the button state.
        updateButtonState();

        // Remove the dividers between checkboxes.
        ((ListView) getView().findViewById(android.R.id.list)).setDivider(null);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dismissProgressDialog();
        for (Item item : mItems) {
            item.destroy();
        }
    }

    // We either show the dialog, or modify the current one to display our messages.  This avoids
    // a dialog flash.
    private final void showProgressDialog() {
        if (getActivity() == null) return;
        mProgressDialog = ProgressDialog.show(getActivity(),
                getActivity().getString(R.string.clear_browsing_data_progress_title),
                getActivity().getString(R.string.clear_browsing_data_progress_message), true,
                false);
    }

    @VisibleForTesting
    ProgressDialog getProgressDialog() {
        return mProgressDialog;
    }

    @VisibleForTesting
    ConfirmImportantSitesDialogFragment getImportantSitesDialogFragment() {
        return mConfirmImportantSitesDialog;
    }

    /**
     * This method shows the important sites dialog. After the dialog is shown, we correctly clear.
     */
    private void showImportantDialogThenClear() {
        mConfirmImportantSitesDialog = ConfirmImportantSitesDialogFragment.newInstance(
                mSortedImportantDomains, mSortedImportantDomainReasons, mSortedExampleOrigins);
        mConfirmImportantSitesDialog.setTargetFragment(this, IMPORTANT_SITES_DIALOG_CODE);
        mConfirmImportantSitesDialog.show(
                getFragmentManager(), ConfirmImportantSitesDialogFragment.FRAGMENT_TAG);
    }

    @Override
    public void showNoticeAboutOtherFormsOfBrowsingHistory() {
        if (getActivity() == null) return;

        TextMessageWithLinkAndIconPreference google_summary =
                (TextMessageWithLinkAndIconPreference) findPreference(PREF_GOOGLE_SUMMARY);
        if (google_summary == null) return;
        google_summary.setSummary(
                R.string.clear_browsing_data_footnote_signed_and_other_forms_of_history);
    }

    @Override
    public void enableDialogAboutOtherFormsOfBrowsingHistory() {
        if (getActivity() == null) return;

        mIsDialogAboutOtherFormsOfBrowsingHistoryEnabled = true;
    }

    /**
     * Used only to access the dialog about other forms of browsing history from tests.
     */
    @VisibleForTesting
    OtherFormsOfHistoryDialogFragment getDialogAboutOtherFormsOfBrowsingHistory() {
        return mDialogAboutOtherFormsOfBrowsingHistory;
    }

    @Override
    public void onImportantRegisterableDomainsReady(
            String[] domains, String[] exampleOrigins, int[] importantReasons) {
        if (domains == null) return;
        // mMaxImportantSites is a constant on the C++ side. While 0 is valid, use 1 as the minimum
        // because histogram code assumes a min >= 1; the underflow bucket will record the 0s.
        RecordHistogram.recordLinearCountHistogram("History.ClearBrowsingData.NumImportant",
                domains.length, 1, mMaxImportantSites + 1, mMaxImportantSites + 1);
        mSortedImportantDomains = Arrays.copyOf(domains, domains.length);
        mSortedImportantDomainReasons = Arrays.copyOf(importantReasons, importantReasons.length);
        mSortedExampleOrigins = Arrays.copyOf(exampleOrigins, exampleOrigins.length);
    }

    /**
     * This is the callback for the important domain dialog. We should only clear if we get the
     * positive button response.
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == IMPORTANT_SITES_DIALOG_CODE && resultCode == Activity.RESULT_OK) {
            // Deselected means that the user is excluding the domain from being cleared.
            String[] deselectedDomains = data.getStringArrayExtra(
                    ConfirmImportantSitesDialogFragment.DESELECTED_DOMAINS_TAG);
            int[] deselectedDomainReasons = data.getIntArrayExtra(
                    ConfirmImportantSitesDialogFragment.DESELECTED_DOMAIN_REASONS_TAG);
            String[] ignoredDomains = data.getStringArrayExtra(
                    ConfirmImportantSitesDialogFragment.IGNORED_DOMAINS_TAG);
            int[] ignoredDomainReasons = data.getIntArrayExtra(
                    ConfirmImportantSitesDialogFragment.IGNORED_DOMAIN_REASONS_TAG);
            if (deselectedDomains != null && mSortedImportantDomains != null) {
                // mMaxImportantSites is a constant on the C++ side.
                RecordHistogram.recordCustomCountHistogram(
                        "History.ClearBrowsingData.ImportantDeselectedNum",
                        deselectedDomains.length, 1, mMaxImportantSites + 1,
                        mMaxImportantSites + 1);
                RecordHistogram.recordCustomCountHistogram(
                        "History.ClearBrowsingData.ImportantIgnoredNum", ignoredDomains.length, 1,
                        mMaxImportantSites + 1, mMaxImportantSites + 1);
                // We put our max at 20 instead of 100 to reduce the number of empty buckets (as
                // our maximum denominator is 5).
                RecordHistogram.recordEnumeratedHistogram(
                        "History.ClearBrowsingData.ImportantDeselectedPercent",
                        deselectedDomains.length * IMPORTANT_SITES_PERCENTAGE_BUCKET_COUNT
                                / mSortedImportantDomains.length,
                        IMPORTANT_SITES_PERCENTAGE_BUCKET_COUNT + 1);
                RecordHistogram.recordEnumeratedHistogram(
                        "History.ClearBrowsingData.ImportantIgnoredPercent",
                        ignoredDomains.length * IMPORTANT_SITES_PERCENTAGE_BUCKET_COUNT
                                / mSortedImportantDomains.length,
                        IMPORTANT_SITES_PERCENTAGE_BUCKET_COUNT + 1);
            }
            clearBrowsingData(getSelectedOptions(), deselectedDomains, deselectedDomainReasons,
                    ignoredDomains, ignoredDomainReasons);
        }
    }
}


text:
![Swift](https://img.shields.io/badge/Swift-4.1-orange.svg)
[![CI Status](http://img.shields.io/travis/pisces/OrangeLabel.svg?style=flat)](https://travis-ci.org/pisces/OrangeLabel)
[![Version](https://img.shields.io/cocoapods/v/OrangeLabel.svg?style=flat)](http://cocoapods.org/pods/OrangeLabel)
[![License](https://img.shields.io/cocoapods/l/OrangeLabel.svg?style=flat)](http://cocoapods.org/pods/OrangeLabel)
[![Platform](https://img.shields.io/cocoapods/p/OrangeLabel.svg?style=flat)](http://cocoapods.org/pods/OrangeLabel)
[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)

- OrangeLabel is extensions of UILabel linkable, available line background and placeholder text

## Features
- Link for mention, hashtag, url and custom
- Placeholder text and color
- Line background

## Import

```swift
import OrangeLabel
```

## Example
<img src="Screenshot/ss_01.png" width="375" />

```swift
let numbers = UILabelLinkType.custom(pattern: "[0-9]+")
let label = OrangeLabel()
label.adjustsFontSizeToFitWidth = true
label.enabledLinkTypes = [.mention, .hashtag, .url, numbers]
label.isUserInteractionEnabled = true
label.font = UIFont(name: "AvenirNext-Bold", size: 60)
label.minimumScaleFactor = 0.2
label.lineBackgroundColor = .black
label.lineBackgroundInset = UIEdgeInsets(top: -5, left: 5, bottom: -5, right: 5)
label.numberOfLines = 0
label.text = "@steve Your selfie overed 1000 views @steve Your selfie overed 1000 views @steve Your selfie overed 1000 views @steve #hahaha http://retrica.co Your selfie overed 1000 views @steve Your selfie overed 1000 views @steve Your selfie overed 1000 views www.retrica.co @steve Your selfie overed 1000 views @steve Your selfie overed 1000 views @steve #hahaha Your selfie overed 1000 views @steve Your selfie overed 1000 views"
label.textAlignment = .center
label.textColor = .white

label.setHighlightedLinkColor(UIColor.white.withAlphaComponent(0.5), type: .mention)
    .setHighlightedLinkColor(UIColor.white.withAlphaComponent(0.5), type: .hashtag)
    .setHighlightedLinkColor(UIColor.white.withAlphaComponent(0.5), type: .url)
    .setHighlightedLinkColor(UIColor.white.withAlphaComponent(0.5), type: numbers)
    .setAttributes([NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue,
                    NSForegroundColorAttributeName: UIColor(red: 1, green: 185/255, blue: 0, alpha: 1)], type: .mention)
    .setAttributes([NSForegroundColorAttributeName: UIColor(red: 225/255, green: 66/255, blue: 16/255, alpha: 1)], type: .hashtag)
    .setAttributes([NSForegroundColorAttributeName: UIColor(red: 0, green: 204/255, blue: 238/255, alpha: 1)], type: .url)
    .setAttributes([NSForegroundColorAttributeName: UIColor(red: 1, green: 85/255, blue: 0, alpha: 1)], type: numbers)

label.linkTapped { (link) in
    print(link)
}
```

## Installation

### CocoaPods

[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command:

```bash
$ gem install cocoapods
```

> CocoaPods 1.1.0+ is required to build OrangeLabel 0.1.0+.

To integrate OrangeLabel into your Xcode project using CocoaPods, specify it in your `Podfile`:

```ruby
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'

target '<Your Target Name>' do
    pod 'OrangeLabel', '~> 0.2.0'
end
```

Then, run the following command:

```bash
$ pod install
```

### Carthage

[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

You can install Carthage with [Homebrew](http://brew.sh/) using the following command:

```bash
$ brew update
$ brew install carthage
```

To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`:

```ogdl
github "pisces/OrangeLabel" ~> 0.2.0
```

Run `carthage update` to build the framework and drag the built `OrangeLabel.framework` into your Xcode project.

## Requirements

iOS Deployment Target 9.0 higher

## Author

Steve Kim, hh963103@gmail.com

## License

OrangeLabel is available under the MIT license. See the LICENSE file for more info.


text:
// Verify that properties can vary independently in comparable relationship

declare const x: { a: 1, b: string };
declare const y: { a: number, b: 'a' };

x === y;


text:
namespace StarboardWinRT {
// Provides an interface for an application that owns DeviceResources to be notified of the device being lost or
// created.
interface IDeviceNotify {
    virtual void OnDeviceLost() = 0;
    virtual void OnDeviceRestored() = 0;
};

// Controls all the DirectX device resources.
class DeviceResources {
public:
    DeviceResources();
    void SetLogicalSize(Windows::Foundation::Size logicalSize);
    void SetCurrentOrientation(Windows::Graphics::Display::DisplayOrientations currentOrientation);
    virtual void SetDpi(float dpi) = 0;
    void ValidateDevice();
    void HandleDeviceLost();
    void RegisterDeviceNotify(IDeviceNotify* deviceNotify);
    void Trim();
    void Present();

    // Device Accessors.
    Windows::Foundation::Size GetOutputSize() const {
        return m_outputSize;
    }
    Windows::Foundation::Size GetLogicalSize() const {
        return m_logicalSize;
    }

    // D3D Accessors.
    ID3D11Device2* GetD3DDevice() const {
        return m_d3dDevice.Get();
    }
    ID3D11DeviceContext2* GetD3DDeviceContext() const {
        return m_d3dContext.Get();
    }
    IDXGISwapChain1* GetSwapChain() const {
        return m_swapChain.Get();
    }
    D3D_FEATURE_LEVEL GetDeviceFeatureLevel() const {
        return m_d3dFeatureLevel;
    }
    ID3D11RenderTargetView* GetBackBufferRenderTargetView() const {
        return m_d3dRenderTargetView.Get();
    }
    D3D11_VIEWPORT GetScreenViewport() const {
        return m_screenViewport;
    }
    DirectX::XMFLOAT4X4 GetOrientationTransform3D() const {
        return m_orientationTransform3D;
    }

protected:
    void CreateDeviceIndependentResources();
    void CreateDeviceResources();
    virtual void CreateWindowSizeDependentResources() = 0;
    DXGI_MODE_ROTATION ComputeDisplayRotation();

    // Direct3D objects.
    Microsoft::WRL::ComPtr<ID3D11Device2> m_d3dDevice;
    Microsoft::WRL::ComPtr<ID3D11DeviceContext2> m_d3dContext;
    Microsoft::WRL::ComPtr<IDXGISwapChain1> m_swapChain;

    // Direct3D rendering objects. Required for 3D.
    Microsoft::WRL::ComPtr<ID3D11RenderTargetView> m_d3dRenderTargetView;
    D3D11_VIEWPORT m_screenViewport;

    // Cached device properties.
    D3D_FEATURE_LEVEL m_d3dFeatureLevel;
    Windows::Foundation::Size m_d3dRenderTargetSize;
    Windows::Foundation::Size m_outputSize;
    Windows::Foundation::Size m_logicalSize;
    Windows::Graphics::Display::DisplayOrientations m_nativeOrientation;
    Windows::Graphics::Display::DisplayOrientations m_currentOrientation;
    float m_dpi;

    // Transforms used for display orientation.
    DirectX::XMFLOAT4X4 m_orientationTransform3D;

    // The IDeviceNotify can be held directly as it owns the DeviceResources.
    IDeviceNotify* m_deviceNotify;
};
}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Class: Bud::MaxLattice</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href="../.././rdoc-style.css" type="text/css" media="screen" />

          Class
          Bud::MaxLattice

            In:

                lib/bud/lattice-lib.rb

            Parent:

                Bud::Lattice

Methods

      lt_eq
      merge
      new

Public Class methods

          new(i=-Float::INFINITY)

Public Instance methods

          lt_eq(k)

          merge(i)

[Validate]