text:
package io.quarkus.qute.generator;

import static io.quarkus.qute.generator.ValueResolverGenerator.generatedNameFromTarget;
import static io.quarkus.qute.generator.ValueResolverGenerator.packageName;
import static io.quarkus.qute.generator.ValueResolverGenerator.simpleName;
import static org.objectweb.asm.Opcodes.ACC_FINAL;
import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;

import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.BiConsumer;
import java.util.regex.Pattern;

import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationValue;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.IndexView;
import org.jboss.jandex.MethodInfo;
import org.jboss.jandex.PrimitiveType.Primitive;
import org.jboss.jandex.Type;
import org.jboss.jandex.Type.Kind;

import io.quarkus.gizmo.AssignableResultHandle;
import io.quarkus.gizmo.BranchResult;
import io.quarkus.gizmo.BytecodeCreator;
import io.quarkus.gizmo.CatchBlockCreator;
import io.quarkus.gizmo.ClassCreator;
import io.quarkus.gizmo.ClassOutput;
import io.quarkus.gizmo.FieldDescriptor;
import io.quarkus.gizmo.FunctionCreator;
import io.quarkus.gizmo.MethodCreator;
import io.quarkus.gizmo.MethodDescriptor;
import io.quarkus.gizmo.ResultHandle;
import io.quarkus.gizmo.TryBlock;
import io.quarkus.qute.EvalContext;
import io.quarkus.qute.EvaluatedParams;
import io.quarkus.qute.NamespaceResolver;
import io.quarkus.qute.TemplateException;
import io.quarkus.qute.TemplateExtension;
import io.quarkus.qute.ValueResolver;

/**
 * Generates value resolvers for static extension methods.
 *
 * @see ValueResolver
 * @see NamespaceResolver
 */
public class ExtensionMethodGenerator {

    public static final DotName TEMPLATE_EXTENSION = DotName.createSimple(TemplateExtension.class.getName());
    public static final DotName TEMPLATE_ATTRIBUTE = DotName.createSimple(TemplateExtension.TemplateAttribute.class.getName());
    public static final String SUFFIX = "_Extension" + ValueResolverGenerator.SUFFIX;
    public static final String NAMESPACE_SUFFIX = "_Namespace" + SUFFIX;

    public static final String MATCH_NAME = "matchName";
    public static final String MATCH_NAMES = "matchNames";
    public static final String MATCH_REGEX = "matchRegex";
    public static final String PRIORITY = "priority";
    public static final String NAMESPACE = "namespace";
    public static final String PATTERN = "pattern";

    private final Set<String> generatedTypes;
    private final ClassOutput classOutput;
    private final IndexView index;

    public ExtensionMethodGenerator(IndexView index, ClassOutput classOutput) {
        this.index = index;
        this.classOutput = classOutput;
        this.generatedTypes = new HashSet<>();
    }

    public Set<String> getGeneratedTypes() {
        return generatedTypes;
    }

    public static void validate(MethodInfo method, String namespace) {
        if (!Modifier.isStatic(method.flags())) {
            throw new IllegalStateException(
                    "Template extension method declared on " + method.declaringClass().name() + "  must be static: " + method);
        }
        if (method.returnType().kind() == Kind.VOID) {
            throw new IllegalStateException("Template extension method declared on " + method.declaringClass().name()
                    + " must not return void: " + method);
        }
        if (Modifier.isPrivate(method.flags())) {
            throw new IllegalStateException("Template extension method declared on " + method.declaringClass().name()
                    + " must not be private: " + method);
        }
    }

    public void generate(MethodInfo method, String matchName, List<String> matchNames, String matchRegex, Integer priority) {

        AnnotationInstance extensionAnnotation = method.annotation(TEMPLATE_EXTENSION);
        List<Type> parameters = method.parameterTypes();

        // Validate the method first
        // NOTE: this method is never used for namespace extension methods
        validate(method, null);
        ClassInfo declaringClass = method.declaringClass();

        if (matchName == null && extensionAnnotation != null) {
            // No explicit name defined, try annotation
            AnnotationValue matchNameValue = extensionAnnotation.value(MATCH_NAME);
            if (matchNameValue != null) {
                matchName = matchNameValue.asString();
            }
        }
        if (matchName == null || matchName.equals(TemplateExtension.METHOD_NAME)) {
            matchName = method.name();
        }

        if (matchNames == null && extensionAnnotation != null) {
            // No explicit name defined, try annotation
            AnnotationValue matchNamesValue = extensionAnnotation.value(MATCH_NAMES);
            if (matchNamesValue != null) {
                matchNames = new ArrayList<>();
                for (String name : matchNamesValue.asStringArray()) {
                    matchNames.add(name);
                }
            }
        }

        if (priority == null && extensionAnnotation != null) {
            // No explicit priority set, try annotation
            AnnotationValue priorityValue = extensionAnnotation.value(PRIORITY);
            if (priorityValue != null) {
                priority = priorityValue.asInt();
            }
        }
        if (priority == null) {
            priority = TemplateExtension.DEFAULT_PRIORITY;
        }

        if (matchRegex == null && extensionAnnotation != null) {
            AnnotationValue matchRegexValue = extensionAnnotation.value(MATCH_REGEX);
            if (matchRegexValue != null) {
                matchRegex = matchRegexValue.asString();
            }
        }

        if (matchRegex != null || !matchNames.isEmpty() || matchName.equals(TemplateExtension.ANY)) {
            // A string parameter is needed to match the name
            if (parameters.size() < 2 || !parameters.get(1).name().equals(DotNames.STRING)) {
                throw new TemplateException(
                        "A template extension method matching multiple names or a regular expression must declare at least two parameters and the second parameter must be string: "
                                + method);
            }
        }

        String baseName;
        if (declaringClass.enclosingClass() != null) {
            baseName = simpleName(declaringClass.enclosingClass()) + ValueResolverGenerator.NESTED_SEPARATOR
                    + simpleName(declaringClass);
        } else {
            baseName = simpleName(declaringClass);
        }
        String targetPackage = packageName(declaringClass.name());

        String suffix = SUFFIX + "_" + method.name() + "_" + sha1(parameters.toString());
        String generatedName = generatedNameFromTarget(targetPackage, baseName, suffix);
        generatedTypes.add(generatedName.replace('/', '.'));

        ClassCreator valueResolver = ClassCreator.builder().classOutput(classOutput).className(generatedName)
                .interfaces(ValueResolver.class).build();

        FieldDescriptor patternField = null;
        if (matchRegex != null && !matchRegex.isEmpty()) {
            patternField = valueResolver.getFieldCreator(PATTERN, Pattern.class)
                    .setModifiers(ACC_PRIVATE | ACC_FINAL).getFieldDescriptor();
            MethodCreator constructor = valueResolver.getMethodCreator("<init>", "V");
            // Invoke super()
            constructor.invokeSpecialMethod(Descriptors.OBJECT_CONSTRUCTOR, constructor.getThis());
            // Compile the regex pattern
            constructor.writeInstanceField(patternField, constructor.getThis(),
                    constructor.invokeStaticMethod(Descriptors.PATTERN_COMPILE, constructor.load(matchRegex)));
            constructor.returnValue(null);
        }

        implementGetPriority(valueResolver, priority);

        Parameters params = new Parameters(method,
                patternField != null || !matchNames.isEmpty() || matchName.equals(TemplateExtension.ANY), false);
        implementAppliesTo(valueResolver, method, matchName, matchNames, patternField, params);
        implementResolve(valueResolver, declaringClass, method, matchName, matchNames, patternField, params);

        valueResolver.close();
    }

    public NamespaceResolverCreator createNamespaceResolver(ClassInfo declaringClass, String namespace, int priority) {
        return new NamespaceResolverCreator(declaringClass, namespace, priority);
    }

    private void implementGetNamespace(ClassCreator namespaceResolver, String namespace) {
        MethodCreator getNamespace = namespaceResolver.getMethodCreator("getNamespace", String.class)
                .setModifiers(ACC_PUBLIC);
        getNamespace.returnValue(getNamespace.load(namespace));
    }

    private void implementGetPriority(ClassCreator valueResolver, int priority) {
        MethodCreator getPriority = valueResolver.getMethodCreator("getPriority", int.class)
                .setModifiers(ACC_PUBLIC);
        getPriority.returnValue(getPriority.load(priority));
    }

