text:
package com.francetelecom.rd.stubs.engine;

import java.io.IOException;
import java.io.PrintStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * @author piac6784
 *
 */
/**
 * @author piac6784
 *
 */
public class AnnotatingClassDumper extends ClassDumper {

	private static final String TOKEN_CLASS_KEY = "tokenClass";
	/**
	 * The key to get the name of the annotation package in properties.
	 */
	public static final String ANNOTATION_PACKAGE_KEY = "annotationPackage";
	private static final String GENERATOR_CLASS_KEY = "generatorClass";

	final static String[] primitiveTypes = { "boolean", "byte", "char",
			"short", "int", "long", "float", "double" };

	/**
	 * The name of the class used as an internal token for all generated
	 * constructors.
	 */
	private final String tokenClass;

	/**
	 * The name of the class used as an internal token for all generated
	 * constructors.
	 */
	private final String generatorClass;

	/**
	 * A complete hierarchy to know what can be dumped as default value.
	 */
	private final Hierarchy hierarchy;

	/**
	 * Counter to generate unique variable names.
	 */
	private int varCounter = 0;

	/**
	 * All the already defined real class implementations.
	 */
	private HashSet <String> realClasses  = new HashSet<String>();

	/**
	 * Handle to the name cleaner
	 */
	private ReflexUtil rf;
	private Object context;

	/**
	 * Constructor in the most usual case: does not show private elements.
	 *
	 * @param outDir
	 *            the name of the directory where the new source tree is created
	 * @param prefix
	 *            the relocation prefix added for the classloader.
	 */
	public AnnotatingClassDumper(String outDir, ReflexUtil rf,
			Properties properties, Hierarchy hierarchy) {
		super(outDir, rf, true, null);

		this.hierarchy = hierarchy;
		this.tokenClass = properties.getProperty(TOKEN_CLASS_KEY);
		this.generatorClass = properties.getProperty(GENERATOR_CLASS_KEY);
		this.rf = rf;
	}

	@Override
	public void dumpClass(Class<?> c) throws IOException {
		super.dumpClass(c);
		Annotation annot = rf.findAnnotation(EngineConstant.REAL_ANNOT, c
				.getAnnotations());
		if (annot != null) {
			String name = ReflexUtil.getStringValue(annot);
			String superName = (String) ReflexUtil.getAnnotationField(annot,
					EngineConstant.SUPER_FIELD);
			if (realClasses.contains(name)) {
				System.err.println("You have reused the class name: " + name + " for real classes.");
			} else {
				realClasses.add(name);
				dumpRealClass(c, name, superName);
			}
		}
	}

	@Override
	public boolean dumpClass(PrintStream out, Class<?> c) {
		context = c;
		if (c.isAnonymousClass())
			return false;
		Map<TypeVariable<?>, Type> typeEnv = dumpClassHeader(out, c);
		out.println("{");
		beginIndent();
		if (!c.isInterface()) dumpAddedFields(out, c);
		if (!c.isInterface() && !c.isEnum())
			dumpAddedConstructor(out, c);
		dumpClassBody(out, c, typeEnv);
		endIndent();
		indent(out);
		out.println("}");
		return true;
	}

	private <T> T[] sort(T [] array) {
		Comparator <Object> generic = new Comparator () {
			@Override
			public int compare(Object o1, Object o2) { return o1.toString().compareTo(o2.toString()); }
		};
		Arrays.sort(array, generic);
		return array;
	}

	/**
	 * Dumps the fields added for the annotations.
	 *
	 * @param out
	 * @param c
	 */
	private void dumpAddedFields(PrintStream out, Class<?> c) {
		Annotation [] annotArray = c.getAnnotations();
		Annotation accuAnnotation = rf.findAnnotation(EngineConstant.ACCUMULATOR_ANNOT, annotArray);
		if (accuAnnotation != null && !c.isInterface()) {
			String name = ReflexUtil.getStringValue(accuAnnotation);
			indent(out);
			out.print(ClassDumper.modifier(Modifier.STATIC | Modifier.PUBLIC));
			out.print(rf.restoreString(c.getSimpleName()));
			out.print(" ");
			out.print(name);
			out.println(";");
		}
		List<Annotation> newFieldList = rf.findAnnotations(
				EngineConstant.FIELD_ANNOT, EngineConstant.FIELD_ARRAY_ANNOT, annotArray);
		Set<String> fields = new HashSet<String>();
		// Do not add fields already declared in the class.
		for (Field f: c.getFields()) { fields.add(f.getName()); }

		for (Annotation newField : newFieldList) {
			String name = ReflexUtil.getStringValue(newField);
			fields.add(name);
			String type = rf.restoreString((String) ReflexUtil
					.getAnnotationField(newField, EngineConstant.TYPE_FIELD));
			int mod = (Integer) ReflexUtil.getAnnotationField(newField,
					EngineConstant.MODIFIER_FIELD);
			indent(out);
			out.print(ClassDumper.modifier(mod));
			out.print(type);
			out.print(" ");
			out.print(name);
			out.println(";");
		}

		for (Method m : sort(c.getDeclaredMethods())) {
			Annotation[][] paramAnnotsArray = m.getParameterAnnotations();
			Type[] paramTypes = m.getGenericParameterTypes();
			dumpAddedFields(out, fields, paramTypes, paramAnnotsArray, (m.getModifiers() & Modifier.STATIC) != 0);
		}

		for (Constructor<?> co : sort(c.getDeclaredConstructors())) {
			Annotation[][] paramAnnotsArray = co.getParameterAnnotations();
			Type[] paramTypes = co.getGenericParameterTypes();
			dumpAddedFields(out, fields, paramTypes, paramAnnotsArray, false);
		}
	}

	/**
	 * This auxiliary function looks for field setters in methods or
	 * constructors and dump a field declaration if not already done and the
	 * field is local.
	 *
	 * @param out
	 *            output stream
	 * @param fields
	 *            fields already declared
	 * @param paramTypes
	 *            the types of parameters of the method/constructor
	 * @param paramAnnotsArray
	 *            the annotations for each parameter of method/constructor.
	 * @param b tell if the method added is static
	 */
	private void dumpAddedFields(PrintStream out, Set<String> fields,
			Type[] paramTypes, Annotation[][] paramAnnotsArray, boolean isStatic) {
		for (int i = 0; i < paramAnnotsArray.length; i++) {
			Annotation[] paramAnnots = paramAnnotsArray[i];
			Annotation annot = rf.findAnnotation(
					EngineConstant.FIELD_SET_ANNOT, paramAnnots);
			if (annot != null) {
				String name = ReflexUtil.getStringValue(annot);
				if (!fields.contains(name) && name.indexOf('.') < 0) {
					fields.add(name);
					indent(out);
					out.print(isStatic ? "private static " : "protected ");
					type(out, paramTypes[i]);
					out.print(" ");
					out.print(name);
					out.println(";");
				}
			}
		}
	}

	/**
	 * Dumps a constructor added to be sure that we can generate any object.
	 * This constructor takes a "private" parameter used as an isolation token.
	 * If the class has no constructor, then we must generate an explicit empty
	 * constructor.
	 *
	 * @param out
	 * @param c
	 */
	private void dumpAddedConstructor(PrintStream out, Class<?> c) {
		String classname = shorten(c.getName());
		indent(out);
		out.print("public ");
		out.print(classname.substring(classname.lastIndexOf('.') + 1));
		out.print("(" + tokenClass + " arg0)    {");
		Class<?> superClass = c.getSuperclass();
		if (rf.handledClass(superClass)) {
			beginIndent();
			indent(out);
			out.print("super(arg0);");
			endIndent();
		}
		out.println("// Defaults");
		for(Field field : c.getDeclaredFields()) {
			Annotation [] annots = field.getAnnotations();
			Annotation noValueAnnot = rf.findAnnotation(EngineConstant.FIELD_NO_VALUE_ANNOT, annots);
			if(noValueAnnot != null) {
				out.print(field.getName());
				dumpFieldValue(out,field);
				out.println(";");
			}
		}
		dumpAccumulator(out,c);
		indent(out);
		out.println("}");
	}

	@Override
	protected void dumpAnnotation(PrintStream out, Annotation annot) {
		if (!rf.isStubAnnotation(annot))
			super.dumpAnnotation(out, annot);
	}

	/**
	 * Gets the list of registered callbacks in the list of annotations or null
	 *
	 * @param annotArray
	 * @return
	 */
	private String[] getRegisteredCallbacks(Annotation[] annotArray) {
		Annotation registerAnnot = rf.findAnnotation(
				EngineConstant.CALLBACK_REGISTER_ANNOT, annotArray);
		if (registerAnnot == null)
			return null;
		return (String[]) ReflexUtil.getAnnotationField(registerAnnot,
				EngineConstant.VALUE_FIELD);
	}

	/**
	 * @param out
	 * @param eltAnnot
	 * @param baseClass
	 * @param argsAnnot
	 * @param argsTypes
	 * @param typeEnv
	 */
	private void dumpCallbackCalls(PrintStream out, Annotation[] eltAnnot,
			Class<?> baseClass, Annotation[][] argsAnnot, Class<?>[] argsTypes,
			Map<TypeVariable<?>, Type> typeEnv) {
		String[] baseCallbacks = getRegisteredCallbacks(eltAnnot);
		if (baseCallbacks != null) {
			generateCallbackCalls(out, "this", baseClass, baseCallbacks,
					typeEnv);
		}
		int argCount = 0;

		for (Annotation[] paramAnnots : argsAnnot) {
			String[] argCallbacks = getRegisteredCallbacks(paramAnnots);

			if (argCallbacks != null) {
				Class<?> argClass = argsTypes[argCount];
				generateCallbackCalls(out, "arg" + (argCount + 1), argClass,
						argCallbacks, typeEnv);
			}
			argCount++;
		}
	}

	@Override
	protected void dumpConstructorBody(PrintStream out,
			Constructor<?> constructor, Map<TypeVariable<?>, Type> typeEnv) {
		context = constructor;
		Annotation[] constructorAnnotations = constructor.getAnnotations();
		Annotation[][] parametersAnnotations = constructor
				.getParameterAnnotations();
		Annotation codeAnnotation = rf.findAnnotation(
				EngineConstant.CODE_ANNOT, constructorAnnotations);
		if (codeAnnotation != null) {
			dumpCode(out, codeAnnotation);
		} else {
			super.dumpConstructorBody(out, constructor, typeEnv);
			dumpAccumulator(out,constructor.getDeclaringClass());
			dumpFieldAssigns(out, constructorAnnotations, parametersAnnotations);
			try {
				dumpCallbackCalls(out, constructorAnnotations, constructor
						.getDeclaringClass(), parametersAnnotations,
						constructor.getParameterTypes(), typeEnv);
			} catch (RuntimeException e) {
				System.err.println(rf.restoreString(constructor.toString()));
			}
		}
	}

	private void dumpAccumulator(PrintStream out, Class<?> c) {
		Annotation [] annotArray = c.getAnnotations();
		Annotation accuAnnotation = rf.findAnnotation(EngineConstant.ACCUMULATOR_ANNOT, annotArray);
		if (accuAnnotation != null) {
			String name = ReflexUtil.getStringValue(accuAnnotation);
			indent(out);
			out.print(name);
			out.println(" = this;");
		}
		Class <?> [] itfs =  c.getInterfaces();
		for(Class<?> itf : itfs) {
			annotArray = itf.getAnnotations();
			accuAnnotation = rf.findAnnotation(EngineConstant.ACCUMULATOR_ANNOT, annotArray);
			if (accuAnnotation != null) {
				String itfName = rf.restoreString(itf.getName());
				String name = ReflexUtil.getStringValue(accuAnnotation);
				indent(out);
				out.print(itfName);
				out.print(".");
				out.print(name);
				out.println(" = this;");
			}
		}
	}