    private void implementResolve(ClassCreator valueResolver, ClassInfo declaringClass, MethodInfo method, String matchName,
            List<String> matchNames, FieldDescriptor patternField, Parameters params) {
        MethodCreator resolve = valueResolver.getMethodCreator("resolve", CompletionStage.class, EvalContext.class)
                .setModifiers(ACC_PUBLIC);

        ResultHandle evalContext = resolve.getMethodParam(0);
        ResultHandle base = resolve.invokeInterfaceMethod(Descriptors.GET_BASE, evalContext);
        boolean isNameParamRequired = patternField != null || !matchNames.isEmpty() || matchName.equals(TemplateExtension.ANY);
        boolean returnsCompletionStage = method.returnType().kind() != Kind.PRIMITIVE && ValueResolverGenerator
                .hasCompletionStageInTypeClosure(index.getClassByName(method.returnType().name()), index);

        ResultHandle ret;
        if (!params.needsEvaluation()) {
            // No parameter needs to be evaluated
            ResultHandle[] args = new ResultHandle[params.size()];
            for (int i = 0; i < params.size(); i++) {
                Param param = params.get(i);
                if (param.kind == ParamKind.BASE) {
                    args[i] = base;
                } else if (param.kind == ParamKind.NAME) {
                    args[i] = resolve.invokeInterfaceMethod(Descriptors.GET_NAME, evalContext);
                } else if (param.kind == ParamKind.ATTR) {
                    args[i] = resolve.invokeInterfaceMethod(Descriptors.GET_ATTRIBUTE, evalContext, resolve.load(param.name));
                }
            }
            // Invoke the extension method
            ResultHandle result = resolve
                    .invokeStaticMethod(MethodDescriptor.ofMethod(declaringClass.name().toString(), method.name(),
                            method.returnType().name().toString(),
                            params.parameterTypesAsStringArray()),
                            args);
            if (returnsCompletionStage) {
                ret = result;
            } else {
                ret = resolve.invokeStaticMethod(Descriptors.COMPLETED_STAGE, result);
            }
        } else {
            ret = resolve
                    .newInstance(MethodDescriptor.ofConstructor(CompletableFuture.class));
            // Evaluate params first
            ResultHandle name = resolve.invokeInterfaceMethod(Descriptors.GET_NAME, evalContext);
            // The CompletionStage upon which we invoke whenComplete()
            ResultHandle evaluatedParamsHandle = resolve.invokeStaticMethod(Descriptors.EVALUATED_PARAMS_EVALUATE,
                    evalContext);
            ResultHandle paramsReadyHandle = resolve.readInstanceField(Descriptors.EVALUATED_PARAMS_STAGE,
                    evaluatedParamsHandle);

            // Function that is called when params are evaluated
            FunctionCreator whenCompleteFun = resolve.createFunction(BiConsumer.class);
            resolve.invokeInterfaceMethod(Descriptors.CF_WHEN_COMPLETE, paramsReadyHandle, whenCompleteFun.getInstance());
            BytecodeCreator whenComplete = whenCompleteFun.getBytecode();
            AssignableResultHandle whenBase = whenComplete.createVariable(Object.class);
            whenComplete.assign(whenBase, base);
            AssignableResultHandle whenName = null;
            if (isNameParamRequired) {
                whenName = whenComplete.createVariable(String.class);
                whenComplete.assign(whenName, name);
            }
            AssignableResultHandle whenRet = whenComplete.createVariable(CompletableFuture.class);
            whenComplete.assign(whenRet, ret);
            AssignableResultHandle whenEvaluatedParams = whenComplete.createVariable(EvaluatedParams.class);
            whenComplete.assign(whenEvaluatedParams, evaluatedParamsHandle);
            AssignableResultHandle whenEvalContext = whenComplete.createVariable(EvalContext.class);
            whenComplete.assign(whenEvalContext, evalContext);

            BranchResult throwableIsNull = whenComplete.ifNull(whenComplete.getMethodParam(1));
            BytecodeCreator success = throwableIsNull.trueBranch();
            boolean isVarArgs = ValueResolverGenerator.isVarArgs(method);

            // Check type parameters and return NO_RESULT if failed
            List<Param> evaluated = params.evaluated();
            ResultHandle paramTypesHandle = success.newArray(Class.class, evaluated.size());
            int idx = 0;
            for (Param p : evaluated) {
                success.writeArrayValue(paramTypesHandle, idx++,
                        ValueResolverGenerator.loadParamType(success, p.type));
            }
            BytecodeCreator typeMatchFailed = success
                    .ifNonZero(success.invokeVirtualMethod(Descriptors.EVALUATED_PARAMS_PARAM_TYPES_MATCH,
                            whenEvaluatedParams, success.load(isVarArgs), paramTypesHandle))
                    .falseBranch();
            typeMatchFailed.invokeVirtualMethod(Descriptors.COMPLETABLE_FUTURE_COMPLETE, whenRet,
                    typeMatchFailed.invokeStaticMethod(Descriptors.NOT_FOUND_FROM_EC, whenEvalContext));
            typeMatchFailed.returnValue(null);

            // try
            TryBlock tryCatch = success.tryBlock();
            // catch (Throwable e)
            CatchBlockCreator exception = tryCatch.addCatch(Throwable.class);
            // CompletableFuture.completeExceptionally(Throwable)
            exception.invokeVirtualMethod(Descriptors.COMPLETABLE_FUTURE_COMPLETE_EXCEPTIONALLY, whenRet,
                    exception.getCaughtException());

            // Collect the params
            ResultHandle[] args = new ResultHandle[params.size()];
            int evalIdx = 0;
            int lastIdx = params.size() - 1;
            for (int i = 0; i < params.size(); i++) {
                Param param = params.get(i);
                if (param.kind == ParamKind.BASE) {
                    args[i] = whenBase;
                } else if (param.kind == ParamKind.NAME) {
                    args[i] = whenName;
                } else if (param.kind == ParamKind.ATTR) {
                    args[i] = tryCatch.invokeInterfaceMethod(Descriptors.GET_ATTRIBUTE, whenEvalContext,
                            tryCatch.load(param.name));
                } else {
                    if (isVarArgs && i == lastIdx) {
                        // Last param is varargs
                        Type varargsParam = params.get(lastIdx).type;
                        ResultHandle componentType = tryCatch
                                .loadClass(varargsParam.asArrayType().component().name().toString());
                        ResultHandle varargsResults = tryCatch.invokeVirtualMethod(
                                Descriptors.EVALUATED_PARAMS_GET_VARARGS_RESULTS,
                                evaluatedParamsHandle, tryCatch.load(evaluated.size()), componentType);
                        args[i] = varargsResults;
                    } else {
                        args[i] = tryCatch.invokeVirtualMethod(Descriptors.EVALUATED_PARAMS_GET_RESULT,
                                whenEvaluatedParams, tryCatch.load(evalIdx++));
                    }
                }
            }

            // Invoke the extension method
            ResultHandle invokeRet = tryCatch
                    .invokeStaticMethod(MethodDescriptor.ofMethod(declaringClass.name().toString(), method.name(),
                            method.returnType().name().toString(),
                            params.parameterTypesAsStringArray()),
                            args);
            tryCatch.invokeVirtualMethod(Descriptors.COMPLETABLE_FUTURE_COMPLETE, whenRet, invokeRet);

            BytecodeCreator failure = throwableIsNull.falseBranch();
            failure.invokeVirtualMethod(Descriptors.COMPLETABLE_FUTURE_COMPLETE_EXCEPTIONALLY, whenRet,
                    whenComplete.getMethodParam(1));
            whenComplete.returnValue(null);
        }

        resolve.returnValue(ret);
    }

    private void implementAppliesTo(ClassCreator valueResolver, MethodInfo method, String matchName, List<String> matchNames,
            FieldDescriptor patternField, Parameters params) {
        MethodCreator appliesTo = valueResolver.getMethodCreator("appliesTo", boolean.class, EvalContext.class)
                .setModifiers(ACC_PUBLIC);

        boolean matchAny = patternField == null && matchNames.isEmpty() && matchName.equals(TemplateExtension.ANY);
        boolean isVarArgs = ValueResolverGenerator.isVarArgs(method);
        ResultHandle evalContext = appliesTo.getMethodParam(0);
        ResultHandle base = appliesTo.invokeInterfaceMethod(Descriptors.GET_BASE, evalContext);
        ResultHandle name = appliesTo.invokeInterfaceMethod(Descriptors.GET_NAME, evalContext);
        BytecodeCreator baseNull = appliesTo.ifNull(base).trueBranch();
        baseNull.returnValue(baseNull.load(false));

        // Test base object class
        ResultHandle baseClass = appliesTo.invokeVirtualMethod(Descriptors.GET_CLASS, base);
        // Perform autoboxing for primitives
        ResultHandle testClass = appliesTo.loadClass(box(params.getFirst(ParamKind.BASE).type).name().toString());
        ResultHandle baseClassTest = appliesTo.invokeVirtualMethod(Descriptors.IS_ASSIGNABLE_FROM, testClass,
                baseClass);
        BytecodeCreator baseNotAssignable = appliesTo.ifTrue(baseClassTest).falseBranch();
        baseNotAssignable.returnValue(baseNotAssignable.load(false));

        // Test property name
        if (!matchAny) {
            if (patternField != null) {
                // if (!pattern.matcher(value).match()) {
                //   return false;
                // }
                ResultHandle pattern = appliesTo.readInstanceField(patternField, appliesTo.getThis());
                ResultHandle matcher = appliesTo.invokeVirtualMethod(Descriptors.PATTERN_MATCHER, pattern, name);
                BytecodeCreator nameNotMatched = appliesTo
                        .ifFalse(appliesTo.invokeVirtualMethod(Descriptors.MATCHER_MATCHES, matcher)).trueBranch();
                nameNotMatched.returnValue(appliesTo.load(false));
            } else if (!matchNames.isEmpty()) {
                // Any of the name matches
                BytecodeCreator namesMatch = appliesTo.createScope();
                for (String match : matchNames) {
                    ResultHandle nameTest = namesMatch.invokeVirtualMethod(Descriptors.EQUALS, name,
                            namesMatch.load(match));
                    namesMatch.ifTrue(nameTest).trueBranch().breakScope(namesMatch);
                }
                namesMatch.returnValue(namesMatch.load(false));
            } else {
                ResultHandle nameTest = appliesTo.invokeVirtualMethod(Descriptors.EQUALS, name,
                        appliesTo.load(matchName));
                BytecodeCreator nameNotMatched = appliesTo.ifFalse(nameTest).trueBranch();
                nameNotMatched.returnValue(nameNotMatched.load(false));
            }
        }

        // Test number of parameters
        int evaluatedParamsSize = params.evaluated().size();
        if (!isVarArgs || evaluatedParamsSize > 1) {
            ResultHandle paramsHandle = appliesTo.invokeInterfaceMethod(Descriptors.GET_PARAMS, evalContext);
            ResultHandle paramsCount = appliesTo.invokeInterfaceMethod(Descriptors.COLLECTION_SIZE, paramsHandle);
            BytecodeCreator paramsNotMatching;
            if (isVarArgs) {
                // For varargs methods match the minimal number of params
                paramsNotMatching = appliesTo.ifIntegerGreaterThan(appliesTo.load(evaluatedParamsSize - 1), paramsCount)
                        .trueBranch();
            } else {
                paramsNotMatching = appliesTo.ifIntegerEqual(appliesTo.load(evaluatedParamsSize), paramsCount).falseBranch();
            }
            paramsNotMatching.returnValue(paramsNotMatching.load(false));
        }

        appliesTo.returnValue(appliesTo.load(true));
    }

    public class NamespaceResolverCreator implements AutoCloseable {

        private final ClassCreator namespaceResolver;

        public NamespaceResolverCreator(ClassInfo declaringClass, String namespace, int priority) {
            String baseName;
            if (declaringClass.enclosingClass() != null) {
                baseName = simpleName(declaringClass.enclosingClass()) + ValueResolverGenerator.NESTED_SEPARATOR
                        + simpleName(declaringClass);
            } else {
                baseName = simpleName(declaringClass);
            }
            String targetPackage = packageName(declaringClass.name());

            String suffix = NAMESPACE_SUFFIX + "_" + sha1(namespace) + "_" + priority;
            String generatedName = generatedNameFromTarget(targetPackage, baseName, suffix);
            generatedTypes.add(generatedName.replace('/', '.'));

            this.namespaceResolver = ClassCreator.builder().classOutput(classOutput).className(generatedName)
                    .interfaces(NamespaceResolver.class).build();

            implementGetNamespace(namespaceResolver, namespace);
            implementGetPriority(namespaceResolver, priority);
        }

        public ResolveCreator implementResolve() {
            return new ResolveCreator();
        }

        @Override
        public void close() {
            namespaceResolver.close();
        }

        public class ResolveCreator implements AutoCloseable {

            private final MethodCreator resolve;
            private final MethodCreator constructor;
            private final ResultHandle evalContext;
            private final ResultHandle name;
            private final ResultHandle paramsHandle;
            private final ResultHandle paramsCount;

            public ResolveCreator() {
                this.resolve = namespaceResolver.getMethodCreator("resolve", CompletionStage.class, EvalContext.class)
                        .setModifiers(ACC_PUBLIC);
                this.evalContext = resolve.getMethodParam(0);
                this.name = resolve.invokeInterfaceMethod(Descriptors.GET_NAME, evalContext);
                this.paramsHandle = resolve.invokeInterfaceMethod(Descriptors.GET_PARAMS, evalContext);
                this.paramsCount = resolve.invokeInterfaceMethod(Descriptors.COLLECTION_SIZE, paramsHandle);
                this.constructor = namespaceResolver.getMethodCreator("<init>", "V");
                // Invoke super()
                this.constructor.invokeSpecialMethod(Descriptors.OBJECT_CONSTRUCTOR, constructor.getThis());
            }

            public void addMethod(MethodInfo method, String matchName, List<String> matchNames, String matchRegex) {
                FieldDescriptor patternField = null;
                if (matchRegex != null && !matchRegex.isEmpty()) {
                    patternField = namespaceResolver.getFieldCreator(PATTERN + "_" + sha1(method.toString()), Pattern.class)
                            .setModifiers(ACC_PRIVATE | ACC_FINAL).getFieldDescriptor();
                    constructor.writeInstanceField(patternField, constructor.getThis(),
                            constructor.invokeStaticMethod(Descriptors.PATTERN_COMPILE, constructor.load(matchRegex)));
                }

                boolean isNameParamRequired = patternField != null || !matchNames.isEmpty()
                        || matchName.equals(TemplateExtension.ANY);
                Parameters params = new Parameters(method, isNameParamRequired, true);

                BytecodeCreator matchScope = createNamespaceExtensionMatchScope(resolve, method, params.evaluated().size(),
                        matchName, matchNames, patternField, name, paramsHandle, paramsCount);

                if (!params.needsEvaluation()) {
                    ResultHandle[] args = new ResultHandle[params.size()];
                    for (int i = 0; i < params.size(); i++) {
                        Param param = params.get(i);
                        if (param.kind == ParamKind.NAME) {
                            args[i] = name;
                        } else if (param.kind == ParamKind.ATTR) {
                            args[i] = matchScope.invokeInterfaceMethod(Descriptors.GET_ATTRIBUTE, evalContext,
                                    matchScope.load(param.name));
                        }
                    }
                    matchScope.returnValue(matchScope.invokeStaticMethod(Descriptors.COMPLETED_STAGE,
                            matchScope.invokeStaticMethod(MethodDescriptor.of(method), args)));
                } else {
                    ResultHandle ret = matchScope.newInstance(MethodDescriptor.ofConstructor(CompletableFuture.class));

                    // Evaluate params first
                    // The CompletionStage upon which we invoke whenComplete()
                    ResultHandle evaluatedParamsHandle = matchScope.invokeStaticMethod(Descriptors.EVALUATED_PARAMS_EVALUATE,
                            evalContext);
                    ResultHandle paramsReadyHandle = matchScope.readInstanceField(Descriptors.EVALUATED_PARAMS_STAGE,
                            evaluatedParamsHandle);

                    // Function that is called when params are evaluated
                    FunctionCreator whenCompleteFun = matchScope.createFunction(BiConsumer.class);
                    matchScope.invokeInterfaceMethod(Descriptors.CF_WHEN_COMPLETE, paramsReadyHandle,
                            whenCompleteFun.getInstance());
                    BytecodeCreator whenComplete = whenCompleteFun.getBytecode();
                    AssignableResultHandle whenName = null;
                    if (isNameParamRequired) {
                        whenName = whenComplete.createVariable(String.class);
                        whenComplete.assign(whenName, name);
                    }
                    AssignableResultHandle whenRet = whenComplete.createVariable(CompletableFuture.class);
                    whenComplete.assign(whenRet, ret);
                    AssignableResultHandle whenEvaluatedParams = whenComplete.createVariable(EvaluatedParams.class);
                    whenComplete.assign(whenEvaluatedParams, evaluatedParamsHandle);
                    AssignableResultHandle whenEvalContext = whenComplete.createVariable(EvalContext.class);
                    whenComplete.assign(whenEvalContext, evalContext);

                    BranchResult throwableIsNull = whenComplete.ifNull(whenComplete.getMethodParam(1));
                    BytecodeCreator success = throwableIsNull.trueBranch();
                    boolean isVarArgs = ValueResolverGenerator.isVarArgs(method);

                    // Check type parameters and return NO_RESULT if failed
                    List<Param> evaluated = params.evaluated();
                    ResultHandle paramTypesHandle = success.newArray(Class.class, evaluated.size());
                    int idx = 0;
                    for (Param p : evaluated) {
                        success.writeArrayValue(paramTypesHandle, idx++,
                                ValueResolverGenerator.loadParamType(success, p.type));
                    }
                    BytecodeCreator typeMatchFailed = success
                            .ifTrue(success.invokeVirtualMethod(Descriptors.EVALUATED_PARAMS_PARAM_TYPES_MATCH,
                                    whenEvaluatedParams, success.load(isVarArgs), paramTypesHandle))
                            .falseBranch();
                    typeMatchFailed.invokeVirtualMethod(Descriptors.COMPLETABLE_FUTURE_COMPLETE, whenRet,
                            typeMatchFailed.invokeStaticMethod(Descriptors.NOT_FOUND_FROM_EC, whenEvalContext));
                    typeMatchFailed.returnValue(null);

                    // try
                    TryBlock tryCatch = success.tryBlock();
                    // catch (Throwable e)
                    CatchBlockCreator exception = tryCatch.addCatch(Throwable.class);
                    // CompletableFuture.completeExceptionally(Throwable)
                    exception.invokeVirtualMethod(Descriptors.COMPLETABLE_FUTURE_COMPLETE_EXCEPTIONALLY, whenRet,
                            exception.getCaughtException());

                    // Collect the params
                    ResultHandle[] args = new ResultHandle[params.size()];
                    int evalIdx = 0;
                    int lastIdx = params.size() - 1;
                    for (int i = 0; i < params.size(); i++) {
                        Param param = params.get(i);
                        if (param.kind == ParamKind.NAME) {
                            args[i] = whenName;
                        } else if (param.kind == ParamKind.ATTR) {
                            args[i] = tryCatch.invokeInterfaceMethod(Descriptors.GET_ATTRIBUTE, whenEvalContext,
                                    tryCatch.load(param.name));
                        } else {
                            if (isVarArgs && i == lastIdx) {
                                // Last param is varargs
                                Type varargsParam = params.get(lastIdx).type;
                                ResultHandle componentType = tryCatch
                                        .loadClass(varargsParam.asArrayType().component().name().toString());
                                ResultHandle varargsResults = tryCatch.invokeVirtualMethod(
                                        Descriptors.EVALUATED_PARAMS_GET_VARARGS_RESULTS,
                                        whenEvaluatedParams, tryCatch.load(evaluated.size()), componentType);
                                args[i] = varargsResults;
                            } else {
                                args[i] = tryCatch.invokeVirtualMethod(Descriptors.EVALUATED_PARAMS_GET_RESULT,
                                        whenEvaluatedParams, tryCatch.load(evalIdx++));
                            }
                        }
                    }

                    ResultHandle invokeRet = tryCatch.invokeStaticMethod(MethodDescriptor.of(method), args);
                    tryCatch.invokeVirtualMethod(Descriptors.COMPLETABLE_FUTURE_COMPLETE, whenRet, invokeRet);

                    BytecodeCreator failure = throwableIsNull.falseBranch();
                    failure.invokeVirtualMethod(Descriptors.COMPLETABLE_FUTURE_COMPLETE_EXCEPTIONALLY, whenRet,
                            whenComplete.getMethodParam(1));
                    whenComplete.returnValue(null);

                    matchScope.returnValue(ret);
                }
            }

            @Override
            public void close() {
                constructor.returnValue(null);
                resolve.returnValue(resolve.invokeStaticMethod(Descriptors.RESULTS_NOT_FOUND_EC, evalContext));
            }

        }

    }

    private BytecodeCreator createNamespaceExtensionMatchScope(BytecodeCreator bytecodeCreator, MethodInfo method,
            int realParamSize, String matchName, List<String> matchNames, FieldDescriptor patternField, ResultHandle name,
            ResultHandle params,
            ResultHandle paramsCount) {

        boolean matchAny = patternField == null && matchNames.isEmpty() && matchName.equals(TemplateExtension.ANY);
        boolean isVarArgs = ValueResolverGenerator.isVarArgs(method);

        BytecodeCreator matchScope = bytecodeCreator.createScope();
        // Test property name
        if (!matchAny) {
            if (patternField != null) {
                ResultHandle pattern = matchScope.readInstanceField(patternField, matchScope.getThis());
                ResultHandle matcher = matchScope.invokeVirtualMethod(Descriptors.PATTERN_MATCHER, pattern, name);
                matchScope.ifFalse(matchScope.invokeVirtualMethod(Descriptors.MATCHER_MATCHES, matcher)).trueBranch()
                        .breakScope(matchScope);
            } else if (!matchNames.isEmpty()) {
                // Any of the name matches
                BytecodeCreator namesMatch = matchScope.createScope();
                for (String match : matchNames) {
                    ResultHandle nameTest = namesMatch.invokeVirtualMethod(Descriptors.EQUALS, name,
                            namesMatch.load(match));
                    namesMatch.ifTrue(nameTest).trueBranch().breakScope(namesMatch);
                }
                namesMatch.breakScope(matchScope);
            } else {
                matchScope.ifTrue(matchScope.invokeVirtualMethod(Descriptors.EQUALS,
                        matchScope.load(matchName),
                        name))
                        .falseBranch().breakScope(matchScope);
            }
        }
        // Test number of parameters
        if (!isVarArgs || realParamSize > 1) {
            if (isVarArgs) {
                // For varargs methods match the minimal number of params
                matchScope.ifIntegerLessEqual(matchScope.load(realParamSize - 1), paramsCount).falseBranch()
                        .breakScope(matchScope);
            } else {
                matchScope.ifIntegerEqual(matchScope.load(realParamSize), paramsCount).falseBranch().breakScope(matchScope);
            }
        }
        return matchScope;
    }