	private void dumpCode(PrintStream out, Annotation codeAnnotation) {
		String[] code = ReflexUtil.getStringValues(codeAnnotation);
		for (String codeLine : code) {
			indent(out);
			out.println(rf.restoreString(codeLine));
		}
	}

	private void dumpFieldAssigns(PrintStream out, Annotation[] baseAnnotation,
			Annotation[][] parameterAnnotations) {
		Annotation thisFieldSet = rf.findAnnotation(
				EngineConstant.FIELD_SET_ANNOT, baseAnnotation);
		if (thisFieldSet != null) {
			String name = ReflexUtil.getStringValue(thisFieldSet);
			indent(out);
			out.println(name + " = this;");
		}
		for (int i = 0; i < parameterAnnotations.length; i++) {
			Annotation fieldSet = rf.findAnnotation(
					EngineConstant.FIELD_SET_ANNOT, parameterAnnotations[i]);
			if (fieldSet != null) {
				String name = ReflexUtil.getStringValue(fieldSet);
				indent(out);
				out.println(name + " = arg" + (i + 1) + ";");
			}
		}
	}

	@Override
	protected void dumpMethodBody(PrintStream out, Method method,
			Map<TypeVariable<?>, Type> typeEnv) {
		Annotation[] methodAnnotations = method.getAnnotations();
		Annotation codeAnnotation = rf.findAnnotation(
				EngineConstant.CODE_ANNOT, methodAnnotations);
		if (codeAnnotation != null) {
			dumpCode(out, codeAnnotation);
		} else {
			Annotation[][] parameterAnnotations = method
					.getParameterAnnotations();
			dumpFieldAssigns(out, methodAnnotations, parameterAnnotations);
			try {
				dumpCallbackCalls(out, methodAnnotations, method
						.getDeclaringClass(), parameterAnnotations, method
						.getParameterTypes(), typeEnv);
			} catch (RuntimeException e) {
				System.err.println(rf.restoreString(method.toString()));
			}
			dumpMethodResult(out, method, typeEnv);
		}
	}

	@Override
	protected void dumpMethod(PrintStream out, Method meth, boolean isItf,
			boolean isNotAbstract, Map<TypeVariable<?>, Type> typeEnv) {
		context = meth;
		Annotation annot = rf.findAnnotation(EngineConstant.SUPER_ANNOT, meth
				.getAnnotations());
		if (annot == null)
			super.dumpMethod(out, meth, isItf, isNotAbstract, typeEnv);
		else {
			// TODO Check that this is correct to use USE_SUPER
		}
	}

	/**
	 * Output the result of a method so that it is an actual value.
	 *
	 * @param out
	 * @param method
	 * @param typeEnv
	 */
	private void dumpMethodResult(PrintStream out, Method method,
			Map<TypeVariable<?>, Type> typeEnv) {
		Class<?> result = method.getReturnType();
		if (result.getName().equals("void"))
			return;
		Annotation[] annots = method.getAnnotations();
		Annotation specificResultAnnot = rf.findAnnotation(
				EngineConstant.MAY_BE_ANNOT, annots);
		Annotation fieldResultAnnot = rf.findAnnotation(
				EngineConstant.FIELD_GET_ANNOT, annots);
		if (fieldResultAnnot != null) {
			indent(out);
			String fieldName = ReflexUtil.getStringValue(fieldResultAnnot);
			out.append("return ").append(fieldName).append(";\n");
		} else if (specificResultAnnot != null) {
			String[] mayBeClasses = ReflexUtil
					.getStringValues(specificResultAnnot);
			int count = 0;
			indent(out);
			out.println("switch(" + generatorClass + ".intValue()){");
			for (String maybe : mayBeClasses) {
				indent(out);
				out.println("case " + count++ + ":");
				beginIndent();
				indent(out);
				out.append("return new ").append(maybe).append("(").append(
						generatorClass + ".token").append(");\n");
				endIndent();
			}
			indent(out);
			out.println("default:");
			beginIndent();
			indent(out);
			out.println("return null;");
			endIndent();
			indent(out);
			out.println("}");

		} else {
			String resultContent = buildDefaultValue(out, result, typeEnv);
			indent(out);
			// I do not understand why I need this explicit coercion.
			if (method.getGenericReturnType() instanceof TypeVariable<?>) {
				out.append("return (");
				type(out, method.getGenericReturnType(), true, typeEnv );
				out.append(") ").append(resultContent).append(";\n");
			} else {
				out.append("return ").append(resultContent).append(";\n");
			}
		}
	}

	/**
	 * @param out
	 *            the output stream
	 * @param targetObj
	 *            the name of the element containing the callbacks
	 * @param clazz
	 *            its class.
	 * @param callbackIds
	 *            a list of callback id
	 * @param typeEnv
	 *            a type environment to solve type variables
	 */
	private void generateCallbackCalls(PrintStream out, String targetObj,
			Class<?> clazz, String[] callbackIds,
			Map<TypeVariable<?>, Type> typeEnv) {
		for (String callbackId : callbackIds) {
			int count = generateCallbackCalls(out, targetObj, clazz,
					callbackId, typeEnv);
			if (count == 0) {
				System.err.println("Problem with callbacks in "
						+ rf.restoreString(clazz.getName()) + " for "
						+ callbackId);
				throw new RuntimeException("count");
			}

		}
	}

	/**
	 * Generate the callback for one id. This version recursively explore the
	 * ancestors (interfaces and superclass).
	 *
	 * @param out
	 * @param targetObj
	 * @param clazz
	 * @param callbackId
	 * @param typeEnv
	 * @return
	 */
	private int generateCallbackCalls(PrintStream out, String targetObj,
			Class<?> clazz, String callbackId,
			Map<TypeVariable<?>, Type> typeEnv) {
		int count = generateCallbackCallsLocal(out, targetObj, clazz,
				callbackId, typeEnv);
		Class<?> superClass = clazz.getSuperclass();
		if (superClass != null)
			count += generateCallbackCalls(out, targetObj, superClass,
					callbackId, typeEnv);
		for (Class<?> itfs : clazz.getInterfaces())
			count += generateCallbackCalls(out, targetObj, itfs, callbackId,
					typeEnv);
		return count;
	}

	/**
	 * Generate the callbacks for one id and one class.
	 *
	 * @param out
	 *            the output stream
	 * @param targetObj
	 *            the name of the element containing the callbacks
	 * @param clazz
	 *            its class.
	 * @param callbackId
	 *            a given callback id
	 * @param typeEnv
	 *            a type environment to solve type variables
	 */
	private int generateCallbackCallsLocal(PrintStream out, String targetObj,
			Class<?> clazz, String callbackId,
			Map<TypeVariable<?>, Type> typeEnv) {
		int count = 0;
		int lastDot = callbackId.lastIndexOf('.');
		if (lastDot > 0) {
			// String prefix = callbackId.substring(0, lastDot);
			// String clazzName =
			// restoreString(clazz.getName()).replace('$','.');
			// System.err.println(clazzName + " " + prefix);
			// if (!clazzName.equals(prefix)) return 0;
			callbackId = callbackId.substring(lastDot + 1);
			// System.err.println(callbackId);
		}
		for (Method method : clazz.getDeclaredMethods()) {
			Annotation callbackAnnot = rf.findAnnotation(
					EngineConstant.CALLBACK_ANNOT, method.getAnnotations());
			if (callbackAnnot != null) {
				String[] ids = ReflexUtil.getStringValues(callbackAnnot);
				if (ids == null)
					continue;
				if (contains(ids, callbackId)) {
					Class<?>[] argTypesArray = method.getParameterTypes();
					String[] defaultValuesArray = new String[argTypesArray.length];
					for (int i = 0; i < argTypesArray.length; i++) {
						defaultValuesArray[i] = buildDefaultValue(out,
								argTypesArray[i], typeEnv);
					}
					boolean raiseExc = method.getExceptionTypes().length > 0;
					if (raiseExc) {
						indent(out);
						out.println("try {");
						beginIndent();
					}
					indent(out);
					out.print(targetObj);
					out.print(".");
					out.print(method.getName());
					out.print("(");
					boolean first = true;
					for (int i = 0; i < defaultValuesArray.length; i++) {
						if (first)
							first = false;
						else
							out.print(", ");
						out.print(defaultValuesArray[i]);
					}
					out.println(");");
					if (raiseExc) {
						endIndent();
						indent(out);
						out.println("} catch (Exception exc) { }");
					}
					count++;
				}
			}
		}
		return count;
	}

	/**
	 * This methods gives back a string that represent a default value of class
	 * clazz. But building this value may require several statements that will
	 * be dumped on the output stream during the method execution.
	 *
	 * @param out
	 * @param type
	 * @return
	 */
	private String buildDefaultValue(PrintStream out, Type type,
			Map<TypeVariable<?>, Type> typeEnv) {
		String typeName = type.toString();
		if (contains(primitiveTypes, typeName)) {
			return generatorClass + "." + typeName + "Value()";
		} else {
			if (type instanceof TypeVariable<?>) {
				if (typeEnv == null)
					return "null";
				else {
					Type actual = typeEnv.get((TypeVariable<?>) type);
					if (actual == null)
						return "null";
					else
						return buildDefaultValue(out, actual, null);
				}
			} else if (type instanceof Class<?>) {
				Class<?> clazz = (Class<?>) type;
				if (clazz.isArray()) {
					Class<?> elt = clazz.getComponentType();
					String eltValue = buildDefaultValue(out, elt, typeEnv);
					return "new " + shorten(ReflexUtil.readableName(elt))
							+ "[]{" + eltValue + "}";
				} else if (clazz.isEnum()) {
					return buildDefaultEnumValue(out, clazz, typeEnv);
				} else {
					return buildDefaultClassValue(out, clazz, typeEnv);
				}
			} else {
				return "*** BOGUS " + type + " ***";
			}
		}
	}

	@Override
	protected void dumpField(PrintStream out, Field field, boolean hasValue) {
		Annotation [] annots = field.getAnnotations();
		Annotation implemAnnot = rf.findAnnotation(EngineConstant.FIELD_VALUE_IMPL_ANNOT, annots);

		if (implemAnnot != null) {
			String name = ReflexUtil.getStringValue(implemAnnot);
			String superName;
			Class <?> type = field.getType();
			Annotation [] annotType = type.getAnnotations();
			Annotation realAnnot = rf.findAnnotation(EngineConstant.REAL_ANNOT, annotType);
			if (realAnnot != null) {
				superName = ReflexUtil.getStringValue(realAnnot);
			} else {
				superName = shorten(type.getName());
			}
			indent(out);
			out.println("static class " + name + " extends " + superName + " {");
			beginIndent();
			indent(out);
			out.println("public " + name + "(){ super(" + generatorClass + ".token); }");
			endIndent();
			indent(out);
			out.println("}");
		}
		super.dumpField(out,field,rf.findAnnotation(EngineConstant.FIELD_NO_VALUE_ANNOT, annots) == null );
	}