    static String sha1(String value) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(value.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder(40);
            for (int i = 0; i < digest.length; ++i) {
                sb.append(Integer.toHexString((digest[i] & 0xFF) | 0x100).substring(1, 3));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e);
        }
    }

    static Type box(Type type) {
        if (type.kind() == Kind.PRIMITIVE) {
            return box(type.asPrimitiveType().primitive());
        }
        return type;
    }

    static Type box(Primitive primitive) {
        switch (primitive) {
            case BOOLEAN:
                return Type.create(DotNames.BOOLEAN, Kind.CLASS);
            case DOUBLE:
                return Type.create(DotNames.DOUBLE, Kind.CLASS);
            case FLOAT:
                return Type.create(DotNames.FLOAT, Kind.CLASS);
            case LONG:
                return Type.create(DotNames.LONG, Kind.CLASS);
            case INT:
                return Type.create(DotNames.INTEGER, Kind.CLASS);
            case BYTE:
                return Type.create(DotNames.BYTE, Kind.CLASS);
            case CHAR:
                return Type.create(DotNames.CHARACTER, Kind.CLASS);
            case SHORT:
                return Type.create(DotNames.SHORT, Kind.CLASS);
            default:
                throw new IllegalArgumentException("Unsupported primitive: " + primitive);
        }
    }

    public static final class Parameters implements Iterable<Param> {

        final List<Param> params;

        public Parameters(MethodInfo method, boolean isNameParameterRequired, boolean hasNamespace) {
            List<Type> parameters = method.parameterTypes();
            Map<Integer, String> attributeParamNames = new HashMap<>();
            for (AnnotationInstance annotation : method.annotations()) {
                if (annotation.target().kind() == org.jboss.jandex.AnnotationTarget.Kind.METHOD_PARAMETER
                        && annotation.name().equals(TEMPLATE_ATTRIBUTE)) {
                    AnnotationValue value = annotation.value();
                    int position = (int) annotation.target().asMethodParameter().position();
                    String name = value != null ? value.asString() : method.parameterName(position);
                    if (name == null) {
                        throw new TemplateException("Parameter names not recorded for " + method.declaringClass().name()
                                + ": compile the class with -parameters");
                    }
                    attributeParamNames.put(position, name);
                }
            }
            List<Param> params = new ArrayList<>(parameters.size());
            int indexed = 0;
            for (int i = 0; i < parameters.size(); i++) {
                if (attributeParamNames.containsKey(i)) {
                    params.add(new Param(attributeParamNames.get(i), parameters.get(i), i, ParamKind.ATTR));
                } else if (indexed == 0) {
                    indexed++;
                    if (hasNamespace) {
                        // Namespace and matches any or regex - first indexed param is the name
                        if (isNameParameterRequired) {
                            params.add(new Param(method.parameterName(i), parameters.get(i), i, ParamKind.NAME));
                        } else {
                            params.add(new Param(method.parameterName(i), parameters.get(i), i, ParamKind.EVAL));
                        }
                    } else {
                        // No namespace but matches any or regex
                        params.add(new Param(method.parameterName(i), parameters.get(i), i, ParamKind.BASE));
                    }
                } else if (indexed == 1 && !hasNamespace && isNameParameterRequired) {
                    indexed++;
                    params.add(new Param(method.parameterName(i), parameters.get(i), i, ParamKind.NAME));
                } else {
                    indexed++;
                    params.add(new Param(method.parameterName(i), parameters.get(i), i, ParamKind.EVAL));
                }
            }
            this.params = params;

            if (isNameParameterRequired) {
                Param nameParam = getFirst(ParamKind.NAME);
                if (nameParam == null || !nameParam.type.name().equals(DotNames.STRING)) {
                    throw new TemplateException(
                            "Template extension method declared on " + method.declaringClass().name()
                                    + " must accept at least one string parameter to match the name: " + method);
                }
            }
            if (!hasNamespace && getFirst(ParamKind.BASE) == null) {
                throw new TemplateException(
                        "Template extension method declared on " + method.declaringClass().name()
                                + " must accept at least one parameter to match the base object: " + method);
            }

            for (Param param : params) {
                if (param.kind == ParamKind.ATTR && !param.type.name().equals(DotNames.OBJECT)) {
                    throw new TemplateException(
                            "Template extension method parameter annotated with @TemplateAttribute declared on "
                                    + method.declaringClass().name()
                                    + " must be of type java.lang.Object: " + method);
                }
            }
        }

        public String[] parameterTypesAsStringArray() {
            String[] types = new String[params.size()];
            for (int i = 0; i < params.size(); i++) {
                types[i] = params.get(i).type.name().toString();
            }
            return types;
        }

        public Param getFirst(ParamKind kind) {
            for (Param param : params) {
                if (param.kind == kind) {
                    return param;
                }
            }
            return null;
        }

        public Param get(int index) {
            return params.get(index);
        }

        public int size() {
            return params.size();
        }

        public boolean needsEvaluation() {
            for (Param param : params) {
                if (param.kind == ParamKind.EVAL) {
                    return true;
                }
            }
            return false;
        }

        public List<Param> evaluated() {
            if (params.isEmpty()) {
                return Collections.emptyList();
            }
            List<Param> evaluated = new ArrayList<>();
            for (Param param : params) {
                if (param.kind == ParamKind.EVAL) {
                    evaluated.add(param);
                }
            }
            return evaluated;
        }

        @Override
        public Iterator<Param> iterator() {
            return params.iterator();
        }

    }

    public static final class Param {

        public final String name;
        public final Type type;
        public final int position;
        public final ParamKind kind;

        public Param(String name, Type type, int position, ParamKind paramKind) {
            this.name = name;
            this.type = type;
            this.position = position;
            this.kind = paramKind;
        }

        @Override
        public String toString() {
            return "Param [name=" + name + ", type=" + type + ", position=" + position + ", kind=" + kind + "]";
        }

    }

    enum ParamKind {
        BASE,
        NAME,
        ATTR,
        EVAL
    }

}


text:
package org.guvnor.common.services.workingset.client.events;

import org.uberfire.backend.vfs.Path;

/**
 *
 */
public class OnWorkingSetDisabled {

    private Path resource;
    private Path workingSet;

    public OnWorkingSetDisabled() {
    }

    public OnWorkingSetDisabled( final Path resource,
                                 final Path workingSet ) {
        this.resource = resource;
        this.workingSet = workingSet;
    }

    public Path getResource() {
        return resource;
    }

    public Path getWorkingSet() {
        return workingSet;
    }
}

redpajama_set_name: RedPajamaGithub


text:
module S3reamer
  class S3WriteStream
    DEFAULT_OPTIONS = {
      chunk_size: 5 * 1024 * 1024
    }

    def initialize(object, options = {})
      @buffer = String.new
      @options = DEFAULT_OPTIONS.merge(options)
      @multipart_upload = object.initiate_multipart_upload
      @closed = false
    end

    def write(data)
      raise RuntimeError.new("Illegal state: cannot write after close.") if @closed

      @buffer << data
      flush if @buffer.length >= @options[:chunk_size]
    end

    def flush
      part = @multipart_upload.part(@multipart_upload.parts.count + 1)
      part.upload(body: @buffer)
      @buffer.clear
    end

    def close
      flush unless @buffer.empty?
      @multipart_upload.complete(compute_parts: true)
      @closed = true
    end
  end
end


text:
<?php

require_once 'PHPUnit/Framework.php';

/**
 * @covers Db_Inflector
 */
class Db_InflectorTest extends PHPUnit_Framework_TestCase
{
	// ------------------------------------------------------------------------

	public function setUp()
	{
		require_once dirname(__FILE__).'/../../lib/Db/Inflector.php';
	}

	// ------------------------------------------------------------------------

	public function testPluralize()
	{
		$this->assertEquals('tables', Db_Inflector::pluralize('table'));
		$this->assertEquals('hives', Db_Inflector::pluralize('hive'));
	}

	// ------------------------------------------------------------------------

	public function testPluralizePlural()
	{
		$this->assertEquals('tables', Db_Inflector::pluralize('tables'));
		$this->assertEquals('hives', Db_Inflector::pluralize('hives'));
	}

	// ------------------------------------------------------------------------

	public function testPluralUppercaseFirst()
	{
		$this->assertEquals('Tables', Db_Inflector::pluralize('Table'));
		$this->assertEquals('Children', Db_Inflector::pluralize('Child'));
	}

	// ------------------------------------------------------------------------

	public function testPluralizeIrregular()
	{
		$this->assertEquals('atlases', Db_Inflector::pluralize('atlas'));
		$this->assertEquals('children', Db_Inflector::pluralize('child'));
	}

	// ------------------------------------------------------------------------

	public function testPluralizeIrregularPlural()
	{
		$this->assertEquals('atlases', Db_Inflector::pluralize('atlases'));
		$this->assertEquals('children', Db_Inflector::pluralize('children'));
	}

	// ------------------------------------------------------------------------

	public function testPluralizeUncountable()
	{
		$this->assertEquals('news', Db_Inflector::pluralize('news'));
		$this->assertEquals('equipment', Db_Inflector::pluralize('equipment'));
	}

	// ------------------------------------------------------------------------

	public function testSingularize()
	{
		$this->assertEquals('table', Db_Inflector::singularize('tables'));
		$this->assertEquals('hive', Db_Inflector::singularize('hives'));
	}

	// ------------------------------------------------------------------------

	public function testSingularizeSingular()
	{
		$this->assertEquals('table', Db_Inflector::singularize('table'));
		$this->assertEquals('hive', Db_Inflector::singularize('hive'));
	}

	// ------------------------------------------------------------------------

	public function testSingularizeUppercaseFirst()
	{
		$this->assertEquals('Table', Db_Inflector::singularize('Tables'));
		$this->assertEquals('Child', Db_Inflector::singularize('Children'));
	}

	// ------------------------------------------------------------------------

	public function testSingularizeIrregular()
	{
		$this->assertEquals('atlas', Db_Inflector::singularize('atlases'));
		$this->assertEquals('child', Db_Inflector::singularize('children'));
	}

	// ------------------------------------------------------------------------

	public function testSingularizeIrregularSingular()
	{
		$this->assertEquals('atlas', Db_Inflector::singularize('atlas'));
		$this->assertEquals('child', Db_Inflector::singularize('child'));
	}

	// ------------------------------------------------------------------------

	public function testSingularizeUncountable()
	{
		$this->assertEquals('news', Db_Inflector::singularize('news'));
		$this->assertEquals('equipment', Db_Inflector::singularize('equipment'));
	}
}

/* End of file InflectorTest.php */
/* Location: ./tests/Db */


text: %% Database-related predicates are built-in in SICStus3


text:
package org.sfm.map.getter.impl.time;

import org.sfm.reflect.Getter;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.TemporalAccessor;
import java.util.Date;

public class JavaLocalDateFromObjectGetter<S> implements Getter<S, LocalDate> {
    private final Getter<S, ?> getter;
    private final ZoneId zone;

    public JavaLocalDateFromObjectGetter(Getter<S, ?> getter, ZoneId zoneId) {
        this.getter = getter;
        this.zone = zoneId;
    }

    @Override
    public LocalDate get(S target) throws Exception {
        Object o = getter.get(target);

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

        if (o instanceof Date) {
            return Instant.ofEpochMilli(((Date) o).getTime()).atZone(zone).toLocalDate();
        }

        if (o instanceof LocalDate) {
            return (LocalDate) o;
        }

        if (o instanceof LocalDateTime) {
            return ((LocalDateTime)o).toLocalDate();
        }

        if (o instanceof TemporalAccessor) {
            return LocalDate.from((TemporalAccessor) o);
        }

        throw new IllegalArgumentException("Cannot convert " + o + " to LocalDate");
    }

    @Override
    public String toString() {
        return "JavaLocalDateFromObjectGetter{" +
                "getter=" + getter +
                '}';
    }
}


text:
package fake

import (
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/apimachinery/registered"
	clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
	unversionedautoscaling "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned"
	fakeunversionedautoscaling "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/fake"
	unversionedbatch "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned"
	fakeunversionedbatch "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/fake"
	unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned"
	fakeunversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake"
	unversionedextensions "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned"
	fakeunversionedextensions "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake"
	unversionedrbac "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned"
	fakeunversionedrbac "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake"
	"k8s.io/kubernetes/pkg/client/testing/core"
	"k8s.io/kubernetes/pkg/client/typed/discovery"
	fakediscovery "k8s.io/kubernetes/pkg/client/typed/discovery/fake"
	"k8s.io/kubernetes/pkg/runtime"
	"k8s.io/kubernetes/pkg/watch"
)

// Clientset returns a clientset that will respond with the provided objects
func NewSimpleClientset(objects ...runtime.Object) *Clientset {
	o := core.NewObjects(api.Scheme, api.Codecs.UniversalDecoder())
	for _, obj := range objects {
		if err := o.Add(obj); err != nil {
			panic(err)
		}
	}

	fakePtr := core.Fake{}
	fakePtr.AddReactor("*", "*", core.ObjectReaction(o, registered.RESTMapper()))

	fakePtr.AddWatchReactor("*", core.DefaultWatchReactor(watch.NewFake(), nil))

	return &Clientset{fakePtr}
}

// Clientset implements clientset.Interface. Meant to be embedded into a
// struct to get a default implementation. This makes faking out just the method
// you want to test easier.
type Clientset struct {
	core.Fake
}

func (c *Clientset) Discovery() discovery.DiscoveryInterface {
	return &fakediscovery.FakeDiscovery{Fake: &c.Fake}
}