	private String buildDefaultClassValue(PrintStream out, Class<?> clazz, Map<TypeVariable<?>, Type> typeEnv) {
		int mod = clazz.getModifiers();
		if (! rf.handledClass(clazz)) {
			if (clazz.isInterface() || Modifier.isAbstract(mod)) return "null";
			if (clazz.equals(Class.class)) return "Object.class";
			if (clazz.equals(String.class)) {
				return "\"[stubs:" + rf.restoreString(context.toString()) + "]\"";
			}
			return "new " + clazz.getName() + "()";
		}
		List <Class <?>> subclasses = hierarchy.getSubclasses(clazz);
		if (clazz.isInterface()) {
			if (subclasses == null) subclasses = hierarchy.getImplementors(clazz);
			else subclasses.addAll(hierarchy.getImplementors(clazz));
		}
		String thisDefault;
		// TODO : Here we get rid of interfaces, abstract class but also embedded classes.
		// The last point deserves a second thought.
		Annotation [] annots = clazz.getAnnotations();
		Annotation accumulatorAnnot = rf.findAnnotation(EngineConstant.ACCUMULATOR_ANNOT, annots);
		if (accumulatorAnnot != null) {
			String name = ReflexUtil.getStringValue(accumulatorAnnot);
			// We stop here.
			return rf.restoreString(clazz.getName())+ "." + name;
		}
		if (clazz.isInterface() || Modifier.isAbstract(mod) || (clazz.getEnclosingClass() != null && (!Modifier.isStatic(mod)) || (!Modifier.isPublic(mod)))) {
			thisDefault = interfaceWitness(annots);
		} else {
			thisDefault =
				"new " + shorten(clazz.getName()) + "(" +
				(rf.handledClass(clazz) ? generatorClass + ".token)" : ")");
		}
		if (hierarchy.count(clazz) > 30 || subclasses == null) {
			if (thisDefault.equals("null") && (clazz.isInterface() || Modifier.isAbstract(mod) || clazz.getEnclosingClass() == null)) {
				System.err.println("Warning no default for " + rf.restoreString(clazz.toString())
						+ " in context " + rf.restoreString(context.toString()));
				count++;
			}
			return thisDefault;
		} else {
			int count = 0;
			String var = "v" + varCounter ++;
			indent(out);
			out.println(shorten(clazz.getName()) + " " + var + ";");
			indent(out);
			out.println("switch(" + generatorClass + ".intValue()){");
			for(Class <?> subC : subclasses) {
				indent(out);
				out.println("case " + count++ + ":");
				beginIndent();
				String defSubC = buildDefaultValue(out, subC, typeEnv);
				indent(out);
				out.println(var + " = "  + defSubC + ";");
				indent(out);
				out.println("break;");
				endIndent();
			}
			indent(out);
			out.println("default:");
			beginIndent();
			indent(out);
			out.println(var + " = "  + thisDefault + ";");
			endIndent();
			indent(out);
			out.println("}");
			return var;
		}
	}

	/**
	 * Goes through the different enum constants as they are more or less
	 * independent objects. It is not clear it is of any good.
	 *
	 * @param out
	 * @param enumClazz
	 * @param typeEnv
	 * @return
	 */
	private String buildDefaultEnumValue(PrintStream out, Class<?> enumClazz,
			Map<TypeVariable<?>, Type> typeEnv) {
		int count = 0;
		String var = "v" + varCounter++;
		String name = shorten(enumClazz.getName());
		indent(out);
		out.println(name + " " + var + ";");
		indent(out);
		out.println("switch(" + generatorClass + ".intValue()){");
		for (Field field : enumClazz.getDeclaredFields()) {
			if (field.isEnumConstant()) {
				indent(out);
				out.println("case " + count++ + ":");
				beginIndent();
				indent(out);
				out.println(var + " = " + name + "." + field.getName() + ";");
				indent(out);
				out.println("break;");
				endIndent();
			}
		}
		indent(out);
		out.println("default:");
		beginIndent();
		indent(out);
		out.println(var + " = null;");
		endIndent();
		indent(out);
		out.println("}");
		return var;

	}

	/**
	 * Finds the class if it exists that is the witness for a given class and
	 * gives back the code that provide that witness.
	 *
	 * @param clazz
	 *            the interface.
	 * @return a new expression if the implementor exists and null otherwise.
	 */
	private String interfaceWitness(Annotation [] annots) {
		Annotation implementorAnnot = rf.findAnnotation(
				EngineConstant.REAL_ANNOT, annots);
		if (implementorAnnot == null) {
			return "null";
		} else {
			String implemClazz = ReflexUtil.getStringValue(implementorAnnot);
			return "new " + implemClazz + "(" + generatorClass + ".token)";
		}
	}

	/**
	 * Utility method that search a string in an array of strings.
	 *
	 * @param array
	 *            the array where the search is done
	 * @param searched
	 *            the string searched.
	 * @return
	 */
	private boolean contains(String[] array, String searched) {
		if (array == null)
			return false;
		for (String id : array) {
			if (searched.equals(id))
				return true;
		}
		return false;
	}

	private void buildRecursiveEnvType(Class <?> c, Map<TypeVariable<?>, Type> typeEnv) {
		if (c == null || c.equals(Object.class)) return;
		Type superClass = c.getGenericSuperclass();
		if (superClass instanceof ParameterizedType) {
			buildEnvType(typeEnv, (ParameterizedType) superClass);
		}
		buildRecursiveEnvType(c.getSuperclass(), typeEnv);
		for(Type itfs: c.getGenericInterfaces()) {
			if (itfs instanceof ParameterizedType) {
				buildEnvType(typeEnv, (ParameterizedType) itfs);
			}
		}
		for(Class <?> itf : c.getInterfaces()) buildRecursiveEnvType(itf, typeEnv);
	}

	/**
	 * Dump the real class implementing an interface to a file to a file
	 *
	 * @param out
	 * @param c
	 */
	public void dumpRealClass(Class<?> c, String classname, String superclass)
			throws IOException {
		PrintStream out = buildOutStream(classname);
		if (out == null)
			return;

		try {
			Map<TypeVariable<?>, Type> typeEnv = new HashMap<TypeVariable<?>, Type>();
			buildRecursiveEnvType(c,typeEnv);
			setPackage(out, classname);

			indent(out);
			String shortname = classname
					.substring(classname.lastIndexOf('.') + 1);
			out.print("public /* */ class ");
			out.print(shortname);
			typeParameters(out, c.getTypeParameters());
			if (c.isInterface()) {
				if (superclass != null && !superclass.equals("") && !superclass.equals("-")) {
					out.print(" extends " + superclass);
				}
				out.print(" implements ");
				type(out,c);
			} else {

				out.print(" extends ");
				type(out,c);
			}
			Type [] args = c.getTypeParameters();
			if (args.length > 0) {
				out.print("<");
				dumpListType(out,args, false);
				out.print(">");
			}
			out.println("{");
			beginIndent();
			// Implemented fields
			dumpAddedFields(out,c);
			// Constructor
			indent(out);
			out.print("public ");
			out.print(shortname);
			out.print("(" + tokenClass + " arg0){");
			beginIndent();
			if ((superclass != null && !superclass.equals("") && !superclass.equals("-")) || !c.isInterface()) {
				indent(out);
				out.print("super(arg0);");
			}
			endIndent();
			indent(out);
			out.println("}");
			// Dump constructors as calls to super if there are super constructor (abstract class)
			for(Constructor<?> co : c.getDeclaredConstructors()) {
				int mod = co.getModifiers();
				if (!Modifier.isProtected(mod) &&  ! Modifier.isPublic(mod)) continue;
				indent(out);
				out.print("public ");
				out.print(shortname);
				out.print("(");
				Type [] params = co.getGenericParameterTypes();

				int count = 0;
				for(Type param : params) {
					if(count > 0) out.print(", ");
					type(out, param,true, typeEnv);
					out.print(" arg");
					out.print(++count);
				}

				out.print(") ");
				Type [] excs = co.getGenericExceptionTypes();
				if (excs.length > 0) {
					out.print(" throws ");
					dumpListType(out, excs, true);
				}
				out.println("{");
				beginIndent();
				indent(out);
				out.print("super(");
				for(int c1=0; c1 < params.length; c1++) {
					if(c1 > 0) out.print(", ");
					out.print(" arg");
					out.print(c1+1);
				}

				out.println(");");
				endIndent();
				indent(out);
				out.println("}");

			}
			// Get all the public methods.
			HashSet <Method> seen = new HashSet<Method>();
			for (Method meth : c.getMethods()) {
				if (Modifier.isAbstract(meth.getModifiers()) && !meth.isSynthetic() && isNewMethod(meth,seen)) {
					dumpMethod(out, meth, false, true, typeEnv);
					seen.add(meth);
				}
			}
			// Go up the hierarchy
			Class <?> parent = c;
			while(parent != null && parent != java.lang.Object.class) {
				for (Method meth : parent.getDeclaredMethods()) {
					int mod = meth.getModifiers();
					if (Modifier.isAbstract(mod)  && Modifier.isProtected(mod) && isNewMethod(meth,seen))
						dumpMethod(out, meth, false, true, typeEnv);
				}
				for(Method m: parent.getDeclaredMethods()) { seen.add(m); }
				parent = parent.getSuperclass();
			}
			endIndent();
			indent(out);
			out.println("}");

		} catch (Throwable e) {
			e.printStackTrace();
			out.println("}");
			throw new IOException(e.getMessage());
		}
		if (!debug) {
			out.close();
		}
	}

	private boolean isNewMethod(Method meth, HashSet<Method> seen) {
		String name = meth.getName();
		Class<?> [] types = meth.getParameterTypes();
		for(Method match: seen) {
			if(match.getName().equals(name) && Arrays.equals(match.getParameterTypes(), types)) return false;
		}
		return true;
	}

	@Override
	protected void dumpValueAnyClass(PrintStream out, Type typ) {
		if (typ instanceof Class <?>) {
			Class<?> clazz = (Class <?>) typ;
			if (clazz.isArray()) {
				Class<?> elt = clazz.getComponentType();
				out.print("new " + shorten(ReflexUtil.readableName(elt)) + "[]{");
				dumpDefaultValue(out,elt,null);
				out.print("}");
			} else {
				if (!Modifier.isAbstract(clazz.getModifiers()) && !clazz.isEnum() && rf.handledClass(clazz)) {
					out.print("new " + shorten(clazz.getName()) + "(" +	generatorClass + ".token)" );
				} else {
					Annotation [] annots = clazz.getAnnotations();
					Annotation realAnnot = rf.findAnnotation(EngineConstant.REAL_ANNOT, annots);
					if (realAnnot != null) {
						String name = ReflexUtil.getStringValue(realAnnot);
						out.print("new " + name + "(" +	generatorClass + ".token)" );
					} else { out.print("null"); }
				}
			}
		} else out.print("null");
	}

	@Override
	protected void dumpFieldValue(PrintStream out, Field field) {
		int mod = field.getModifiers();
		out.print(" = ");
		Annotation [] annots = field.getAnnotations();
		Annotation implemAnnot = rf.findAnnotation(EngineConstant.FIELD_VALUE_IMPL_ANNOT, annots);
		if (implemAnnot != null) {
			out.print("new ");
			out.print(ReflexUtil.getStringValue(implemAnnot));
			out.print("()");
		} else if (Modifier.isFinal(mod) && Modifier.isStatic(mod)) dumpValue(out,field);
		else dumpFieldValue(out,field, field.getType());
	}

	private void dumpFieldValue(PrintStream out, Field field, Class<?> type) {
		if (type.equals(java.lang.String.class)) {
			out.print("\"[field:");
			out.print(rf.restoreString(field.toString()));
			out.print("]\"");
		} else if (type.isArray()) {
			Class<?> elt = type.getComponentType();
			out.print("new " + shorten(ReflexUtil.readableName(elt)) + "[]{");
			dumpFieldValue(out,field,elt);
			out.print("}");
		} else 	if(type.equals(boolean.class)) out.print("false");
		else if (type.equals(byte.class)) out.print("(byte) 0");
		else if (type.equals(char.class)) out.print("'\\u0000'");
		else if (type.equals(short.class)) out.print("(short) 0");
		else if (type.equals(int.class)) out.print("0");
		else if (type.equals(long.class)) out.print("0l");
		else if (type.equals(float.class)) out.print("0.0f");
		else if (type.equals(double.class)) out.print("0.0d");
		else {
			dumpValueAnyClass(out, type);
		}
	}