var _ clientset.Interface = &Clientset{}

// Core retrieves the CoreClient
func (c *Clientset) Core() unversionedcore.CoreInterface {
	return &fakeunversionedcore.FakeCore{Fake: &c.Fake}
}

// Extensions retrieves the ExtensionsClient
func (c *Clientset) Extensions() unversionedextensions.ExtensionsInterface {
	return &fakeunversionedextensions.FakeExtensions{Fake: &c.Fake}
}

// Autoscaling retrieves the AutoscalingClient
func (c *Clientset) Autoscaling() unversionedautoscaling.AutoscalingInterface {
	return &fakeunversionedautoscaling.FakeAutoscaling{Fake: &c.Fake}
}

// Batch retrieves the BatchClient
func (c *Clientset) Batch() unversionedbatch.BatchInterface {
	return &fakeunversionedbatch.FakeBatch{Fake: &c.Fake}
}

// Rbac retrieves the RbacClient
func (c *Clientset) Rbac() unversionedrbac.RbacInterface {
	return &fakeunversionedrbac.FakeRbac{Fake: &c.Fake}
}


text:
it("should compile without error", function() {
	return import(/* webpackChunkName: "one" */ "./one");
});


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class VitrineProduto_Model extends CI_Model {

	public function getTotal($condicao = array()) {
		$this->db->from('vitrineproduto');
		$this->db->where($condicao);
		return $this->db->count_all_results();
	}

	public function get($condicao = array(), $primeiraLinha = FALSE, $pagina = 0, $limite = LINHAS_PESQUISA_DASHBOARD) {
		$this->db->select('v.codvitrineproduto, v.ordemvitrineproduto, v.codproduto, v.codvitrine, p.urlseo, p.valorproduto, p.valorpromocional');
		$this->db->select('p.nomeproduto');
		$this->db->from('vitrineproduto v');
		$this->db->from('produto p');
		$this->db->where('p.codproduto', 'v.codproduto', FALSE);
		$this->db->where($condicao);
		$this->db->order_by('v.ordemvitrineproduto');

		if ($primeiraLinha) {
			return $this->db->get()->first_row();
		} else {
			if ($limite !== FALSE) {
				$this->db->limit($limite, $pagina);
			}
			return $this->db->get()->result();
		}
	}

	public function post($itens) {
		$itens['codvitrineproduto'] = $this->Increment('codvitrineproduto');

		$res = $this->db->insert('vitrineproduto', $itens);
		if ($res) {
			$this->db->select_max('codvitrineproduto', 'id');
			return $this->db->get('vitrineproduto')->result();
		} else {
			return FALSE;
		}
	}

	//Incremento no codvitrineproduto para a inserção de um novo usuário
	private function Increment($campo)
	{
		$this->db->select_max($campo, 'num');
		$res = $this->db->get('vitrineproduto')->result();

		if ($res) {
			return $res[0]->num + 1;
		} else {
			return 1;
		}
	}

	public function aumentarOrdem ($codvitrineproduto) {
		$this->db->set('ordemvitrineproduto', 'ordemvitrineproduto + 1', FALSE);
		$this->db->where('codvitrineproduto', $codvitrineproduto, FALSE);
		$this->db->update('vitrineproduto');
	}

	public function diminuirOrdem ($codvitrineproduto) {
		$this->db->set('ordemvitrineproduto', 'ordemvitrineproduto - 1', FALSE);
		$this->db->where('codvitrineproduto', $codvitrineproduto, FALSE);
		$this->db->update('vitrineproduto');
	}

	public function redifineAntigo ($codvitrine, $codvitrineproduto, $novaPosicao, $velhaPosicao) {
		$this->db->set('ordemvitrineproduto', $velhaPosicao, FALSE);
		$this->db->where('ordemvitrineproduto', $novaPosicao, FALSE);
		$this->db->where('codvitrineproduto != ', $codvitrineproduto, FALSE);
		$this->db->where('codvitrine', $codvitrine, FALSE);
		$this->db->update('vitrineproduto');
	}

	public function delete($codvitrineproduto) {
		$this->db->where('codvitrineproduto', $codvitrineproduto, FALSE);
		return $this->db->delete('vitrineproduto');
	}

	public function atualizarDelete($codvitrine, $velhaPosicao) {
		$this->db->set('ordemvitrineproduto', 'ordemvitrineproduto - 1', FALSE);
		$this->db->where('codvitrine', $codvitrine, FALSE);
		$this->db->where('ordemvitrineproduto > ', $velhaPosicao, FALSE);
		$this->db->update('vitrineproduto');
	}
}


text:
import factory

from articletrack import models
from journalmanager.tests.modelfactories import JournalFactory, UserFactory, CollectionFactory

class ArticleFactory(factory.Factory):
    FACTORY_FOR = models.Article

    #journals = JournalFactory()
    article_title = u'An azafluorenone alkaloid and a megastigmane from Unonopsis lindmanii (Annonaceae)'
    articlepkg_ref = 1
    journal_title = u'Journal of the Brazilian Chemical Society'
    issue_label = u'2013 v.24 n.4'
    pissn = '1234-1234'
    eissn = ''

    @classmethod
    def _prepare(cls, create, **kwargs):
        user = UserFactory(is_active=True)
        collection = CollectionFactory.create()
        collection.add_user(user, is_manager=True)
        journal = JournalFactory()
        journal.join(collection, user)
        article = super(ArticleFactory, cls)._prepare(create, **kwargs)
        article.journals.add(journal)
        return article

class CheckinFactory(factory.Factory):
    FACTORY_FOR = models.Checkin

    attempt_ref = 1
    package_name = u'20132404.zip'
    uploaded_at = '2013-11-13 15:23:12.286068-02'
    created_at = '2013-11-13 15:23:18.286068-02'

    article = factory.SubFactory(ArticleFactory)

class NoticeFactory(factory.Factory):
    FACTORY_FOR = models.Notice

    checkin = factory.SubFactory(CheckinFactory)

    stage = u'reference'
    checkpoint = u'Validation'
    message = u'The reference xyz is not ok'
    status = 'error'
    created_at = '2013-11-13 15:23:18.286068-02'

class TicketFactory(factory.Factory):
    FACTORY_FOR = models.Ticket

    started_at = '2013-11-13 15:23:12'
    title = u'change XYZ at ABC for XXX'
    message = u'the XYZ at ABC must be changed for XXX because YYY'
    article = factory.SubFactory(ArticleFactory)
    author = factory.SubFactory(UserFactory)

class CommentFactory(factory.Factory):
    FACTORY_FOR = models.Comment

    author = factory.SubFactory(UserFactory)
    ticket = factory.SubFactory(TicketFactory)
    message = u'Fixed!'


text:
<img src="static/Que-es-TDD.png" width="128" alt="TDD">

# TDD (Test-driven development)

## Index