	@Override
	protected void generateImports(PrintStream out, Class<?> c) { }
}


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _path = _interopRequireDefault(require("./path"));

var _attribute_value = require("../utils/attribute_value");

var _smooth_curve = require("../utils/smooth_curve");

require("gl-matrix").glMatrix.setMatrixArrayType(Array);

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2.default)(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2.default)(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2.default)(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

var setDefault = Symbol.for('spritejs_setAttributeDefault');
var setAttribute = Symbol.for('spritejs_setAttribute');
var getAttribute = Symbol.for('spritejs_getAttribute');
var declareAlias = Symbol.for('spritejs_declareAlias');

function getPath(attr) {
  var points = attr.points,
      smooth = attr.smooth,
      smoothRange = attr.smoothRange,
      close = attr.close;
  var p = [];

  for (var i = 0; i < points.length; i += 2) {
    p.push([points[i], points[i + 1]]);
  }

  var d = '';

  if (smooth) {
    // if(close) {
    //   p.push([...p[0]]);
    // }
    d = (0, _smooth_curve.makeSmoothCurveLine)(p, smoothRange);
  } else if (p.length) {
    d = "M".concat(p.map(function (v) {
      return v.join(' ');
    }).join('L'));
  }

  if (d && close) {
    d += 'Z';
  }

  return d;
}

var Polyline = /*#__PURE__*/function (_Path) {
  (0, _inherits2.default)(Polyline, _Path);

  var _super = _createSuper(Polyline);

  function Polyline(subject) {
    var _this;

    (0, _classCallCheck2.default)(this, Polyline);
    _this = _super.call(this, subject);

    _this[setDefault]({
      points: [],
      smooth: false,
      smoothRange: [0],
      closeType: 'none' // none | normal

      /* close */

    });

    _this[declareAlias]('close');

    return _this;
  } // readonly

  (0, _createClass2.default)(Polyline, [{
    key: "d",
    get: function get() {
      return this[getAttribute]('d');
    },
    set: function set(value) {} // eslint-disable-line no-empty-function

  }, {
    key: "close",
    get: function get() {
      return this.closeType !== 'none';
    },
    set: function set(value) {
      value = value ? 'normal' : 'none';
      this.closeType = value;
    }
  }, {
    key: "closeType",
    get: function get() {
      return this[getAttribute]('closeType');
    },
    set: function set(value) {
      if (value != null && value !== 'none' && value !== 'normal') throw new TypeError('Invalid closeType type.');

      if (this[setAttribute]('closeType', value)) {
        var d = getPath(this);
        this[setAttribute]('d', d);
      }
    }
  }, {
    key: "smooth",
    get: function get() {
      return this[getAttribute]('smooth');
    },
    set: function set(value) {
      if (this[setAttribute]('smooth', value)) {
        var d = getPath(this);
        this[setAttribute]('d', d);
      }
    }
  }, {
    key: "smoothRange",
    get: function get() {
      return this[getAttribute]('smoothRange');
    },
    set: function set(value) {
      if (value && !Array.isArray(value)) value = [value];

      if (this[setAttribute]('smoothRange', value)) {
        if (this.smooth) {
          var d = getPath(this);
          this[setAttribute]('d', d);
        }
      }
    }
  }, {
    key: "points",
    get: function get() {
      return this[getAttribute]('points');
    },
    set: function set(value) {
      value = (0, _attribute_value.toArray)(value);

      if (Array.isArray(value)) {
        value = value.reduce(function (a, b) {
          if (Array.isArray(b)) {
            return [].concat((0, _toConsumableArray2.default)(a), (0, _toConsumableArray2.default)(b.map(function (v) {
              return (0, _attribute_value.toNumber)(v);
            })));
          }

          return [].concat((0, _toConsumableArray2.default)(a), [(0, _attribute_value.toNumber)(b)]);
        }, []);
      }

      if (this[setAttribute]('points', value)) {
        var d = getPath(this);
        this[setAttribute]('d', d);
      }
    }
  }]);
  return Polyline;
}(_path.default);

exports.default = Polyline;

redpajama_set_name: RedPajamaGithub


text:
(function () {
    require.config({
        'paths': {
            'jquery': 'scripts/jquery.min',
            'handlebars': 'scripts/handlebars-v2.0.0',
            'controls': 'lib/controls',
            'comboBox': 'lib/comboBox'
        },
        'shim': {
            'handlebars': {
                'exports': 'Handlebars'
            }
        }
    });

    require([
        'jquery',
        'handlebars',
        'controls'],
        function ($, Handlebars, controls) {
            var people = [
                { id: 1, name: "Doncho Minkov", age: 18, avatarUrl: "images/minkov.jpg" },
                { id: 2, name: "Groznik", age: 18, avatarUrl: "images/minkov.jpg" },
                { id: 3, name: "Georgi Georgiev", age: 19, avatarUrl: "images/joreto.jpg" }];

            var controlsInstantiated = new controls();
            var comboBox = controlsInstantiated.ComboBox(people);
            var template = $('#template').html();
            comboBox.render(template);

            function displayDivs() {
                $('body div:hidden').css('display', '');
                $('body div').addClass('visible');
            }

            function hideAllExeptSelected (event) {
                $('div').css('display', 'none').removeClass('visible');
                event.target.style.display = '';
            }

            $('body div').click(function (event) {

                if (event.target.className === 'person-item') {
                    displayDivs();
                }
                else if (event.target.className === 'person-item visible') {
                    hideAllExeptSelected(event);
                }
            });
        });
}());


text:
@interface PerformanceViewController : UIViewController

@end


text:
.. _publishing:

Publishing Tales
================

When your Tale is ready to be preserved and shared, you can publish it to external repositories. When you publish your Tale, it receives a DOI that can be cited by others.

Publishers
----------

DataONE
^^^^^^^
DataONE is a network of data centers and organizations that share their information across a network of nodes, where data
is replicated and described with rich metadata. Publishing your Tale into the DataONE network will allow you to
archive your work, collect usage statistics, and make it easy to share with other scientists.

Zenodo
^^^^^^
Zenodo is a general purpose data repository that's run by CERN. Zenodo allows for Tales up to 50gb and can mint DOIs. Zenodo also
offers the ability to version data submissions, which is supported in Whole Tale's system.

Before publishing to production servers, it's recommended to first publish the Tale to a sandbox repository.

Publishing Your Tale
--------------------

To publish your Tale, select "Publish Tale" from the dropdown menu on the Run page.

     .. figure:: images/publish/start_publish.gif
          :align: center

          Publishing is accessed through the Tale Run page

Once the publishing dialog is opened, select which data repository you want to store your Tale in.

     .. figure:: images/publish/run_publish.gif
          :align: center

          Publishing to the Development node

If you haven't connected any third-party accounts the list will be empty. For instructions how to connect your account, visit
the settings page.

Viewing Publishing Information
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
After you've published your Tale, you can always view the published location under the metadata tab on the Run page.

Updating Published Tales
^^^^^^^^^^^^^^^^^^^^^^^^

In the case that the published Tale needs to be published again, with the intent of overwriting the previous publication,
it can be updated by re-publishing to the same repository. This feature is _only_ available to Tales under the user's ownership.

If a Tale was used for related, subsequent work and _shouldn't_ update the previous Tale, a new Tale should be created by
first copying the Tale. When the copied Tale is published, it will be a completely new record.

Whole Tale Generated Files
--------------------------

manifest.json
^^^^^^^^^^^^^
This is a metadata document that describes the Tale, which was inspired from the `Research Object Lite`_ specification. The
important information contained in this file includes any external data that was used, locations of data files, and author attributes.

environment.json
^^^^^^^^^^^^^^^^
The environment file contains information about the Tale's compute environment which includes memory limits and docker information.

LICENSE
^^^^^^^
The LICENSE file describes the Tale's license. To change the license, navigate to the metadata editor in the Run page.

README.md
^^^^^^^^^
The README file gives instructions for running your Tale locally without Whole Tale.

.. _Research Object Lite : https://researchobject.github.io/ro-lite/0.1.0/


text:
package org.kuali.rice.kns.datadictionary;
@Deprecated
public interface SubSectionHeaderDefinitionI {
    public String getName();
}


text:
layout: map-post
title: Wanderung durch die Soierngruppe - Tag 2
description: "Wanderung vom Soiernhaus über die Soiernspitze nach Krün"
modified: 2015-07-19
tags: [wanderung]
comments: false
share: false
gpx: true
---


text:
/** @type {LH.Config.Json} */
const config = {
  extends: 'lighthouse:default',
  plugins: ['lighthouse-plugin-publisher-ads'],
};

/**
  * @type {Smokehouse.ExpectedRunnerResult}
  */
const expectations = {
  lhr: {
    requestedUrl: 'http://localhost:10200/online-only.html',
    finalDisplayedUrl: 'http://localhost:10200/online-only.html',
    // We should receive warnings about no ads being on the page.
    runWarnings: {length: '>0'},
    audits: {
      // We just want to ensure the plugin had a chance to run without error.
      'ad-render-blocking-resources': {scoreDisplayMode: 'notApplicable'},
    },
  },
};

export default {
  id: 'pubads',
  expectations,
  config,
};


text:
SilverStripe's test system has built-in support for testing emails sent using the Email class.

## How it works

For this to work, you need to send emails using the `Email` class, which is generally the way that we recommend you
send emails in your SilverStripe application.  Here is a simple example of how you might do this:

	:::php
	$e = new Email();
	$e->To = "someone@example.com";
	$e->Subject = "Hi there";
	$e->Body = "I just really wanted to email you and say hi.";
	$e->send();

Normally, the send() method would send an email using PHP's mail() function.  However, if you are running a `[api:SapphireTest]`
test, then it holds off actually sending the email, and instead lets you assert that an email was sent using this method.

	:::php
	$this->assertEmailSent("someone@example.com", null, "/th.*e$/");

The arguments are `$to`, `$from`, `$subject`, `$body`, and can be take one of the following three forms:

*  A string: match exactly that string
*  `null/false`: match anything
*  A PERL regular expression (starting with '/'): match that regular expression

## How to use it

Given all of that, there is not a lot that you have to do in order to test emailing functionality in your application.

*  Write your SilverStripe application, using the Email class to send emails.
*  Write tests that trigger the email sending functionality.
*  Include appropriate `$this->assertEmailSent()` calls in those tests.

That's it!

## What isn't tested

It's important to realise that this email testing doesn't actually test everything that there is to do with email.  The
focus of this email testing system is testing that your application is triggering emails correctly.  It doesn't test
your email infrastructure outside of the webserver.  For example:

*  It won't test that email is correctly configured on your webserver
*  It won't test whether your emails are going to be lost in someone's spam filter
*  It won't test bounce-handling or any other auxiliary services of email

## How it's built

For those of you who want to dig a little deeper, here's a quick run-through of how the system has been built.  As well
as explaining how we built the email test, this is a good design pattern for making other "tricky external systems"
testable:

1.  The `Email::send()` method makes uses of a static object, `Email::$mailer`, to do the dirty work of calling
mail().  The default mailer is an object of type `Mailer`, which performs a normal send.
2.  `Email::set_mailer()` can be called to load in a new mailer object.
3.  `SapphireTest::setUp()` method calls `Email::set_mailer(new TestMailer())` to replace the default mailer with a `TestMailer` object.  This replacement mailer doesn't actually do anything when it is asked to send an email; it just
records the details of the email in an internal field that can be searched with `TestMailer::findEmails()`.
4.  `SapphireTest::assertEmailSent()` calls `TestMailer::findEmails()` to see if a mail-send was requested by the
application.


text:
-- Flags
local premiumAccount = {type = CONTROLLER_TYPE.SWITCH, title = "Do you have a Premium Account?", key = "premium", value = 1}
local clickFairies = {type = CONTROLLER_TYPE.SWITCH, title = "Tap Fairies?", key = "fairies", value = 1}
local clickFlashZip = {type = CONTROLLER_TYPE.SWITCH, title = "Chase Flash Zip?", key = "flashzip", value = 1}
local clanQuestRounds = {type = CONTROLLER_TYPE.INPUT, title = "Number of CQ/Titan", key = "cqrounds", value = "1"}
local tapAttack = {type = CONTROLLER_TYPE.SWITCH, title = "Attack with Sword Master?", key = "attack", value = 1}
local prestigeTimer = {type = CONTROLLER_TYPE.INPUT, title = "Prestige Timer (in minutes)", key = "pTimer", value = "60"}
local primaryHero = {type = CONTROLLER_TYPE.PICKER, title = "Primary Hero", key = "hero", value = "Finn", options = {"Damon", "Finn", "Nohni"}}

local controls = {premiumAccount, clickFairies, clickFlashZip, tapAttack, clanQuestRounds, prestigeTimer, primaryHero}
local enableRemember = true

dialog(controls, enableRemember)

require "TT2.tt2config"
require "TT2.tt2utils"

if not fileExists("prestige") then writeTime("prestige") end
prestigeTime = readTime("prestige")

while appState("com.gamehivecorp.taptitans2") == "ACTIVATED" do

    while hasPixel(Stage.main) do

        -- Prestige Routine
        if checkForPrestige(prestigeTimer.value) then
            prestige()
            levelSwordMaster()
            learnSkills(1)
            hireHeroes()
            prestigeTime = readTime("prestige")
        end

        -- Clan Quest Routine
        if tonumber(clanQuestRounds.value) > 0 then fightClanQuest(clanQuestRounds.value) end

        -- Collection Routine
        checkForGold()
        checkForNewPet()
        checkForDaily()

        -- Find and Click
        if clickFairies.value == 1 then chaseFairies() end
        if clickFlashZip.value == 1 then chaseFlashZip() end
        if mainStageBossAvailable() then tapButton(Menu.fightBoss) end
        -- Use Skills
        useSkill()
        -- Level  Hereos
        if checkCounter then levelHeroes(primaryHero.value) end
        -- Attack with Sword Master
        if tapAttack.value == 1 then
            ttap(0, 110, 680);
            ttap(1, 220, 680);
            ttap(2, 330, 620);
            ttap(1, 380, 290);
            ttap(0, 400, 620);
            ttap(1, 550, 400);
            ttap(2, 680, 660);
        end
    end

    while not hasPixel(Stage.main) do
        checkCounter = true
        -- Fairy Ad
        if premiumAccount.value == 1 and hasPixel(Stage.fairyAd) then
            ttap(1, 566, 1040)
        elseif hasPixel(Stage.fairyAd) then
            tap(1, 200, 1040);
            usleep(Delay.menu);
        end

        -- Item Splash, Egg Splash, or Pet Splash
        if hasPixel(Stage.splash) then
            usleep(Delay.animation)
            ttap(1, 357, 350)
            usleep(Delay.menu)
        end

        if hasPixel(Stage.splashDark) then
            usleep(Delay.animation)
            ttap(1, 357, 350)
            usleep(Delay.menu)
        end

        -- Transition
        if hasPixel(Stage.transition) then
            usleep(2e6)
        end
    end
end


text:
namespace Cassandra
{
    internal class OutputProtocolError : OutputError
    {
        public override DriverException CreateException()
        {
            return new ProtocolErrorException(Message);
        }

        protected override void Load(FrameReader reader)
        {
        }
    }
}


text:
<?php

namespace Oro\Bundle\IntegrationBundle\Tests\Unit\Manager;

use Doctrine\ORM\EntityManager;
use Doctrine\Common\Persistence\ManagerRegistry;

use Oro\Bundle\IntegrationBundle\Entity\Channel as Integration;
use Oro\Bundle\IntegrationBundle\Manager\SyncScheduler;
use Oro\Bundle\IntegrationBundle\Manager\TypesRegistry;
use Oro\Bundle\IntegrationBundle\Tests\Unit\Fixture\TestIntegrationType;
use Oro\Bundle\IntegrationBundle\Tests\Unit\Fixture\TestConnector;

class SyncSchedulerTest extends \PHPUnit_Framework_TestCase
{
    /** @var EntityManager|\PHPUnit_Framework_MockObject_MockObject */
    protected $em;

    /** @var ManagerRegistry|\PHPUnit_Framework_MockObject_MockObject */
    protected $registry;

    /** @var TypesRegistry */
    protected $typesRegistry;

    /** @var SyncScheduler */
    protected $scheduler;

    public function setUp()
    {
        $this->em       = $this->getMockBuilder('Doctrine\ORM\EntityManager')
            ->disableOriginalConstructor()->getMock();
        $this->registry = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry');

        $this->typesRegistry = new TypesRegistry();
        $this->scheduler     = new SyncScheduler($this->registry, $this->typesRegistry);
    }

    public function tearDown()
    {
        unset($this->em, $this->registry, $this->typesRegistry, $this->scheduler);
    }

    /**
     * @expectedException \LogicException
     * @expectedExceptionMessage Connectors not found for integration "testType"
     */
    public function testScheduleRegistryError()
    {
        $integration = new Integration();
        $integration->setType('testType');
        $integration->setEnabled(true);

        $this->scheduler->schedule($integration, '');
    }

    /**
     * @expectedException \LogicException
     * @expectedExceptionMessage Unable to schedule job for "testConnectorType" connector type
     */
    public function testScheduleConnectorError()
    {
        $testIntegrationType = 'testIntegrationType';
        $testConnectorType   = 'testConnectorType';

        $integration = new Integration();
        $integration->setType($testIntegrationType);
        $this->typesRegistry->addChannelType($testIntegrationType, new TestIntegrationType());
        $this->typesRegistry->addConnectorType($testConnectorType, $testIntegrationType, new TestConnector());
        $integration->setEnabled(true);

        $this->scheduler->schedule($integration, $testConnectorType);
    }
}


text:
class ErrorObject
{
	private:

	public:
		char szWSAErrorMessage[128];

		void vGetWSAErrorMessage(int err);
};


text:
namespace optimization_guide {

class IOSChromeHintsManager : public HintsManager {
 public:
  IOSChromeHintsManager(
      bool off_the_record,
      const std::string& application_locale,
      PrefService* pref_service,
      base::WeakPtr<optimization_guide::OptimizationGuideStore> hint_store,
      optimization_guide::TopHostProvider* top_host_provider,
      optimization_guide::TabUrlProvider* tab_url_provider,
      scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
      OptimizationGuideLogger* optimization_guide_logger);

  ~IOSChromeHintsManager() override = default;

  IOSChromeHintsManager(const IOSChromeHintsManager&) = delete;
  IOSChromeHintsManager& operator=(const IOSChromeHintsManager&) = delete;
};

}  // namespace optimization_guide

#endif  // IOS_CHROME_BROWSER_OPTIMIZATION_GUIDE_IOS_CHROME_HINTS_MANAGER_H_


text:
package com.ifeng.octopus.bpm2.web.async;

import java.util.concurrent.Callable;

import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter;

/**
 * @version 0.1
 *
 * @author Hefei Li
 *
 * @since Sep 11, 2014
 */
public class TimeoutCallableProcessingInterceptor extends CallableProcessingInterceptorAdapter {

	@Override
	public <T> Object handleTimeout(NativeWebRequest request, Callable<T> task) throws Exception {
		throw new IllegalStateException("[" + task.getClass().getName() + "] timed out");
	}

}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
N. Amer. Fl. (New York) 10(2): (1917)

#### Original name
Agaricus teneroides Peck, 1878

### Remarks
null


text:
package org.apache.stratos.common.internal;

import com.hazelcast.core.HazelcastInstance;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.stratos.common.services.DistributedObjectProvider;
import org.wso2.carbon.caching.impl.DistributedMapProvider;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.service.RealmService;

/**
 * Stratos common service reference holder.
 */
public class ServiceReferenceHolder {

    private static final Log log = LogFactory.getLog(ServiceReferenceHolder.class);

    private static volatile ServiceReferenceHolder instance;
    private HazelcastInstance hazelcastInstance;
    private DistributedMapProvider distributedMapProvider;
    private RealmService realmService;
    private RegistryService registryService;
    private AxisConfiguration axisConfiguration;
    private DistributedObjectProvider distributedObjectProvider;

    private ServiceReferenceHolder() {
    }

    public static ServiceReferenceHolder getInstance() {
        if (instance == null) {
            synchronized (ServiceReferenceHolder.class) {
                if (instance == null) {
                    instance = new ServiceReferenceHolder();
                }
            }
        }
        return instance;
    }

    public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
        this.hazelcastInstance = hazelcastInstance;
    }

    public HazelcastInstance getHazelcastInstance() {
        return hazelcastInstance;
    }

    public void setDistributedMapProvider(DistributedMapProvider distributedMapProvider) {
        this.distributedMapProvider = distributedMapProvider;
    }

    public DistributedMapProvider getDistributedMapProvider() {
        return distributedMapProvider;
    }

    public void setRealmService(RealmService realmService) {
        this.realmService = realmService;
    }

    public RealmService getRealmService() {
        return realmService;
    }

    public void setRegistryService(RegistryService registryService) {
        this.registryService = registryService;
    }

    public RegistryService getRegistryService() {
        return registryService;
    }

    public void setAxisConfiguration(AxisConfiguration axisConfiguration) {
        this.axisConfiguration = axisConfiguration;
    }

    public AxisConfiguration getAxisConfiguration() {
        return axisConfiguration;
    }

    public void setDistributedObjectProvider(DistributedObjectProvider distributedObjectProvider) {
        this.distributedObjectProvider = distributedObjectProvider;
    }

    public DistributedObjectProvider getDistributedObjectProvider() {
        return distributedObjectProvider;
    }
}