* [TDD "The Great Unknown"](#tdd-the-great-unknown)
* [What is TDD?](#what-is-tdd)
* [Advantages and disadvantages](#advantages-and-disadvantages)
* [Based Features](#based-features)
* [Tdd test properties](#tdd-test-properties)
* [Cycle of TDD](#cycle-of-tdd)
* [Speed is the key](#speed-is-the-key)
* [Executable documentation](#executable-documentation)
* [Design Principles](#design-principles)
* [Recommendations](#recommendations)
* [Conclusions](#conclusions)
* [References](#references)

### TDD "The Great Unknown"
The TDD concept is generally misunderstood by people. Perhaps the acronym TDD "Test-driven development " are not the most convenient. The "T" of TDD cheats a bit for TDD is not a testing methodology else a development methodology and design software.
In practice TDD tends to confuse concepts are interrelated but do not start from the same root:
> Self -testing -code ! = TDD ! = Unit testing

Self -testing -code ! = TDD , TDD has not primary mission the test coverage. This coverage is a benefit that is obtained by applying the methodology. This means that you can have high test coverage making after developing the product. It isnt´t condition applying TDD or to have high test coverage.

TDD ! = Unit testing , unit test as much as possible try to be decoupled by definition. In exchange for not applying the compulsory decoupling TDD code is required although it is convenient. Moreover, in many parts of it will be convenient to be a "small" coupled for some tests. Moreover establish any automated test framework is a consequence of applying the methodology.

People also believed that applying TDD the need for other types of tests is eliminated. This is completely false as there are types of test as system test "End to End" performing QA that do not comply with the principles that must meet a test in TDD. TDD therefore does not eliminate the QA work even if indirectly reduced because the number of bugs that can appear in higher-level test without having appeared in unit testing or integration of lower level is very low probability occur.

### What is TDD?
The definition of wikipedia express:
> "Test-driven development (TDD) is a software development process that relies on the repetition of a very short development cycle: first the developer writes an (initially failing) automated test case that defines a desired improvement or new function, then produces the minimum amount of code to pass that test, and finally refactors the new code to acceptable standards"

TDD is more than just perform test at first. As a result of applying the methodology produced automated test and also occur following the first TFD "Test - First- development".
But we must not forget that the main mission of the methodology is to design the software product by examples. These examples are translated in getting test emerging architecture of our product iteratively and incrementally only what the customer asks us .

### Advantages and disadvantages
The main advantages and disadvantages are:

| Advantages                                 | disadvantages |
| :-------------                             |:-------------|
| The tests act as low documentation         | Always focus on micro design |
| Debugging less time                        | The developer makes testing : it goes against good testing practices |
| Higher quality software                    | More development time delay so the feedback to the user |
| Lower maintenance costs                    | Learning curve for new teams |
| Avoid overdesigned : a test requires us to write the minimum functionality | |
| Solid test coverage                        | |

### Based Features
TDD methodology provides a basis features:

| Written by developers (TDD)|
| :-------------|
| How does the system|
| Test code|
| Vocabulary solution|
| With implementation detail|

### Tdd test properties
All unit test that applies tdd must to be:

> * **FAST**: Large number of test should be very fast.
> * **INDEPENDENT**: You can not depend on another to produce a satisfactory result.
> * **REPEATABLE**: Innocuous. You should not alter the system. It will run just 20 times.
> * **SMALL**: Atomic. Proving the minimum amount of functionality possible.
> * **TRANSPARENT**: Clear the purpose of the test, even without comment.

### Cycle of TDD
The iterative cycle methodology is divided in three easy steps: *RED - GREEN - REFACTOR*

![alt text](static/red-green-refactor.png "Reed-Green-Refactor")

* We write a test
* We run all tests
* Check that the last written test fails **(RED)**
* Write code implementation
* We run all tests
* Check that all tests pass **(GREEN)**
* Refactored the code **(Refactoring)**
* We run all tests
* We check that all tests pass

### Speed is the key
Speed is the key to success of TDD. We must make the cycle in minutes, even seconds. You can compare it like a game of ping pong.

* We write and execute all test **(PING)**.
* We write implementation **(PONG)**.
* Refactored and confirm that all tests pass **(POINT)**.

### Executable documentation
One consequence and benefit of applying the TDD methodology is the generation of an executable documentation. The tests act as documentation for developers. Practically we do not need to put comments in the code. The nomenclature should explain the functionality test. It is easier to understand the code does a test that implementation of the code itself. The documentation does not conflict with other documents of higher or wider level. Code documentation is completely further. The documentation is kept current without any extra work because it belongs flow methodology.

### Design Principles
* YAGNI ("You ain't gonna need it"):

> It is aimed at eliminating unnecessary code and focus on functionality. Less code means less maintenance and less chance of bugs.

* DRY ("Don't repeat yourself"):

> We reuse previously written code. The benefit is less code to maintain and use code that we know works.

* KISS ("Keep it simple, stupid"):

> Keep the code as simple as possible while performing their function.

* OCCAM'S RAZOR ("Philosophical principle"):

> Being equal, the simplest explanation is usually the most likely. That is, when you have two solutions to the same problem, the simplest is often the best.

### Recommendations
There are problems in applying the methodology tdd.

* TDD with an unknown technology:

> It is common when we started with new tools that problems occur when following the TDD methodology. As a first approximation is convenient "spikes " or concept testing tools. *Before driving the car it is important to know where the steering wheel, brake etc*.

* TDD middle of a project:

> One of the questions that arise when we start implementing TDD is: *Can you apply TDD project started?*For the new that has to implement course. The problem comes to what is already developed. In this case you could abusing lot of mocks. There are many legacy without coverage test and difficult to use parts. So they can live the parties will be necessary in many mocks even penalize fragility test. *Best parachute jump without it!*

### Conclusions
To apply the TDD methodology is necessary to change the mindset of how teams have worked in traditional development methodologies. This usually has a significant learning curve to start. TDD program "now" is not programmed thinking " it just in case. "Cast the first stone that the developer has not set then things have not been used. In the end this is just in case it not using!

The developments do not work with the super architect who owns the application. **So the super enterprise architect does not mount the foundation product for developers to add functionality?** The answer is a resounding no. The super architect remains a reference and asked for advice and help, but the technical team will be responsible for emerging architecture. That is all developers act as architects, designers and developers. TDD promotes the concept of "collective code" leaving aside the stereotype that certain portions of code only the certain technical touch.

Note that this method works to be met mainly two things ; first the whole team and the second TDD make the team and the client has a constant flow of communication following an iterative and incremental manner any agile methodology like Scrum. Without this low success we have applied the methodology.

### References

* [Link](https://www.beeva.com/beeva-view/metodologiasagiles/desarrollo-dirigido-por-test-el-gran-desconocido/) Beeva TDD
* [Course](https://github.com/beeva-danielpetrovic/beeva-curso-tdd) Beeva course TDD
* [Katas](https://github.com/beeva-danielpetrovic/beeva-taller-tdd/tree/master) Beeva katas TDD

___

[BEEVA](http://www.beeva.com) | 2016


text:
// Author: jud@google.com (Jud Porter)

#include "net/instaweb/rewriter/public/split_html_beacon_filter.h"

#include <algorithm>

#include "net/instaweb/http/public/request_context.h"
#include "net/instaweb/http/public/user_agent_matcher_test_base.h"
#include "net/instaweb/rewriter/public/beacon_critical_line_info_finder.h"
#include "net/instaweb/rewriter/public/critical_line_info_finder.h"
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/rewriter/public/rewrite_options.h"
#include "net/instaweb/rewriter/public/rewrite_test_base.h"
#include "net/instaweb/rewriter/public/server_context.h"
#include "net/instaweb/rewriter/public/static_asset_manager.h"
#include "net/instaweb/rewriter/public/test_rewrite_driver_factory.h"
#include "net/instaweb/util/public/mock_property_page.h"
#include "net/instaweb/util/public/property_cache.h"
#include "pagespeed/kernel/base/gtest.h"
#include "pagespeed/kernel/base/mock_timer.h"
#include "pagespeed/kernel/base/string.h"
#include "pagespeed/kernel/base/string_util.h"
#include "pagespeed/kernel/base/timer.h"
#include "pagespeed/kernel/html/html_parse_test_base.h"

namespace net_instaweb {

class SplitHtmlBeaconFilterTest : public RewriteTestBase {
 protected:
  SplitHtmlBeaconFilterTest() {}
  virtual ~SplitHtmlBeaconFilterTest() {}

  virtual void SetUp() {
    RewriteTestBase::SetUp();
    SplitHtmlBeaconFilter::InitStats(statistics());
    // Enabling the filter and options that will turn on beacon injection.
    factory()->set_use_beacon_results_in_filters(true);

    // Set up pcache for page.
    const PropertyCache::Cohort* cohort =
        SetupCohort(page_property_cache(), RewriteDriver::kBeaconCohort);
    server_context()->set_beacon_cohort(cohort);

    // Set up and register a beacon finder now that the pcache is configured.
    CriticalLineInfoFinder* finder = new BeaconCriticalLineInfoFinder(
        server_context()->beacon_cohort(), factory()->nonce_generator());
    server_context()->set_critical_line_info_finder(finder);

    options()->EnableFilter(RewriteOptions::kSplitHtml);
    rewrite_driver()->AddFilters();

    ResetDriver();
  }

  void ResetDriver() {
    rewrite_driver()->Clear();
    rewrite_driver()->SetUserAgent(
        UserAgentMatcherTestBase::kChrome18UserAgent);
    SetHtmlMimetype();  // Don't wrap scripts in <![CDATA[ ]]>
    rewrite_driver()->set_request_context(
        RequestContext::NewTestRequestContext(factory()->thread_system()));
    MockPropertyPage* page = NewMockPage(kTestDomain);
    rewrite_driver()->set_property_page(page);
    PropertyCache* pcache = server_context_->page_property_cache();
    pcache->Read(page);
  }

  void ValidateBeacon() {
    ParseUrl(kTestDomain, "");
    EXPECT_NE(GoogleString::npos, output_buffer_.find(BeaconScript()));
    // split_html will be disabled when we beacon, so the noscript redirect that
    // it enables won't be inserted.
    EXPECT_EQ(GoogleString::npos, output_buffer_.find("noscript"));
  }

  void ValidateNoBeacon() {
    ParseUrl(kTestDomain, "");
    EXPECT_EQ(GoogleString::npos,
              output_buffer_.find("pagespeed.splitHtmlBeaconInit"));
    // If we don't beacon, then a noscript tag will be inserted because
    // the split_html filter should be enabled.
    EXPECT_NE(GoogleString::npos, output_buffer_.find("noscript"));
  }

  void WriteToPropertyCache() {
    rewrite_driver()->property_page()->WriteCohort(
        rewrite_driver()
            ->server_context()
            ->critical_line_info_finder()
            ->cohort());
  }

  // Don't call this if a beacon isn't also being generated by rewriting (for
  // example, if you wanted to check that a beacon isn't being generated)
  // because then ExpectedNonce() will get out of sync.
  GoogleString BeaconScript() {
    GoogleString script =
        StrCat("");
    return script;
  }
};

TEST_F(SplitHtmlBeaconFilterTest, ScriptInjection) {
  ValidateBeacon();
}

TEST_F(SplitHtmlBeaconFilterTest, DontRebeaconBeforeTimeout) {
  ValidateBeacon();

  WriteToPropertyCache();
  ResetDriver();
  ValidateNoBeacon();

  int64 expiration_time_ms =
      std::min(options()->finder_properties_cache_expiration_time_ms(),
               options()->beacon_reinstrument_time_sec() * Timer::kSecondMs);
  factory()->mock_timer()->AdvanceMs(expiration_time_ms / 2);
  ResetDriver();
  ValidateNoBeacon();

  // Beacon injection happens when the pcache value expires.
  factory()->mock_timer()->AdvanceMs(expiration_time_ms / 2 + 1);
  ResetDriver();
  ValidateBeacon();
}

TEST_F(SplitHtmlBeaconFilterTest, DisabledForBots) {
  rewrite_driver()->SetUserAgent(UserAgentMatcherTestBase::kGooglebotUserAgent);
  ValidateNoBeacon();
}

}  // namespace net_instaweb


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace U2F.Server.Data
{
	public class SecurityKeyData : IEqualityComparer<SecurityKeyData>
	{
		public long EnrollmentTime { get; private set; }
		public byte[] KeyHandle { get; private set; }
		public byte[] PublicKey { get; private set; }
		public X509Certificate2 AttestationCert { get; set; }
		public int Counter { get; set; }

		public SecurityKeyData(
			long enrollmentTime,
			byte[] keyHandle,
			byte[] publicKey,
			X509Certificate2 attestationCert,
			int counter)
		{
			EnrollmentTime = enrollmentTime;
			KeyHandle = keyHandle;
			PublicKey = publicKey;
			AttestationCert = attestationCert;
			Counter = counter;
		}

		/**
   * When these keys were created/enrolled with the relying party.
   */
		public override String ToString()
		{
			return new StringBuilder()
				.Append("public_key: ")
				.Append(PublicKey.Base64Urlencode())
				.Append("\n")
				.Append("key_handle: ")
				.Append(KeyHandle.Base64Urlencode())
				.Append("\n")
				.Append("counter: ")
				.Append(Counter)
				.Append("\n")
				.Append("attestation certificate:\n")
				.Append(AttestationCert)
				.ToString();
		}

		public bool Equals(SecurityKeyData x, SecurityKeyData y)
		{
			if (x == y)
				return true;
			if (y == null)
				return false;
			if (!x.KeyHandle.SequenceEqual(y.KeyHandle))
				return false;
			if (!x.EnrollmentTime.Equals(y.EnrollmentTime))
				return false;
			if (!x.PublicKey.SequenceEqual(y.PublicKey))
				return false;
			if (! x.AttestationCert.Equals(y.AttestationCert))
				return false;

			return true;
		}

		public int GetHashCode(SecurityKeyData obj)
		{
			const int prime = 31;
			var result = 1;
			result = prime*result + EnrollmentTime.GetHashCode();
			result = prime*result + KeyHandle.GetHashCode();
			result = prime*result + PublicKey.GetHashCode();
			result = prime*result + AttestationCert.GetHashCode();

			return result;
		}
	}
}


text:
import * as Loadable from 'react-loadable'
import {Loading} from './loading'

const importer = () =>
  import('../main-menu' /* webpackChunkName: "menu-view" */)
    .then(mod => mod.Menu)

export const MenuView = Loadable({
  loader: importer,
  loading: Loading
})


text:
@implementation NSString (HTMLEntities)

- (NSString *)html_stringByEscapingForHTML
{
    NSMutableString *escaped = [self mutableCopy];
    void (^replace)() = ^(NSString *find, NSString *replace) {
        [escaped replaceOccurrencesOfString:find withString:replace options:0 range:NSMakeRange(0, escaped.length)];
    };
    replace(@"&", @"&");
    replace(@"\u00A0", @" ");
    replace(@"\"", @""");
    replace(@"<", @"<");
    replace(@">", @">");
    return escaped;
}

- (NSString *)html_stringByUnescapingHTML
{
    NSRange ampersand = [self rangeOfString:@"&" options:NSBackwardsSearch];
    if (ampersand.location == NSNotFound || NSMaxRange(ampersand) == self.length) return self;

    // These are expensive to create, so we'll lazily create them once per unescaping operation.
    NSCharacterSet *decimalDigitCharacterSet;
    NSCharacterSet *hexadecimalDigitCharacterSet;

    NSRange searchRange = NSMakeRange(0, self.length);
    NSScanner *scanner = [NSScanner scannerWithString:self];
    NSMutableString *unescaped = [self mutableCopy];
    do {
        searchRange.length = ampersand.location;

        NSString *replacement;

        // Numeric entity.
        scanner.scanLocation = NSMaxRange(ampersand);
        if ([scanner scanString:@"#" intoString:nil]) {

            UInt32 entity;

            // Hex number.
            if ([scanner scanString:@"x" intoString:nil]) {
                if (!hexadecimalDigitCharacterSet) {
                    hexadecimalDigitCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789ABCDEFabcdef"];
                }
                NSString *entityString;
                if ([scanner scanCharactersFromSet:hexadecimalDigitCharacterSet intoString:&entityString]) {
                    NSScanner *hexScanner = [NSScanner scannerWithString:entityString];
                    unsigned int hex;
                    [hexScanner scanHexInt:&hex];
                    entity = hex;
                } else {
                    continue;
                }
            }

            // Decimal number.
            else {
                if (!decimalDigitCharacterSet) {
                    decimalDigitCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
                }
                NSString *entityString;
                if ([scanner scanCharactersFromSet:decimalDigitCharacterSet intoString:&entityString]) {
                    NSInteger decimal = entityString.integerValue;
                    if (decimal > 0x10FFFF) {
                        entity = UINT32_MAX;
                    } else {
                        entity = (UInt32)decimal;
                    }
                } else {
                    continue;
                }
            }

            UTF32Char win1252Replacement = ReplacementForNumericEntity(entity);
            if (win1252Replacement) {
                entity = win1252Replacement;
            }

            if ((entity >= 0xD800 && entity <= 0xDFFF) || entity > 0x10FFFF) {
                entity = 0xFFFD;
            }

            replacement = StringWithLongCharacter(entity);

            // Optional semicolon.
            [scanner scanString:@";" intoString:nil];
        }

        // Named entity.
        else {
            NSRange nameRange = NSMakeRange(NSMaxRange(ampersand), LongestEntityNameLength);
            if (NSMaxRange(nameRange) > self.length) {
                nameRange.length = self.length - nameRange.location;
            }
            NSString *nameString = [self substringWithRange:nameRange];
            NSString *parsedEntity;
            replacement = StringForNamedEntity(nameString, &parsedEntity);
            if (replacement) {
                [scanner scanString:parsedEntity intoString:nil];
            } else {
                continue;
            }
        }

        [unescaped replaceCharactersInRange:NSMakeRange(ampersand.location, scanner.scanLocation - ampersand.location) withString:replacement];
    } while ((ampersand = [self rangeOfString:@"&" options:NSBackwardsSearch range:searchRange]).location != NSNotFound);
    return unescaped;
}

@end


text:
package org.horizontaldb.shard;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.horizontaldb.example.model.UserToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class ConversationRegistry {
	private static final Logger LOG = LoggerFactory.getLogger( ConversationRegistry.class );

	private final Object lock = new Object( );
	private Map<String, Boolean> conversationMap = new HashMap<>( );
	private Map<String, Set<Resource>> conversationResourceMap = new HashMap<>( );

	public void startConversation( UserToken userToken ) {
		synchronized ( lock ) {
			if ( !conversationMap.containsKey( userToken.getUserId( ) ) ) {
				conversationMap.put( userToken.getUserId( ), true );

				LOG.debug( String.format( "startConversation.%s=conversation started", userToken.getUserId( ) ) );
			} else {
				LOG.debug( String.format( "startConversation.%s=conversation already started", userToken.getUserId( ) ) );
			}
		}
	}

	public boolean hasConversation( String clientId ) {
		boolean retval = false;

		synchronized ( lock ) {
			retval = conversationMap.containsKey( clientId );
		}

		return retval;
	}

	public void teardownConversation( UserToken userToken ) {
		synchronized ( lock ) {
			if ( conversationMap.containsKey( userToken.getUserId( ) ) ) {
				releaseResources( userToken.getUserId( ) );

				conversationMap.remove( userToken.getUserId( ) );

				LOG.debug( String.format( "teardownConversation.%s=conversation torn down", userToken.getUserId( ) ) );
			} else {
				LOG.error( String.format( "teardownConversation.%s=client is not involved in a valid conversation", userToken.getUserId( ) ) );
			}
		}
	}

	public void addResource( String clientId, Object resource ) {
		if ( resource instanceof Resource ) {
			synchronized ( lock ) {
				if ( conversationMap.containsKey( clientId ) ) {
					Set<Resource> resourceSet = conversationResourceMap.get( clientId );

					if ( resourceSet == null ) {
						resourceSet = new HashSet<>( );

						conversationResourceMap.put( clientId, resourceSet );
					}

					if ( resourceSet.add( ( Resource ) resource ) ) {
						LOG.debug( String.format( "addResource.%s=resource registered", clientId ) );
					} else {
						LOG.debug( String.format( "addResource.%s=resource already registered", clientId ) );
					}
				} else {
					LOG.error( String.format( "addResource.%s=client is not involved in a valid conversation", clientId ) );
				}
			}
		}
	}

	private void releaseResources( String clientId ) {
		if ( conversationResourceMap.containsKey( clientId ) ) {
			Iterator<Resource> iterator = conversationResourceMap.get( clientId ).iterator( );

			while ( iterator.hasNext( ) ) {
				Resource resource = iterator.next( );

				try {
					resource.release( );
				} catch ( Exception ex ) {
					LOG.error( String.format( "releaseResource.%s=could not release dataSource [%s]", clientId, resource ), ex );
				}
			}

			conversationResourceMap.remove( clientId );
		}
	}

}


text:
package seedu.taskmanager.logic.commands;

import java.util.List;

import seedu.taskmanager.commons.core.Messages;
import seedu.taskmanager.commons.exceptions.IllegalValueException;
import seedu.taskmanager.commons.util.DateTimeUtil;
import seedu.taskmanager.logic.commands.exceptions.CommandException;
import seedu.taskmanager.model.task.EndDate;
import seedu.taskmanager.model.task.ReadOnlyTask;
import seedu.taskmanager.model.task.StartDate;
import seedu.taskmanager.model.task.Task;
import seedu.taskmanager.model.task.UniqueTaskList.DuplicateTaskException;

//@@author A0141102H
/**
 * Recurs an existing task in the task manager. Application is only able to
 * recur events and deadlines, floating task cannot be recurred.
 */
public class RecurringCommand extends Command {

    public static final String COMMAND_WORD = "RECUR";

    public static final String MESSAGE_USAGE = COMMAND_WORD + ": Recurs the entire task identified "
            + "by the index number used in the last task listing.\n" + "Parameters: INDEX NUMBER TYPEOFRECURRENCE\n"
            + "Example: " + COMMAND_WORD + " 1 4 days will result in task #1 being recurred everyday for 4 days"
            + "Example: " + COMMAND_WORD + " 3 3 weeks will result in task #3 being recurred on that date for 3 weeks";

    public static final String MESSAGE_DUPLICATE_TASK = "This task already exists in the task manager.";
    public static final String MESSAGE_RECURRING_TASK_SUCCESS = "Task has successfully recurred ";
    public static final String MESSAGE_RECURRING_FLOATING_TASK_FAILURE = "Unable to create recurring "
            + "task for floating task!";
    public static final String RECURRING_TASK_VALIDATION_REGEX = "\\d+\\s+\\d+\\s+[a-zA-Z]+";
    public static final String RECURRING_TASK_VALIDATION_REGEX2 = "[^\\s].*";
    public static final String EMPTY_FIELD = "EMPTY_FIELD";

    private final int taskListIndex;
    private final int numberOfRecurrence;
    private final String typeOfRecurrence;
    private Task recurringTask;

    public RecurringCommand(int taskListIndex, int numberOfRecurrence, String typeOfRecurrence) {
        assert taskListIndex > 0;
        this.taskListIndex = taskListIndex - 1;
        this.numberOfRecurrence = numberOfRecurrence;
        this.typeOfRecurrence = typeOfRecurrence;
    }

    public CommandResult execute() throws CommandException {

        List<ReadOnlyTask> lastShownList = model.getFilteredTaskList();

        if (taskListIndex >= lastShownList.size()) {
            throw new CommandException(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
        }

        ReadOnlyTask taskToRecur = lastShownList.get(taskListIndex);

        if (taskToRecur.isFloatingTask()) {
            throw new CommandException(MESSAGE_RECURRING_FLOATING_TASK_FAILURE);
        }

        if (taskToRecur.isDeadlineTask()) {

            for (int loop = 1; loop <= numberOfRecurrence; loop++) {

                try {
                    recurringTask = new Task(taskToRecur.getTaskName(), taskToRecur.getStartDate(),
                            taskToRecur.getStartTime(),
                            new EndDate(DateTimeUtil.getFutureDate(loop, typeOfRecurrence,
                                    taskToRecur.getEndDate().toString())),
                            taskToRecur.getEndTime(), false, taskToRecur.getCategories());
                } catch (IllegalValueException ive) {
                    throw new CommandException("Wrong format for deadline!");
                }

                if (DateTimeUtil.isValidDate(recurringTask.getEndDate().toString())) {
                    try {
                        model.addTask(recurringTask);
                    } catch (DuplicateTaskException dte) {
                        throw new CommandException(MESSAGE_DUPLICATE_TASK);
                    }
                }
            }
        }

        if (taskToRecur.isEventTask()) {
            for (int loop = 1; loop <= numberOfRecurrence; loop++) {
                try {
                    recurringTask = new Task(taskToRecur.getTaskName(),
                            new StartDate(DateTimeUtil.getFutureDate(loop, typeOfRecurrence,
                                    taskToRecur.getStartDate().toString())),
                            taskToRecur.getStartTime(),
                            new EndDate(DateTimeUtil.getFutureDate(loop, typeOfRecurrence,
                                    taskToRecur.getEndDate().toString())),
                            taskToRecur.getEndTime(), false, taskToRecur.getCategories());
                } catch (IllegalValueException ive) {
                    throw new CommandException("Wrong format for event!");
                }

                if (DateTimeUtil.isValidDate(recurringTask.getStartDate().toString())
                        && DateTimeUtil.isValidDate(recurringTask.getEndDate().toString())) {
                    try {
                        model.addTask(recurringTask);
                    } catch (DuplicateTaskException dte) {
                        throw new CommandException(MESSAGE_DUPLICATE_TASK);
                    }
                }

            }
        }

        model.updateFilteredListToShowAll();
        return new CommandResult(
                String.format(MESSAGE_RECURRING_TASK_SUCCESS, String.valueOf(numberOfRecurrence), " number of times"));
    }
}


text:
var parseScript = function(_source) {

	var source = _source;
		var scripts = new Array();

		while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
			var s = source.indexOf("<script");
			var s_e = source.indexOf(">", s);
			var e = source.indexOf("</script", s);
			var e_e = source.indexOf(">", e);

			// Add to scripts array
			scripts.push(source.substring(s_e+1, e));
			// Strip from source
			source = source.substring(0, s) + source.substring(e_e+1);
		}

		// Loop through every script collected and eval it
		for(var i=0; i<scripts.length; i++) {
			try {
				eval(scripts[i]);
			}catch(ex) {}

		      }

		// Return the cleaned source
		return source;

}


text:
Trogdir API Client [![Build Status](https://travis-ci.org/biola/trogdir-api-client.svg?branch=master)](https://travis-ci.org/biola/trogdir-api-client)
==================

Installing
----------

Add `gem 'trogdir_api_client'` to your `Gemfile` and run `bundle`

Configuration
-------------

```ruby
TrogdirAPIClient.configure do |config|
  # Optional:
  # config.scheme = 'http'
  # config.host = 'localhost'
  # config.script_name = nil
  # config.version = 'v1'

  # Required:
  config.access_id = '**************'
  config.secret_key = '*****************************************'
end
```

Usage
-----

### Example Syncinator

```ruby
require 'trogdir_api_client'
require 'multi_json'

trogdir = Trogdir::APIClient::ChangeSyncs.new
hashes = trogdir.start.perform.parse

hashes.each do |hash|
  sync_log_id = hash['sync_log_id']
  action = hash['action']
  person_id = hash['person_id']
  scope = hash['scope']
  original = hash['original']
  modified = hash['modified']

  action_taken = 'nothing'

  begin
    person = Person.find(person_id)

    case scope
    when 'person'
      case action
      when 'create'
        # do stuff
        action_taken = 'create'
      when 'update'
        # do stuff
        action_taken = 'update'
      when 'destroy'
        # do stuff
        action_taken = 'destroy'
      end
    when 'id'
      case action
      when 'create'
        # do stuff
        action_taken = 'create'
      when 'update'
        # do stuff
        action_taken = 'update'
      when 'destroy'
        # do stuff
        action_taken = 'destroy'
      end
    when 'email'
      # blah
    when 'photo'
      # blah
    when 'phone'
      # blah
    when 'address'
      # blah
    end

    trogdir.finish(sync_log_id: sync_log_id, action: action_taken).perform
  rescue StandardError => err
    trogdir.error(sync_log_id: sync_log_id, message: err.message).perform
  end
end
```

License
-------

MIT


text:
Spree::ContentController.class_eval do
  after_filter :fire_visited_path, :only => :show
  after_filter :fire_visited_action, :except => :show

  def fire_visited_path
    fire_event('spree.content.visited', :path => "content/#{params[:path]}")
  end

  def fire_visited_action
    fire_event('spree.content.visited', :path => "content/#{params[:action]}")
  end

end


text:
// Copyright © 2016-2019 Andy Goryachev <andy@goryachev.com>
package goryachev.fx;
import javafx.scene.Node;
import javafx.scene.control.MenuItem;

/**
 * CMenuItem.
 */
public class FxMenuItem
	extends MenuItem
{
	public FxMenuItem(String text, Node icon, FxAction a)
	{
		super(text);
		a.attach(this);
		setGraphic(icon);
	}

	public FxMenuItem(Node icon, FxAction a)
	{
		a.attach(this);
		setGraphic(icon);
	}

	public FxMenuItem(String text, FxAction a)
	{
		super(text);
		a.attach(this);
	}

	public FxMenuItem(String text, Runnable r)
	{
		super(text);
		new FxAction(r).attach(this);
	}

	public FxMenuItem(String text)
	{
		super(text);
		setDisable(true);
	}
}


text:
// ReSharper disable All

namespace OpenTl.Schema
{
	using System;
	using System.Collections;
	using System.Text;

	using OpenTl.Schema;
	using OpenTl.Schema.Serialization.Attributes;

	[Serialize(0xe31c34d8)]
	public sealed class TChannelAdminLogEventActionParticipantInvite : IChannelAdminLogEventAction
	{
       [SerializationOrder(0)]
       public OpenTl.Schema.IChannelParticipant Participant {get; set;}

	}
}


text:
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { ToastyModule } from 'ng2-toasty';
import { AuthRoutingModule, authRoutingComponents } from './auth-routing.module';
import { AuthService } from './auth.service';

@NgModule({
  imports: [ CommonModule, FormsModule, ReactiveFormsModule,
  AuthRoutingModule, ToastyModule.forRoot() ],
  declarations: [ authRoutingComponents ],
  exports: [
    CommonModule, FormsModule, AuthRoutingModule,
    authRoutingComponents
   ],
   providers: [ AuthService ]
})

export class AuthModule {
}


text:
import csv
import cffi

# IN-PROGRESS.  See the demo at the end of the file

def _make_ffi_from_dialect(dialect_name):
    dialect = csv.get_dialect(dialect_name)

    ffi = cffi.FFI()

    ffi.cdef("""
        long parse_line(char *rawline, long inputlength);
    """)

    d = {'quotechar': ord(dialect.quotechar),
         'quoting': int(dialect.quoting),
         'skipinitialspace': int(dialect.skipinitialspace),
         'delimiter': ord(dialect.delimiter),
         'doublequote': int(dialect.doublequote),
         'strict': int(dialect.strict),
         }
    if dialect.escapechar is not None:
        d['is_escape_char'] = '== %d' % ord(dialect.escapechar)
    else:
        d['is_escape_char'] = '&& 0'

    ffi.set_source('_fastcsv_' + dialect_name, r'''

    typedef enum {
        START_RECORD, START_FIELD, ESCAPED_CHAR, IN_FIELD,
        IN_QUOTED_FIELD, ESCAPE_IN_QUOTED_FIELD, QUOTE_IN_QUOTED_FIELD,
        EAT_CRNL
    } ParserState;

    typedef enum {
        QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE
    } QuoteStyle;

    typedef struct {
        ParserState state;          /* current CSV parse state */
        char *field;                /* build current field in here */
        int field_size;             /* size of allocated buffer */
        int field_len;              /* length of current field */
        int numeric_field;          /* treat field as numeric */
    } ReaderObj;

    static void
    parse_add_char(ReaderObj *self, char c)
    {
        *self->field++ = c;
    }

    static void
    parse_save_field(ReaderObj *self)
    {
        *self->field++ = 0;
    }

    static int
    parse_process_char(ReaderObj *self, char c)
    {
        switch (self->state) {
        case START_RECORD:
            /* start of record */
            if (c == '\0')
                /* empty line - return [] */
                break;
            else if (c == '\n' || c == '\r') {
                self->state = EAT_CRNL;
                break;
            }
            /* normal character - handle as START_FIELD */
            self->state = START_FIELD;
            /* fallthru */
        case START_FIELD:
            /* expecting field */
            if (c == '\n' || c == '\r' || c == '\0') {
                /* save empty field - return [fields] */
                parse_save_field(self);
                self->state = (c == '\0' ? START_RECORD : EAT_CRNL);
            }
            else if (c == %(quotechar)d &&
                     %(quoting)d != QUOTE_NONE) {
                /* start quoted field */
                self->state = IN_QUOTED_FIELD;
            }
            else if (c %(is_escape_char)s) {
                /* possible escaped character */
                self->state = ESCAPED_CHAR;
            }
            else if (c == ' ' && %(skipinitialspace)d)
                /* ignore space at start of field */
                ;
            else if (c == %(delimiter)d) {
                /* save empty field */
                parse_save_field(self);
            }
            else {
                /* begin new unquoted field */
                if (%(quoting)d == QUOTE_NONNUMERIC)
                    self->numeric_field = 1;
                parse_add_char(self, c);
                self->state = IN_FIELD;
            }
            break;

        case ESCAPED_CHAR:
            if (c == '\0')
                c = '\n';
            parse_add_char(self, c);
            self->state = IN_FIELD;
            break;

        case IN_FIELD:
            /* in unquoted field */
            if (c == '\n' || c == '\r' || c == '\0') {
                /* end of line - return [fields] */
                parse_save_field(self);
                self->state = (c == '\0' ? START_RECORD : EAT_CRNL);
            }
            else if (c %(is_escape_char)s) {
                /* possible escaped character */
                self->state = ESCAPED_CHAR;
            }
            else if (c == %(delimiter)d) {
                /* save field - wait for new field */
                parse_save_field(self);
                self->state = START_FIELD;
            }
            else {
                /* normal character - save in field */
                parse_add_char(self, c);
            }
            break;

        case IN_QUOTED_FIELD:
            /* in quoted field */
            if (c == '\0')
                ;
            else if (c %(is_escape_char)s) {
                /* Possible escape character */
                self->state = ESCAPE_IN_QUOTED_FIELD;
            }
            else if (c == %(quotechar)d &&
                     %(quoting)d != QUOTE_NONE) {
                if (%(doublequote)d) {
                    /* doublequote; " represented by "" */
                    self->state = QUOTE_IN_QUOTED_FIELD;
                }
                else {
                    /* end of quote part of field */
                    self->state = IN_FIELD;
                }
            }
            else {
                /* normal character - save in field */
                parse_add_char(self, c);
            }
            break;

        case ESCAPE_IN_QUOTED_FIELD:
            if (c == '\0')
                c = '\n';
            parse_add_char(self, c);
            self->state = IN_QUOTED_FIELD;
            break;

        case QUOTE_IN_QUOTED_FIELD:
            /* doublequote - seen a quote in an quoted field */
            if (%(quoting)d != QUOTE_NONE &&
                c == %(quotechar)d) {
                /* save "" as " */
                parse_add_char(self, c);
                self->state = IN_QUOTED_FIELD;
            }
            else if (c == %(delimiter)d) {
                /* save field - wait for new field */
                parse_save_field(self);
                self->state = START_FIELD;
            }
            else if (c == '\n' || c == '\r' || c == '\0') {
                /* end of line - return [fields] */
                parse_save_field(self);
                self->state = (c == '\0' ? START_RECORD : EAT_CRNL);
            }
            else if (!%(strict)d) {
                parse_add_char(self, c);
                self->state = IN_FIELD;
            }
            else {
                /* illegal */
                /*PyErr_Format(error_obj, "'%%c' expected after '%%c'",
                                dialect->delimiter,
                                dialect->quotechar);*/
                return -1;
            }
            break;

        case EAT_CRNL:
            if (c == '\n' || c == '\r')
                ;
            else if (c == '\0')
                self->state = START_RECORD;
            else {
                /*PyErr_Format(error_obj, "new-line character seen in unquoted field - do you need to open the file in universal-newline mode?");*/
                return -1;
            }
            break;

        }
        return 0;
    }

    static void
    parse_reset(ReaderObj *self, char *rawline)
    {
        self->field = rawline;
        self->state = START_RECORD;
        self->numeric_field = 0;
    }

    long parse_line(char *rawline, long inputlength)
    {
        char *p;
        ReaderObj reader;
        parse_reset(&reader, rawline);

        for (p=rawline; inputlength > 0; inputlength--, p++) {
            if (parse_process_char(&reader, *p) < 0)
                return -1;
        }
        if (parse_process_char(&reader, 0) < 0)
            return -1;
        return reader.field - rawline - 1;
    }
    ''' % d)

    ffi.compile()

def fastcsv_reader(f, dialect_name):
    try:
        module = __import__('_fastcsv_' + dialect_name)
    except ImportError:
        _make_ffi_from_dialect(dialect_name)
        module = __import__('_fastcsv_' + dialect_name)
    ffi, lib = module.ffi, module.lib
    #
    linelen = -1
    for line in f:
        if linelen <= len(line):
            linelen = 2 * len(line)
            rawline = ffi.new("char[]", linelen)
        ffi.buffer(rawline, len(line))[:] = line
        n = lib.parse_line(rawline, len(line))
        assert n >= 0
        yield ffi.buffer(rawline, n)[:].split('\x00')

if __name__ == '__main__':
    csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)
    with open('/etc/passwd', 'rb') as f:
        reader = fastcsv_reader(f, 'unixpwd')
        for row in reader:
            print row