text:
[browser-workshopper](https://github.com/lakenen/browser-workshopper)

## License

([The MIT License](LICENSE))

Copyright 2014 Cameron Lakenen


text:
module ThinkingSphinx
  class Facet
    attr_reader :property

    def initialize(property)
      @property = property

      if property.columns.length != 1
        raise "Can't translate Facets on multiple-column field or attribute"
      end
    end

    def self.name_for(facet)
      case facet
      when Facet
        facet.name
      when String, Symbol
        facet.to_s.gsub(/(_facet|_crc)$/,'').to_sym
      end
    end

    def self.attribute_name_for(name)
      name.to_s == 'class' ? 'class_crc' : "#{name}_facet"
    end

    def self.attribute_name_from_value(name, value)
      case value
      when String
        attribute_name_for(name)
      when Array
        if value.all? { |val| val.is_a?(Integer) }
          name
        else
          attribute_name_for(name)
        end
      else
        name
      end
    end

    def self.translate?(property)
      return true if property.is_a?(Field)

      case property.type
      when :string
        true
      when :integer, :boolean, :datetime, :float
        false
      when :multi
        !property.all_ints?
      end
    end

    def name
      property.unique_name
    end

    def attribute_name
      if translate?
        Facet.attribute_name_for(@property.unique_name)
      else
        @property.unique_name.to_s
      end
    end

    def translate?
      Facet.translate?(@property)
    end

    def type
      @property.is_a?(Field) ? :string : @property.type
    end

    def value(object, attribute_value)
      return translate(object, attribute_value) if translate?

      case @property.type
      when :datetime
        Time.at(attribute_value)
      when :boolean
        attribute_value > 0
      else
        attribute_value
      end
    end

    def to_s
      name
    end

    private

    def translate(object, attribute_value)
      column.__stack.each { |method|
        return nil unless object = object.send(method)
      }
      if object.is_a?(Array)
        object.collect { |item| item.send(column.__name) }
      else
        object.send(column.__name)
      end
    end

    def column
      @property.columns.first
    end
  end
end


text:
require 'spec_helper'

describe NbaStats::Player, :vcr do

  describe 'Class Methods' do
    describe '.all' do
      it 'parses the api response from JSON to Array' do
        all_players = described_class.all
        expect(all_players).to be_an Array
      end
    end
  end

  describe 'Instance Methods' do
    subject(:player) { described_class.new(id: 1717) }

    describe '#attributes' do
      subject {player.attributes}

      it 'not nil' do
        expect(subject).not_to be nil
      end

      it 'returns a Hash' do
        expect(subject).to be_an_instance_of(Hash)
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FTrend.FXModel
{
    public class Converter
    {
        public static List<Day> nativeTimeToDayWithMovingAvg(List<NativeTime> nativeTime)
        {
            List<Day> days = getDays(nativeTime);
            days = calcMovingAvg(days, Config.movingAvgSize);

            return days;
        }

        public static List<Day> nativeTimeToDay(List<NativeTime> nativeTime)
        {
            return getDays(nativeTime);
        }

        public static List<Day> normalize(List<Day> days)
        {
            double max = days.Max(x => x.movingAvg);
            foreach (var day in days)
            {
                day.movingAvg = day.movingAvg / max;
            }
            return days;
        }

        public static List<Day> calcMovingAvg(List<Day> days, int numOfDays)
        {
            for (int i = numOfDays - 1; i < days.Count; i++)
            {
                double daysSum = 0;
                for (int j = i - (numOfDays - 1); j <= i; j++)
                {
                    daysSum += days[j].avg;
                }
                days[i].movingAvg = daysSum / numOfDays;
            }
            return days;
        }

        static List<Day> getDays(List<NativeTime> nativeTimes)
        {
            List<Day> days = new List<Day>();
            DateTime dayDate = new DateTime(nativeTimes[0].date.Year, nativeTimes[0].date.Month, nativeTimes[0].date.Day);
            double dayAvg = 0;
            double daySum = 0;
            double minuteCount = 0;

            foreach (var min in nativeTimes)
            {
                if (dayDate.Day != min.date.Day)
                {
                    dayAvg = daySum / minuteCount;
                    days.Add(new Day(dayDate, dayAvg, 0));
                    dayDate = new DateTime(min.date.Year, min.date.Month, min.date.Day);
                    dayAvg = 0;
                    daySum = 0;
                    minuteCount = 0;
                }
                daySum += (min.open + min.close + min.high + min.low) / 4;
                minuteCount++;
            }
            dayAvg = daySum / minuteCount;
            days.Add(new Day(dayDate, dayAvg, 0));

            return days;
        }
    }
}


text:
package org.apache.hive.hcatalog.api.repl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;

import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertNull;

/**
 * Class which provides several useful methods to test commands, but is itself not a test.
 */
public class CommandTestUtils {

  private static Logger LOG = LoggerFactory.getLogger(CommandTestUtils.class.getName());

  public static void compareCommands(Command expected, Command actual, boolean ignoreSortOrder) {
    // The reason we use compare-command, rather than simply getting the serialized output and comparing
    // for partition-based commands is that the partition specification order can be different in different
    // serializations, but still be effectively the same. (a="42",b="abc") should be the same as (b="abc",a="42")
    assertEquals(expected.getClass(),actual.getClass());
    assertEquals(expected.getEventId(),actual.getEventId());
    assertEquals(expected.isUndoable(),actual.isUndoable());
    assertEquals(expected.isRetriable(),actual.isRetriable());

    assertEquals(expected.get().size(),actual.get().size());
    Iterator<String> actualIter = actual.get().iterator();
    for (String s : expected.get()){
      if (ignoreSortOrder){
        // compare sorted strings, rather than comparing exact strings.
        assertSortedEquals(s, actualIter.next());
      } else {
        assertEquals(s,actualIter.next());
      }
    }

    if (expected.isUndoable()){
      Iterator<String> actualUndoIter = actual.getUndo().iterator();
      for (String s: expected.getUndo()){
        if (ignoreSortOrder){
          assertSortedEquals(s,actualUndoIter.next());
        } else {
          assertEquals(s,actualIter.next());
        }
      }
    }
  }

  private static void assertSortedEquals(String expected, String actual) {
    char[] expectedChars = expected.toCharArray();
    Arrays.sort(expectedChars);
    char[] actualChars = actual.toCharArray();
    Arrays.sort(actualChars);
    assertEquals(String.valueOf(expectedChars), String.valueOf(actualChars));
  }

  public static void testCommandSerialization(Command cmd) {
    String serializedCmd = null;
    try {
      serializedCmd = ReplicationUtils.serializeCommand(cmd);
    } catch (IOException e) {
      LOG.error("Serialization error",e);
      assertNull(e); // error out.
    }

    Command cmd2 = null;
    try {
      cmd2 = ReplicationUtils.deserializeCommand(serializedCmd);
    } catch (IOException e) {
      LOG.error("Serialization error",e);
      assertNull(e); // error out.
    }

    assertEquals(cmd.getClass(),cmd2.getClass());
    assertEquals(cmd.getEventId(), cmd2.getEventId());
    assertEquals(cmd.get(), cmd2.get());
    assertEquals(cmd.isUndoable(),cmd2.isUndoable());
    if (cmd.isUndoable()){
      assertEquals(cmd.getUndo(),cmd2.getUndo());
    }
    assertEquals(cmd.isRetriable(),cmd2.isRetriable());
  }

}


text:
package net.neevek.android.lib.paginize.exception;

/**
 * Thrown when annotated class does not implemented required interfaces
 *
 * @see net.neevek.android.lib.paginize.util.AnnotationUtils
 */
public class NotImplementedInterfaceException extends RuntimeException {
  public NotImplementedInterfaceException(String msg) {
    super(msg);
  }
}


text:
<?php
class ApplicationControllerGenerator extends CodeGenerator {
	protected $template = '<?php
class ApplicationController extends Controller {

	public function __construct() {
		parent::__construct();
		$this->layout = \'default\';
	}
}

';

	public function __construct() {
		parent::__construct('application');
		$this->path = Config::get('ctrl_dir');
	}

	public function generate() {
		if (!$this->validation()) {
			return;
		}
		$this->generate_path();
		$this->generate_file();

		// make helper
		$generator = new HelperGenerator($this->name);
		$generator->generate();
	}

	public function get_filename() {
		return camel_to_under($this->name) . '_controller.class.php';
	}
}


text:
namespace FCP.Web.Host
{
    public static class FCPWebHostConstants
    {
        /// <summary>
        /// Api状态检测 路由Url
        /// </summary>
        public const string ApiStatusRouteUrl = "api/status";
    }
}


text:
package server

import (
	"google.golang.org/grpc"
	sdkgrpc "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/assuredworkloads/beta/assuredworkloads_beta_go_proto"
)

// RegisterServers registers each resource with the gRPC server.
func RegisterServers(s *grpc.Server) {
	sdkgrpc.RegisterAssuredworkloadsBetaWorkloadServiceServer(s, &WorkloadServer{})
}


text:
function Get-vRAAPIVersion {
<#
    .SYNOPSIS
    Retrieve vRA API version information

    .DESCRIPTION
    Retrieve vRA API version information

    .OUTPUTS
    System.Management.Automation.PSObject.

    .EXAMPLE
    Get-vRAAPIVersion

#>
[CmdletBinding()][OutputType('System.Management.Automation.PSObject')]

    Param ()

    try {

        $URI = "/iaas/api/about"
        $Response = Invoke-vRARestMethod -URI $URI -Method GET

        [pscustomobject] @{

            APIVersion = $Response.latestApiVersion
            SupportedAPIs = $Response.supportedApis.apiversion
        }
    }
    catch [Exception]{

        throw
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<testng-results skipped="0" failed="0" total="4" passed="4">
  <reporter-output>
  </reporter-output>
  <suite name="Default suite" duration-ms="17060" started-at="2014-03-04T23:25:57Z" finished-at="2014-03-04T23:26:14Z">
    <groups>
    </groups>
    <test name="Default test" duration-ms="17060" started-at="2014-03-04T23:25:57Z" finished-at="2014-03-04T23:26:14Z">
      <class name="com.example.tests.GroupCreationTests">
        <test-method status="PASS" signature="testEmptyGroupCreation()[pri:0, instance:com.example.tests.GroupCreationTests@80f252]" name="testEmptyGroupCreation" duration-ms="1227" started-at="2014-03-05T01:26:10Z" finished-at="2014-03-05T01:26:12Z">
          <reporter-output>
          </reporter-output>
        </test-method> <!-- testEmptyGroupCreation -->
        <test-method status="PASS" signature="testNonEmptyGroupCreation()[pri:0, instance:com.example.tests.GroupCreationTests@80f252]" name="testNonEmptyGroupCreation" duration-ms="2245" started-at="2014-03-05T01:26:12Z" finished-at="2014-03-05T01:26:14Z">
          <reporter-output>
          </reporter-output>
        </test-method> <!-- testNonEmptyGroupCreation -->
      </class> <!-- com.example.tests.GroupCreationTests -->
      <class name="com.example.tests.ContactCreationTests">
        <test-method status="PASS" signature="setUp()[pri:0, instance:com.example.tests.ContactCreationTests@780024]" name="setUp" is-config="true" duration-ms="7151" started-at="2014-03-05T01:25:57Z" finished-at="2014-03-05T01:26:04Z">
          <reporter-output>
          </reporter-output>
        </test-method> <!-- setUp -->
        <test-method status="PASS" signature="testEmptyContactCreation()[pri:0, instance:com.example.tests.ContactCreationTests@780024]" name="testEmptyContactCreation" duration-ms="3455" started-at="2014-03-05T01:26:04Z" finished-at="2014-03-05T01:26:08Z">
          <reporter-output>
          </reporter-output>
        </test-method> <!-- testEmptyContactCreation -->
        <test-method status="PASS" signature="testNonEmptyContactCreation()[pri:0, instance:com.example.tests.ContactCreationTests@780024]" name="testNonEmptyContactCreation" duration-ms="2860" started-at="2014-03-05T01:26:08Z" finished-at="2014-03-05T01:26:10Z">
          <reporter-output>
          </reporter-output>
        </test-method> <!-- testNonEmptyContactCreation -->
        <test-method status="PASS" signature="tearDown()[pri:0, instance:com.example.tests.ContactCreationTests@780024]" name="tearDown" is-config="true" duration-ms="106" started-at="2014-03-05T01:26:14Z" finished-at="2014-03-05T01:26:14Z">
          <reporter-output>
          </reporter-output>
        </test-method> <!-- tearDown -->
      </class> <!-- com.example.tests.ContactCreationTests -->
    </test> <!-- Default test -->
  </suite> <!-- Default suite -->
</testng-results>


text:
<?php
include('login.php'); // Includes Login Script

if(isset($_SESSION['login_user'])){
header("location: profile.php");
}
?>
<!DOCTYPE html>

<title>Login Form in PHP with Session</title>
<link href="css/style.css" rel="stylesheet" type="text/css">

PHP Login Session Example

Login Form

<form action="" method="post">
UserName :
<input id="name" name="username" placeholder="username" type="text">
Password :
<input id="password" name="password" placeholder="**********" type="password">
<input name="submit" type="submit" value=" Login ">
<?php echo $error; ?>
</form>


text:
#include <drm/drmP.h>
#include "i915_drv.h"
#include "intel_drv.h"
#include <drm/drm_atomic_helper.h>
#include <drm/drm_crtc_helper.h>
#include <drm/drm_edid.h>

static bool intel_dp_mst_compute_config(struct intel_encoder *encoder,
					struct intel_crtc_state *pipe_config)
{
	struct intel_dp_mst_encoder *intel_mst = enc_to_mst(&encoder->base);
	struct intel_digital_port *intel_dig_port = intel_mst->primary;
	struct intel_dp *intel_dp = &intel_dig_port->dp;
	struct drm_atomic_state *state;
	int bpp, i;
	int lane_count, slots;
	const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
	struct drm_connector *drm_connector;
	struct intel_connector *connector, *found = NULL;
	struct drm_connector_state *connector_state;
	int mst_pbn;

	pipe_config->dp_encoder_is_mst = true;
	pipe_config->has_pch_encoder = false;
	pipe_config->has_dp_encoder = true;
	bpp = 24;
	/*
	 * for MST we always configure max link bw - the spec doesn't
	 * seem to suggest we should do otherwise.
	 */
	lane_count = drm_dp_max_lane_count(intel_dp->dpcd);

	pipe_config->lane_count = lane_count;

	pipe_config->pipe_bpp = 24;
	pipe_config->port_clock = intel_dp_max_link_rate(intel_dp);

	state = pipe_config->base.state;

	for_each_connector_in_state(state, drm_connector, connector_state, i) {
		connector = to_intel_connector(drm_connector);

		if (connector_state->best_encoder == &encoder->base) {
			found = connector;
			break;
		}
	}

	if (!found) {
		DRM_ERROR("can't find connector\n");
		return false;
	}

	mst_pbn = drm_dp_calc_pbn_mode(adjusted_mode->crtc_clock, bpp);

	pipe_config->pbn = mst_pbn;
	slots = drm_dp_find_vcpi_slots(&intel_dp->mst_mgr, mst_pbn);

	intel_link_compute_m_n(bpp, lane_count,
			       adjusted_mode->crtc_clock,
			       pipe_config->port_clock,
			       &pipe_config->dp_m_n);

	pipe_config->dp_m_n.tu = slots;

	return true;

}

static void intel_mst_disable_dp(struct intel_encoder *encoder)
{
	struct intel_dp_mst_encoder *intel_mst = enc_to_mst(&encoder->base);
	struct intel_digital_port *intel_dig_port = intel_mst->primary;
	struct intel_dp *intel_dp = &intel_dig_port->dp;
	int ret;

	DRM_DEBUG_KMS("%d\n", intel_dp->active_mst_links);

	drm_dp_mst_reset_vcpi_slots(&intel_dp->mst_mgr, intel_mst->connector->port);

	ret = drm_dp_update_payload_part1(&intel_dp->mst_mgr);
	if (ret) {
		DRM_ERROR("failed to update payload %d\n", ret);
	}
}

static void intel_mst_post_disable_dp(struct intel_encoder *encoder)
{
	struct intel_dp_mst_encoder *intel_mst = enc_to_mst(&encoder->base);
	struct intel_digital_port *intel_dig_port = intel_mst->primary;
	struct intel_dp *intel_dp = &intel_dig_port->dp;

	DRM_DEBUG_KMS("%d\n", intel_dp->active_mst_links);

	/* this can fail */
	drm_dp_check_act_status(&intel_dp->mst_mgr);
	/* and this can also fail */
	drm_dp_update_payload_part2(&intel_dp->mst_mgr);

	drm_dp_mst_deallocate_vcpi(&intel_dp->mst_mgr, intel_mst->connector->port);

	intel_dp->active_mst_links--;

	intel_mst->connector = NULL;
	if (intel_dp->active_mst_links == 0) {
		intel_dig_port->base.post_disable(&intel_dig_port->base);
		intel_dp_sink_dpms(intel_dp, DRM_MODE_DPMS_OFF);
	}
}

static void intel_mst_pre_enable_dp(struct intel_encoder *encoder)
{
	struct intel_dp_mst_encoder *intel_mst = enc_to_mst(&encoder->base);
	struct intel_digital_port *intel_dig_port = intel_mst->primary;
	struct intel_dp *intel_dp = &intel_dig_port->dp;
	struct drm_device *dev = encoder->base.dev;
	struct drm_i915_private *dev_priv = dev->dev_private;
	enum port port = intel_dig_port->port;
	int ret;
	uint32_t temp;
	struct intel_connector *found = NULL, *connector;
	int slots;
	struct drm_crtc *crtc = encoder->base.crtc;
	struct intel_crtc *intel_crtc = to_intel_crtc(crtc);

	for_each_intel_connector(dev, connector) {
		if (connector->base.state->best_encoder == &encoder->base) {
			found = connector;
			break;
		}
	}

	if (!found) {
		DRM_ERROR("can't find connector\n");
		return;
	}

	/* MST encoders are bound to a crtc, not to a connector,
	 * force the mapping here for get_hw_state.
	 */
	found->encoder = encoder;

	DRM_DEBUG_KMS("%d\n", intel_dp->active_mst_links);

	intel_mst->connector = found;

	if (intel_dp->active_mst_links == 0) {
		intel_prepare_ddi_buffer(&intel_dig_port->base);

		intel_ddi_clk_select(&intel_dig_port->base, intel_crtc->config);

		intel_dp_set_link_params(intel_dp, intel_crtc->config);

		intel_ddi_init_dp_buf_reg(&intel_dig_port->base);

		intel_dp_sink_dpms(intel_dp, DRM_MODE_DPMS_ON);

		intel_dp_start_link_train(intel_dp);
		intel_dp_stop_link_train(intel_dp);
	}

	ret = drm_dp_mst_allocate_vcpi(&intel_dp->mst_mgr,
				       intel_mst->connector->port,
				       intel_crtc->config->pbn, &slots);
	if (ret == false) {
		DRM_ERROR("failed to allocate vcpi\n");
		return;
	}

	intel_dp->active_mst_links++;
	temp = I915_READ(DP_TP_STATUS(port));
	I915_WRITE(DP_TP_STATUS(port), temp);

	ret = drm_dp_update_payload_part1(&intel_dp->mst_mgr);
}

static void intel_mst_enable_dp(struct intel_encoder *encoder)
{
	struct intel_dp_mst_encoder *intel_mst = enc_to_mst(&encoder->base);
	struct intel_digital_port *intel_dig_port = intel_mst->primary;
	struct intel_dp *intel_dp = &intel_dig_port->dp;
	struct drm_device *dev = intel_dig_port->base.base.dev;
	struct drm_i915_private *dev_priv = dev->dev_private;
	enum port port = intel_dig_port->port;
	int ret;

	DRM_DEBUG_KMS("%d\n", intel_dp->active_mst_links);

	if (wait_for((I915_READ(DP_TP_STATUS(port)) & DP_TP_STATUS_ACT_SENT),
		     1))
		DRM_ERROR("Timed out waiting for ACT sent\n");

	ret = drm_dp_check_act_status(&intel_dp->mst_mgr);

	ret = drm_dp_update_payload_part2(&intel_dp->mst_mgr);
}

static bool intel_dp_mst_enc_get_hw_state(struct intel_encoder *encoder,
				      enum pipe *pipe)
{
	struct intel_dp_mst_encoder *intel_mst = enc_to_mst(&encoder->base);
	*pipe = intel_mst->pipe;
	if (intel_mst->connector)
		return true;
	return false;
}

static void intel_dp_mst_enc_get_config(struct intel_encoder *encoder,
					struct intel_crtc_state *pipe_config)
{
	struct intel_dp_mst_encoder *intel_mst = enc_to_mst(&encoder->base);
	struct intel_digital_port *intel_dig_port = intel_mst->primary;
	struct intel_crtc *crtc = to_intel_crtc(encoder->base.crtc);
	struct drm_device *dev = encoder->base.dev;
	struct drm_i915_private *dev_priv = dev->dev_private;
	enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
	u32 temp, flags = 0;

	pipe_config->has_dp_encoder = true;

	temp = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
	if (temp & TRANS_DDI_PHSYNC)
		flags |= DRM_MODE_FLAG_PHSYNC;
	else
		flags |= DRM_MODE_FLAG_NHSYNC;
	if (temp & TRANS_DDI_PVSYNC)
		flags |= DRM_MODE_FLAG_PVSYNC;
	else
		flags |= DRM_MODE_FLAG_NVSYNC;

	switch (temp & TRANS_DDI_BPC_MASK) {
	case TRANS_DDI_BPC_6:
		pipe_config->pipe_bpp = 18;
		break;
	case TRANS_DDI_BPC_8:
		pipe_config->pipe_bpp = 24;
		break;
	case TRANS_DDI_BPC_10:
		pipe_config->pipe_bpp = 30;
		break;
	case TRANS_DDI_BPC_12:
		pipe_config->pipe_bpp = 36;
		break;
	default:
		break;
	}
	pipe_config->base.adjusted_mode.flags |= flags;

	pipe_config->lane_count =
		((temp & DDI_PORT_WIDTH_MASK) >> DDI_PORT_WIDTH_SHIFT) + 1;

	intel_dp_get_m_n(crtc, pipe_config);

	intel_ddi_clock_get(&intel_dig_port->base, pipe_config);
}

static int intel_dp_mst_get_ddc_modes(struct drm_connector *connector)
{
	struct intel_connector *intel_connector = to_intel_connector(connector);
	struct intel_dp *intel_dp = intel_connector->mst_port;
	struct edid *edid;
	int ret;

	if (!intel_dp) {
		return intel_connector_update_modes(connector, NULL);
	}

	edid = drm_dp_mst_get_edid(connector, &intel_dp->mst_mgr, intel_connector->port);
	ret = intel_connector_update_modes(connector, edid);
	kfree(edid);

	return ret;
}

static enum drm_connector_status
intel_dp_mst_detect(struct drm_connector *connector, bool force)
{
	struct intel_connector *intel_connector = to_intel_connector(connector);
	struct intel_dp *intel_dp = intel_connector->mst_port;

	if (!intel_dp)
		return connector_status_disconnected;
	return drm_dp_mst_detect_port(connector, &intel_dp->mst_mgr, intel_connector->port);
}

static int
intel_dp_mst_set_property(struct drm_connector *connector,
			  struct drm_property *property,
			  uint64_t val)
{
	return 0;
}

static void
intel_dp_mst_connector_destroy(struct drm_connector *connector)
{
	struct intel_connector *intel_connector = to_intel_connector(connector);

	if (!IS_ERR_OR_NULL(intel_connector->edid))
		kfree(intel_connector->edid);

	drm_connector_cleanup(connector);
	kfree(connector);
}

static const struct drm_connector_funcs intel_dp_mst_connector_funcs = {
	.dpms = drm_atomic_helper_connector_dpms,
	.detect = intel_dp_mst_detect,
	.fill_modes = drm_helper_probe_single_connector_modes,
	.set_property = intel_dp_mst_set_property,
	.atomic_get_property = intel_connector_atomic_get_property,
	.destroy = intel_dp_mst_connector_destroy,
	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
	.atomic_duplicate_state = drm_atomic_helper_connector_duplicate_state,
};

static int intel_dp_mst_get_modes(struct drm_connector *connector)
{
	return intel_dp_mst_get_ddc_modes(connector);
}

static enum drm_mode_status
intel_dp_mst_mode_valid(struct drm_connector *connector,
			struct drm_display_mode *mode)
{
	int max_dotclk = to_i915(connector->dev)->max_dotclk_freq;

	/* TODO - validate mode against available PBN for link */
	if (mode->clock < 10000)
		return MODE_CLOCK_LOW;

	if (mode->flags & DRM_MODE_FLAG_DBLCLK)
		return MODE_H_ILLEGAL;

	if (mode->clock > max_dotclk)
		return MODE_CLOCK_HIGH;

	return MODE_OK;
}

static struct drm_encoder *intel_mst_atomic_best_encoder(struct drm_connector *connector,
							 struct drm_connector_state *state)
{
	struct intel_connector *intel_connector = to_intel_connector(connector);
	struct intel_dp *intel_dp = intel_connector->mst_port;
	struct intel_crtc *crtc = to_intel_crtc(state->crtc);

	if (!intel_dp)
		return NULL;
	return &intel_dp->mst_encoders[crtc->pipe]->base.base;
}

static struct drm_encoder *intel_mst_best_encoder(struct drm_connector *connector)
{
	struct intel_connector *intel_connector = to_intel_connector(connector);
	struct intel_dp *intel_dp = intel_connector->mst_port;
	if (!intel_dp)
		return NULL;
	return &intel_dp->mst_encoders[0]->base.base;
}

static const struct drm_connector_helper_funcs intel_dp_mst_connector_helper_funcs = {
	.get_modes = intel_dp_mst_get_modes,
	.mode_valid = intel_dp_mst_mode_valid,
	.atomic_best_encoder = intel_mst_atomic_best_encoder,
	.best_encoder = intel_mst_best_encoder,
};

static void intel_dp_mst_encoder_destroy(struct drm_encoder *encoder)
{
	struct intel_dp_mst_encoder *intel_mst = enc_to_mst(encoder);

	drm_encoder_cleanup(encoder);
	kfree(intel_mst);
}

static const struct drm_encoder_funcs intel_dp_mst_enc_funcs = {
	.destroy = intel_dp_mst_encoder_destroy,
};

static bool intel_dp_mst_get_hw_state(struct intel_connector *connector)
{
	if (connector->encoder && connector->base.state->crtc) {
		enum pipe pipe;
		if (!connector->encoder->get_hw_state(connector->encoder, &pipe))
			return false;
		return true;
	}
	return false;
}

static void intel_connector_add_to_fbdev(struct intel_connector *connector)
{
#ifdef CONFIG_DRM_FBDEV_EMULATION
	struct drm_i915_private *dev_priv = to_i915(connector->base.dev);

	if (dev_priv->fbdev)
		drm_fb_helper_add_one_connector(&dev_priv->fbdev->helper,
						&connector->base);
#endif
}

static void intel_connector_remove_from_fbdev(struct intel_connector *connector)
{
#ifdef CONFIG_DRM_FBDEV_EMULATION
	struct drm_i915_private *dev_priv = to_i915(connector->base.dev);

	if (dev_priv->fbdev)
		drm_fb_helper_remove_one_connector(&dev_priv->fbdev->helper,
						   &connector->base);
#endif
}

static struct drm_connector *intel_dp_add_mst_connector(struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port, const char *pathprop)
{
	struct intel_dp *intel_dp = container_of(mgr, struct intel_dp, mst_mgr);
	struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
	struct drm_device *dev = intel_dig_port->base.base.dev;
	struct intel_connector *intel_connector;
	struct drm_connector *connector;
	int i;

	intel_connector = intel_connector_alloc();
	if (!intel_connector)
		return NULL;

	connector = &intel_connector->base;
	drm_connector_init(dev, connector, &intel_dp_mst_connector_funcs, DRM_MODE_CONNECTOR_DisplayPort);
	drm_connector_helper_add(connector, &intel_dp_mst_connector_helper_funcs);

	intel_connector->unregister = intel_connector_unregister;
	intel_connector->get_hw_state = intel_dp_mst_get_hw_state;
	intel_connector->mst_port = intel_dp;
	intel_connector->port = port;

	for (i = PIPE_A; i <= PIPE_C; i++) {
		drm_mode_connector_attach_encoder(&intel_connector->base,
						  &intel_dp->mst_encoders[i]->base.base);
	}
	intel_dp_add_properties(intel_dp, connector);

	drm_object_attach_property(&connector->base, dev->mode_config.path_property, 0);
	drm_object_attach_property(&connector->base, dev->mode_config.tile_property, 0);

	drm_mode_connector_set_path_property(connector, pathprop);
	return connector;
}

static void intel_dp_register_mst_connector(struct drm_connector *connector)
{
	struct intel_connector *intel_connector = to_intel_connector(connector);
	struct drm_device *dev = connector->dev;
	drm_modeset_lock_all(dev);
	intel_connector_add_to_fbdev(intel_connector);
	drm_modeset_unlock_all(dev);
	drm_connector_register(&intel_connector->base);
}

static void intel_dp_destroy_mst_connector(struct drm_dp_mst_topology_mgr *mgr,
					   struct drm_connector *connector)
{
	struct intel_connector *intel_connector = to_intel_connector(connector);
	struct drm_device *dev = connector->dev;

	intel_connector->unregister(intel_connector);

	/* need to nuke the connector */
	drm_modeset_lock_all(dev);
	intel_connector_remove_from_fbdev(intel_connector);
	intel_connector->mst_port = NULL;
	drm_modeset_unlock_all(dev);

	drm_connector_unreference(&intel_connector->base);
	DRM_DEBUG_KMS("\n");
}

static void intel_dp_mst_hotplug(struct drm_dp_mst_topology_mgr *mgr)
{
	struct intel_dp *intel_dp = container_of(mgr, struct intel_dp, mst_mgr);
	struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
	struct drm_device *dev = intel_dig_port->base.base.dev;

	drm_kms_helper_hotplug_event(dev);
}

static const struct drm_dp_mst_topology_cbs mst_cbs = {
	.add_connector = intel_dp_add_mst_connector,
	.register_connector = intel_dp_register_mst_connector,
	.destroy_connector = intel_dp_destroy_mst_connector,
	.hotplug = intel_dp_mst_hotplug,
};

static struct intel_dp_mst_encoder *
intel_dp_create_fake_mst_encoder(struct intel_digital_port *intel_dig_port, enum pipe pipe)
{
	struct intel_dp_mst_encoder *intel_mst;
	struct intel_encoder *intel_encoder;
	struct drm_device *dev = intel_dig_port->base.base.dev;

	intel_mst = kzalloc(sizeof(*intel_mst), GFP_KERNEL);

	if (!intel_mst)
		return NULL;

	intel_mst->pipe = pipe;
	intel_encoder = &intel_mst->base;
	intel_mst->primary = intel_dig_port;

	drm_encoder_init(dev, &intel_encoder->base, &intel_dp_mst_enc_funcs,
			 DRM_MODE_ENCODER_DPMST, NULL);

	intel_encoder->type = INTEL_OUTPUT_DP_MST;
	intel_encoder->crtc_mask = 0x7;
	intel_encoder->cloneable = 0;

	intel_encoder->compute_config = intel_dp_mst_compute_config;
	intel_encoder->disable = intel_mst_disable_dp;
	intel_encoder->post_disable = intel_mst_post_disable_dp;
	intel_encoder->pre_enable = intel_mst_pre_enable_dp;
	intel_encoder->enable = intel_mst_enable_dp;
	intel_encoder->get_hw_state = intel_dp_mst_enc_get_hw_state;
	intel_encoder->get_config = intel_dp_mst_enc_get_config;

	return intel_mst;

}

static bool
intel_dp_create_fake_mst_encoders(struct intel_digital_port *intel_dig_port)
{
	int i;
	struct intel_dp *intel_dp = &intel_dig_port->dp;

	for (i = PIPE_A; i <= PIPE_C; i++)
		intel_dp->mst_encoders[i] = intel_dp_create_fake_mst_encoder(intel_dig_port, i);
	return true;
}

int
intel_dp_mst_encoder_init(struct intel_digital_port *intel_dig_port, int conn_base_id)
{
	struct intel_dp *intel_dp = &intel_dig_port->dp;
	struct drm_device *dev = intel_dig_port->base.base.dev;
	int ret;

	intel_dp->can_mst = true;
	intel_dp->mst_mgr.cbs = &mst_cbs;

	/* create encoders */
	intel_dp_create_fake_mst_encoders(intel_dig_port);
	ret = drm_dp_mst_topology_mgr_init(&intel_dp->mst_mgr, dev->dev, &intel_dp->aux, 16, 3, conn_base_id);
	if (ret) {
		intel_dp->can_mst = false;
		return ret;
	}
	return 0;
}

void
intel_dp_mst_encoder_cleanup(struct intel_digital_port *intel_dig_port)
{
	struct intel_dp *intel_dp = &intel_dig_port->dp;

	if (!intel_dp->can_mst)
		return;

	drm_dp_mst_topology_mgr_destroy(&intel_dp->mst_mgr);
	/* encoders will get killed by normal cleanup */
}


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <link rel="apple-touch-icon" sizes="76x76" href="assets/img/logo-inf.png">
  <link rel="icon" type="image/png" href="assets/img/logo-inf.png">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
  <title>Bacharelado em Engenharia de Software</title>
  <meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, shrink-to-fit=no' name='viewport' />

  <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700,200" rel="stylesheet" />
  <link rel="stylesheet" href="assets/css/font-awesome.min.css" />

  <link href="assets/css/bootstrap.min.css" rel="stylesheet" />
  <link href="assets/css/now-ui-kit.css?v=1.1.0" rel="stylesheet" />
	<link href="assets/css/bes.css" rel="stylesheet" />

	        <button class="navbar-toggler navbar-toggler-menu" type="button" data-toggle="collapse" data-target="#navigation" aria-controls="navigation-index" aria-expanded="false" aria-label="Toggle navigation">

	        </button>

Home

Disciplinas

Informações

Página de Busca

Acessibilidade

                  Acessibilidade
                  <button class="dropdown-item" onclick="enableContrast()">Ativar Contraste</button>
                  Fonte
                  <button class="dropdown-item" onclick="fontSize(0)">A</button>
                  <button class="dropdown-item" onclick="fontSize(-1)">A-</button>
                  <button class="dropdown-item" onclick="fontSize(1)">A+</button>

Código-Fonte

Disciplinas

									UFG

									INF

										MIT License

          ©
          , Coded by
            geminos.


text:
<?php
namespace romaten1\books\helpers;

use Imagine\Image\Box;
use Imagine\Image\Point;
use Imagine\Gd\Imagine;
use Imagine\Image\ImageInterface;
/**
 * Данный класс позволяет обрабатывать фотографии.
 */
class ImageHelper
{
    /**
     * @param $path_from
     * @param $path_to
     * @param $desired_width
     *
     * Обработка рисунка и сохранение
     */
    public static  function makeImage( $path_from, $path_to, $desired_width )
    {
        $imagine       = new Imagine();
        $image         = $imagine->open( $path_from );
        $image_size    = $image->getSize();
        $image_height  = $image_size->getHeight();
        $image_width   = $image_size->getWidth();
        $ratio         = $image_width / $desired_width;
        $resizedHeight = $image_height / $ratio;
        $resizedWidth  = $image_width / $ratio;
        $resized_image = $image->resize( new Box( $resizedWidth, $resizedHeight ) );
        $options       = array(
            'resolution-units' => ImageInterface::RESOLUTION_PIXELSPERINCH,
            'resolution-x'     => 100,
            'resolution-y'     => 200,
            'flatten'          => false
        );
        $resized_image->save( $path_to, $options );
    }
}