text:
package frclibj;

import edu.wpi.first.wpilibj.Timer;

public class TrcDbgTrace
{
    public static final String ESC_PREFIX       = "\u001b[";
    public static final String ESC_SUFFIX       = "m";
    public static final String ESC_SEP          = ";";

    public static final String SGR_RESET        = "0";
    public static final String SGR_BRIGHT       = "1";
    public static final String SGR_DIM          = "2";
    public static final String SGR_ITALIC       = "3";
    public static final String SGR_UNDERLINE    = "4";
    public static final String SGR_BLINKSLOW    = "5";
    public static final String SGR_BLINKFAST    = "6";
    public static final String SGR_REVERSE      = "7";
    public static final String SGR_HIDDEN       = "8";
    public static final String SGR_CROSSEDOUT   = "9";

    public static final String SGR_FG_BLACK     = "30";
    public static final String SGR_FG_RED       = "31";
    public static final String SGR_FG_GREEN     = "32";
    public static final String SGR_FG_YELLOW    = "33";
    public static final String SGR_FG_BLUE      = "34";
    public static final String SGR_FG_MAGENTA   = "35";
    public static final String SGR_FG_CYAN      = "36";
    public static final String SGR_FG_WHITE     = "37";

    public static final String SGR_BG_BLACK     = "40";
    public static final String SGR_BG_RED       = "41";
    public static final String SGR_BG_GREEN     = "42";
    public static final String SGR_BG_YELLOW    = "43";
    public static final String SGR_BG_BLUE      = "44";
    public static final String SGR_BG_MAGENTA   = "45";
    public static final String SGR_BG_CYAN      = "46";
    public static final String SGR_BG_WHITE     = "47";

    public static final String ESC_NORMAL       = ESC_PREFIX
                                                    + ESC_SUFFIX;
    public static final String ESC_BLINKSLOW    = ESC_PREFIX
                                                    + SGR_BLINKSLOW
                                                    + ESC_SUFFIX;
    public static final String ESC_BLINKFAST    = ESC_PREFIX
                                                    + SGR_BLINKFAST
                                                    + ESC_SUFFIX;

    public static final String ESC_FG_BLACK     = ESC_PREFIX
                                                    + SGR_FG_BLACK
                                                    + ESC_SUFFIX;
    public static final String ESC_FG_RED       = ESC_PREFIX
                                                    + SGR_FG_RED
                                                    + ESC_SUFFIX;
    public static final String ESC_FG_GREEN     = ESC_PREFIX
                                                    + SGR_FG_GREEN
                                                    + ESC_SUFFIX;
    public static final String ESC_FG_YELLOW    = ESC_PREFIX
                                                    + SGR_FG_YELLOW
                                                    + ESC_SUFFIX;
    public static final String ESC_FG_BLUE      = ESC_PREFIX
                                                    + SGR_FG_BLUE
                                                    + ESC_SUFFIX;
    public static final String ESC_FG_MAGENTA   = ESC_PREFIX
                                                    + SGR_FG_MAGENTA
                                                    + ESC_SUFFIX;
    public static final String ESC_FG_CYAN      = ESC_PREFIX
                                                    + SGR_FG_CYAN
                                                    + ESC_SUFFIX;
    public static final String ESC_FG_WHITE     = ESC_PREFIX
                                                    + SGR_FG_WHITE
                                                    + ESC_SUFFIX;

    public static final String ESC_BG_BLACK     = ESC_PREFIX
                                                    + SGR_BG_BLACK
                                                    + ESC_SUFFIX;
    public static final String ESC_BG_RED       = ESC_PREFIX
                                                    + SGR_BG_RED
                                                    + ESC_SUFFIX;
    public static final String ESC_BG_GREEN     = ESC_PREFIX
                                                    + SGR_BG_GREEN
                                                    + ESC_SUFFIX;
    public static final String ESC_BG_YELLOW    = ESC_PREFIX
                                                    + SGR_BG_YELLOW
                                                    + ESC_SUFFIX;
    public static final String ESC_BG_BLUE      = ESC_PREFIX
                                                    + SGR_BG_BLUE
                                                    + ESC_SUFFIX;
    public static final String ESC_BG_MAGENTA   = ESC_PREFIX
                                                    + SGR_BG_MAGENTA
                                                    + ESC_SUFFIX;
    public static final String ESC_BG_CYAN      = ESC_PREFIX
                                                    + SGR_BG_CYAN
                                                    + ESC_SUFFIX;
    public static final String ESC_BG_WHITE     = ESC_PREFIX
                                                    + SGR_BG_WHITE
                                                    + ESC_SUFFIX;

    public static final String ESC_FGB_BLACK    = ESC_PREFIX
                                                    + SGR_FG_BLACK
                                                    + ESC_SEP
                                                    + SGR_BRIGHT
                                                    + ESC_SUFFIX;
    public static final String ESC_FGB_RED      = ESC_PREFIX
                                                    + SGR_FG_RED
                                                    + ESC_SEP
                                                    + SGR_BRIGHT
                                                    + ESC_SUFFIX;
    public static final String ESC_FGB_GREEN    = ESC_PREFIX
                                                    + SGR_FG_GREEN
                                                    + ESC_SEP
                                                    + SGR_BRIGHT
                                                    + ESC_SUFFIX;
    public static final String ESC_FGB_YELLOW   = ESC_PREFIX
                                                    + SGR_FG_YELLOW
                                                    + ESC_SEP
                                                    + SGR_BRIGHT
                                                    + ESC_SUFFIX;
    public static final String ESC_FGB_BLUE     = ESC_PREFIX
                                                    + SGR_FG_BLUE
                                                    + ESC_SEP
                                                    + SGR_BRIGHT
                                                    + ESC_SUFFIX;
    public static final String ESC_FGB_MAGENTA  = ESC_PREFIX
                                                    + SGR_FG_MAGENTA
                                                    + ESC_SEP
                                                    + SGR_BRIGHT
                                                    + ESC_SUFFIX;
    public static final String ESC_FGB_CYAN     = ESC_PREFIX
                                                    + SGR_FG_CYAN
                                                    + ESC_SEP
                                                    + SGR_BRIGHT
                                                    + ESC_SUFFIX;
    public static final String ESC_FGB_WHITE    = ESC_PREFIX
                                                    + SGR_FG_WHITE
                                                    + ESC_SEP
                                                    + SGR_BRIGHT
                                                    + ESC_SUFFIX;

    public static final String ESC_BGB_BLACK    = ESC_PREFIX
                                                    + SGR_BG_BLACK
                                                    + ESC_SEP
                                                    + SGR_BRIGHT
                                                    + ESC_SUFFIX;
    public static final String ESC_BGB_RED      = ESC_PREFIX
                                                    + SGR_BG_RED
                                                    + ESC_SEP
                                                    + SGR_BRIGHT
                                                    + ESC_SUFFIX;
    public static final String ESC_BGB_GREEN    = ESC_PREFIX
                                                    + SGR_BG_GREEN
                                                    + ESC_SEP
                                                    + SGR_BRIGHT
                                                    + ESC_SUFFIX;
    public static final String ESC_BGB_YELLOW   = ESC_PREFIX
                                                    + SGR_BG_YELLOW
                                                    + ESC_SEP
                                                    + SGR_BRIGHT
                                                    + ESC_SUFFIX;
    public static final String ESC_BGB_BLUE     = ESC_PREFIX
                                                    + SGR_BG_BLUE
                                                    + ESC_SEP
                                                    + SGR_BRIGHT
                                                    + ESC_SUFFIX;
    public static final String ESC_BGB_MAGENTA  = ESC_PREFIX
                                                    + SGR_BG_MAGENTA
                                                    + ESC_SEP
                                                    + SGR_BRIGHT
                                                    + ESC_SUFFIX;
    public static final String ESC_BGB_CYAN     = ESC_PREFIX
                                                    + SGR_BG_CYAN
                                                    + ESC_SEP
                                                    + SGR_BRIGHT
                                                    + ESC_SUFFIX;
    public static final String ESC_BGB_WHITE    = ESC_PREFIX
                                                    + SGR_BG_WHITE
                                                    + ESC_SEP
                                                    + SGR_BRIGHT
                                                    + ESC_SUFFIX;

    public static enum TraceLevel
    {
        QUIET(0),
        INIT(1),
        API(2),
        CALLBK(3),
        EVENT(4),
        FUNC(5),
        TASK(6),
        UTIL(7),
        HIFREQ(8);

        private int value;

        TraceLevel(int value)
        {
            this.value = value;
        }   //TraceLevel

        public int getValue()
        {
            return this.value;
        }   //getValue

    }   //enum TraceLevel

    public static enum MsgLevel
    {
        FATAL(1),
        ERR(2),
        WARN(3),
        INFO(4),
        VERBOSE(5);

        private int value;

        MsgLevel(int value)
        {
            this.value = value;
        }   //MsgLevel

        public int getValue()
        {
            return this.value;
        }   //getValue

    }   //enum MsgLevel

    private static int indentLevel = 0;

    private String instanceName;
    private boolean traceEnabled;
    private TraceLevel traceLevel;
    private MsgLevel msgLevel;
    private double nextTraceTime;

    public void setDbgTraceConfig(
            boolean traceEnabled,
            TraceLevel traceLevel,
            MsgLevel msgLevel)
    {
        this.traceEnabled = traceEnabled;
        this.traceLevel = traceLevel;
        this.msgLevel = msgLevel;
    }   //setDbgTraceConfig

    public TrcDbgTrace(
            final String instanceName,
            boolean traceEnabled,
            TraceLevel traceLevel,
            MsgLevel msgLevel)
    {
        this.instanceName = instanceName;
        setDbgTraceConfig(traceEnabled, traceLevel, msgLevel);
        this.nextTraceTime = Timer.getFPGATimestamp();
    }   //TrcDbgTrace

    public void traceEnter(
            final String funcName,
            final TraceLevel funcLevel,
            final String format,
            Object... args)
    {
        if (traceEnabled &&
            funcLevel.getValue() <= traceLevel.getValue())
        {
            printTracePrefix(funcName, true, false);
            System.out.printf(format, args);
            System.out.print(")\n" + ESC_NORMAL);
        }
    }   //traceEnter

    public void traceEnter(
            final String funcName,
            final TraceLevel funcLevel)
    {
        if (traceEnabled &&
            funcLevel.getValue() <= traceLevel.getValue())
        {
            printTracePrefix(funcName, true, true);
        }
    }   //traceEnter

    public void traceExit(
            final String funcName,
            final TraceLevel funcLevel,
            final String format,
            Object... args)
    {
        if (traceEnabled &&
            funcLevel.getValue() <= traceLevel.getValue())
        {
            printTracePrefix(funcName, false, false);
            System.out.printf(format, args);
            System.out.print("\n" + ESC_NORMAL);
        }
    }   //traceExitMsg

    public void traceExit(
            final String funcName,
            final TraceLevel funcLevel)
    {
        if (traceEnabled &&
            funcLevel.getValue() <= traceLevel.getValue())
        {
            printTracePrefix(funcName, false, true);
        }
    }   //traceExit

    public void traceFatal(
            final String funcName,
            final String format,
            Object... args)
    {
        traceMsg(funcName, MsgLevel.FATAL, 0.0, format, args);
    }   //traceFatal

    public void traceErr(
            final String funcName,
            final String format,
            Object... args)
    {
        traceMsg(funcName, MsgLevel.ERR, 0.0, format, args);
    }   //traceErr

    public void traceWarn(
            final String funcName,
            final String format,
            Object... args)
    {
        traceMsg(funcName, MsgLevel.WARN, 0.0, format, args);
    }   //traceWarn

    public void traceInfo(
            final String funcName,
            final String format,
            Object... args)
    {
        traceMsg(funcName, MsgLevel.INFO, 0.0, format, args);
    }   //traceInfo

    public void traceVerbose(
            final String funcName,
            final String format,
            Object... args)
    {
        traceMsg(funcName, MsgLevel.VERBOSE, 0.0, format, args);
    }   //traceVerbose

    public void tracePeriodic(
            final String funcName,
            double traceInterval,
            final String format,
            Object... args)
    {
        traceMsg(funcName, MsgLevel.INFO, traceInterval, format, args);
    }   //tracePeriodic

    private void traceMsg(
            final String funcName,
            MsgLevel level,
            double traceInterval,
            final String format,
            Object... args)
    {
        if (level.getValue() <= msgLevel.getValue())
        {
            double currTime = Timer.getFPGATimestamp();
            if (currTime >= nextTraceTime)
            {
                nextTraceTime = currTime + traceInterval;
                printMsgPrefix(funcName, level);
                System.out.printf(format, args);
                System.out.print("\n" + ESC_NORMAL);
            }
        }
    }   //traceMsg

    private void printTracePrefix(
            final String funcName,
            boolean enter,
            boolean newline)
    {
        if (enter)
        {
            indentLevel++;
        }

        System.out.print(ESC_FGB_MAGENTA);
        for (int i = 0; i < indentLevel; i++)
        {
            System.out.print("| ");
        }

        System.out.print(instanceName + "." + funcName);

        if (enter)
        {
            System.out.print(newline? "()\n": "(");
        }
        else
        {
            System.out.print(newline? "!\n" + ESC_NORMAL: "");
            indentLevel--;
        }
    }   //printTracePrefix

    private void printMsgPrefix(
            final String funcName,
            MsgLevel level)
    {
        String prefix;
        String color;

        switch (level)
        {
        case FATAL:
            prefix = "_Fatal: ";
            color = ESC_PREFIX + SGR_FG_YELLOW +
                    ESC_SEP + SGR_BRIGHT +
                    ESC_SEP + SGR_BG_RED +
                    ESC_SUFFIX;
            break;

        case ERR:
            prefix = "_Err: ";
            color = ESC_FGB_RED;
            break;

        case WARN:
            prefix = "_Warn: ";
            color = ESC_FGB_YELLOW;
            break;

        case INFO:
            prefix = "_Info: ";
            color = ESC_FGB_GREEN;
            break;

        case VERBOSE:
            prefix = "_Verbose: ";
            color = ESC_FGB_WHITE;
            break;

        default:
            prefix = "_Unk: ";
            color = ESC_NORMAL;
            break;
        }

        System.out.print(color + instanceName + "." + funcName + prefix);
    }   //printMsgPrefix

}   //class TrcDbgTrace


text:
package org.apache.cassandra.simulator.asm;

import java.io.IOException;
import java.io.InputStream;
import java.lang.instrument.ClassDefinition;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.function.BiFunction;
import java.util.regex.Pattern;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;

import static org.apache.cassandra.simulator.asm.Flag.DETERMINISTIC;
import static org.apache.cassandra.simulator.asm.Flag.LOCK_SUPPORT;
import static org.apache.cassandra.simulator.asm.Flag.NO_PROXY_METHODS;
import static org.apache.cassandra.simulator.asm.InterceptClasses.BYTECODE_VERSION;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.GETFIELD;
import static org.objectweb.asm.Opcodes.GETSTATIC;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.IRETURN;
import static org.objectweb.asm.Opcodes.RETURN;

/**
 * A mechanism for weaving classes loaded by the bootstrap classloader that we cannot override.
 * The design supports weaving of the internals of these classes, and in future we may want to
 * weave LockSupport or the internals of other blocking concurrency primitives.
 *
 * Ultimately this wasn't necessary for the initial functionality, but we have maintained
 * the layout so that it will be easier to enable such functionality in future should it be needed.
 *
 * To this end, the asm package and simulator-asm.jar is as self-contained set of classes for performing
 * simulator byteweaving, and simulator-bootstrap.jar contains a self-contained class and interface for
 * replacing important system methods.
 */
public class InterceptAgent
{
    public static void premain(final String agentArgs, final Instrumentation instrumentation) throws UnmodifiableClassException, ClassNotFoundException, IOException
    {
        setup(agentArgs, instrumentation);
    }

    public void agentmain(final String agentArgs, final Instrumentation instrumentation) throws UnmodifiableClassException, ClassNotFoundException, IOException
    {
        setup(agentArgs, instrumentation);
    }

    private static void setup(final String agentArgs, final Instrumentation instrumentation) throws UnmodifiableClassException, ClassNotFoundException, IOException
    {
        instrumentation.addTransformer(new ClassFileTransformer()
        {
            @Override
            public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] bytecode) throws IllegalClassFormatException
            {
                if (className == null)
                    return null;

                if (className.equals("java/lang/Object"))
                    return transformObject(bytecode);

                if (className.equals("java/lang/Enum"))
                    return transformEnum(bytecode);

                if (className.equals("java/util/Random"))
                    return transformRandom(bytecode);

                if (className.equals("java/util/concurrent/ThreadLocalRandom"))
                    return transformThreadLocalRandom(bytecode);

                if (className.startsWith("java/util/concurrent/ConcurrentHashMap"))
                    return transformConcurrent(className, bytecode, DETERMINISTIC, NO_PROXY_METHODS);

                if (className.startsWith("java/util/concurrent/locks"))
                    return transformConcurrent(className, bytecode, LOCK_SUPPORT, NO_PROXY_METHODS);

                return null;
            }
        });

        Pattern reloadPattern = Pattern.compile("java\\.(lang\\.Enum|util\\.concurrent\\.(locks\\..*|ConcurrentHashMap)|util\\.(concurrent\\.ThreadLocal)?Random|lang\\.Object)");
        List<ClassDefinition> redefine = new ArrayList<>();
        for (Class<?> loadedClass : instrumentation.getAllLoadedClasses())
        {
            if (reloadPattern.matcher(loadedClass.getName()).matches())
                redefine.add(new ClassDefinition(loadedClass, readDefinition(loadedClass)));
        }
        if (!redefine.isEmpty())
            instrumentation.redefineClasses(redefine.toArray(new ClassDefinition[0]));
    }

    private static byte[] readDefinition(Class<?> clazz) throws IOException
    {
        return readDefinition(clazz.getName().replaceAll("\\.", "/"));
    }

    private static byte[] readDefinition(String className) throws IOException
    {
        byte[] bytes = new byte[1024];
        try (InputStream in = ClassLoader.getSystemResourceAsStream(className + ".class"))
        {
            int count = 0;
            while (true)
            {
                int add = in.read(bytes, count, bytes.length - count);
                if (add < 0)
                    break;
                if (add == 0)
                    bytes = Arrays.copyOf(bytes, bytes.length * 2);
                count += add;
            }
            return Arrays.copyOf(bytes, count);
        }
    }

    /**
     * We don't want Object.toString() to invoke our overridden identityHashCode by virtue of invoking some overridden hashCode()
     * So we overwrite Object.toString() to replace calls to Object.hashCode() with direct calls to System.identityHashCode()
     */
    private static byte[] transformObject(byte[] bytes)
    {
        class ObjectVisitor extends ClassVisitor
        {
            public ObjectVisitor(int api, ClassVisitor classVisitor)
            {
                super(api, classVisitor);
            }

            @Override
            public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions)
            {
                if (descriptor.equals("()Ljava/lang/String;") && name.equals("toString"))
                    return Utils.deterministicToString(super.visitMethod(access, name, descriptor, signature, exceptions));
                else
                    return super.visitMethod(access, name, descriptor, signature, exceptions);
            }
        }
        return transform(bytes, ObjectVisitor::new);
    }

    /**
     * We want Enum to have a deterministic hashCode() so we simply forward calls to ordinal()
     */
    private static byte[] transformEnum(byte[] bytes)
    {
        class EnumVisitor extends ClassVisitor
        {
            public EnumVisitor(int api, ClassVisitor classVisitor)
            {
                super(api, classVisitor);
            }

            @Override
            public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions)
            {
                if (descriptor.equals("()I") && name.equals("hashCode"))
                {
                    MethodVisitor visitor = super.visitMethod(access, name, descriptor, signature, exceptions);
                    visitor.visitLabel(new Label());
                    visitor.visitIntInsn(ALOAD, 0);
                    visitor.visitFieldInsn(GETFIELD, "java/lang/Enum", "ordinal", "I");
                    visitor.visitInsn(IRETURN);
                    visitor.visitLabel(new Label());
                    visitor.visitMaxs(1, 1);
                    visitor.visitEnd();

                    return new MethodVisitor(BYTECODE_VERSION) {};
                }
                else
                {
                    return super.visitMethod(access, name, descriptor, signature, exceptions);
                }
            }
        }
        return transform(bytes, EnumVisitor::new);
    }

    /**
     * We want Random to be initialised deterministically, so we modify the default constructor to fetch
     * some deterministically generated seed to pass to its seed constructor
     */
    private static byte[] transformRandom(byte[] bytes)
    {
        class RandomVisitor extends ClassVisitor
        {
            public RandomVisitor(int api, ClassVisitor classVisitor)
            {
                super(api, classVisitor);
            }

            @Override
            public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions)
            {
                if (descriptor.equals("()V") && name.equals("<init>"))
                {
                    MethodVisitor visitor = super.visitMethod(access, name, descriptor, signature, exceptions);
                    visitor.visitLabel(new Label());
                    visitor.visitIntInsn(ALOAD, 0);
                    visitor.visitMethodInsn(INVOKESTATIC, "org/apache/cassandra/simulator/systems/InterceptorOfSystemMethods$Global", "randomSeed", "()J", false);
                    visitor.visitMethodInsn(INVOKESPECIAL, "java/util/Random", "<init>", "(J)V", false);
                    visitor.visitInsn(RETURN);
                    visitor.visitLabel(new Label());
                    visitor.visitMaxs(3, 1);
                    visitor.visitEnd();

                    return new MethodVisitor(BYTECODE_VERSION) {};
                }
                else
                {
                    return super.visitMethod(access, name, descriptor, signature, exceptions);
                }
            }
        }
        return transform(bytes, RandomVisitor::new);
    }

    /**
     * We require ThreadLocalRandom to be deterministic, so we modify its initialisation method to invoke a
     * global deterministic random value generator
     */
    private static byte[] transformThreadLocalRandom(byte[] bytes)
    {
        class ThreadLocalRandomVisitor extends ClassVisitor
        {
            public ThreadLocalRandomVisitor(int api, ClassVisitor classVisitor)
            {
                super(api, classVisitor);
            }

            String unsafeDescriptor;
            String unsafeFieldName;

            @Override
            public FieldVisitor visitField(int access, String name, String descriptor, String signature, Object value)
            {
                if (descriptor.equals("Lsun/misc/Unsafe;") || descriptor.equals("Ljdk/internal/misc/Unsafe;"))
                {
                    unsafeFieldName = name;
                    unsafeDescriptor = descriptor;
                }
                return super.visitField(access, name, descriptor, signature, value);
            }

            @Override
            public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions)
            {
                if (descriptor.equals("()V") && name.equals("localInit"))
                {
                    if (unsafeFieldName == null)
                    {
                        String version = System.getProperty("java.version");
                        if (version.startsWith("11.")) { unsafeFieldName = "U"; unsafeDescriptor = "Ljdk/internal/misc/Unsafe;"; }
                        else if (version.startsWith("1.8")) { unsafeFieldName = "UNSAFE"; unsafeDescriptor = "Lsun/misc/Unsafe;"; }
                        else throw new AssertionError("Unsupported Java Version");
                    }

                    MethodVisitor visitor = super.visitMethod(access, name, descriptor, signature, exceptions);
                    visitor.visitLabel(new Label());
                    visitor.visitIntInsn(ALOAD, 0);
                    visitor.visitFieldInsn(GETSTATIC, "java/util/concurrent/ThreadLocalRandom", unsafeFieldName, unsafeDescriptor);
                    visitor.visitMethodInsn(INVOKESTATIC, "java/lang/Thread", "currentThread", "()Ljava/lang/Thread;", false);
                    visitor.visitFieldInsn(GETSTATIC, "java/util/concurrent/ThreadLocalRandom", "SEED", "J");
                    visitor.visitMethodInsn(INVOKESTATIC, "org/apache/cassandra/simulator/systems/InterceptorOfSystemMethods$Global", "randomSeed", "()J", false);
                    visitor.visitMethodInsn(INVOKEVIRTUAL, "sun/misc/Unsafe", "putLong", "(Ljava/lang/Object;JJ)V", false);
                    visitor.visitFieldInsn(GETSTATIC, "java/util/concurrent/ThreadLocalRandom", unsafeFieldName, unsafeDescriptor);
                    visitor.visitMethodInsn(INVOKESTATIC, "java/lang/Thread", "currentThread", "()Ljava/lang/Thread;", false);
                    visitor.visitFieldInsn(GETSTATIC, "java/util/concurrent/ThreadLocalRandom", "PROBE", "J");
                    visitor.visitLdcInsn(0);
                    visitor.visitMethodInsn(INVOKEVIRTUAL, "sun/misc/Unsafe", "putInt", "(Ljava/lang/Object;JI)V", false);
                    visitor.visitInsn(RETURN);
                    visitor.visitLabel(new Label());
                    visitor.visitMaxs(6, 1);
                    visitor.visitEnd();

                    return new MethodVisitor(BYTECODE_VERSION) {};
                }
                else
                {
                    return super.visitMethod(access, name, descriptor, signature, exceptions);
                }
            }
        }
        return transform(bytes, ThreadLocalRandomVisitor::new);
    }

    private static byte[] transform(byte[] bytes, BiFunction<Integer, ClassWriter, ClassVisitor> constructor)
    {
        ClassWriter out = new ClassWriter(0);
        ClassReader in = new ClassReader(bytes);
        ClassVisitor transform = constructor.apply(BYTECODE_VERSION, out);
        in.accept(transform, 0);
        return out.toByteArray();
    }

    private static byte[] transformConcurrent(String className, byte[] bytes, Flag flag, Flag ... flags)
    {
        ClassTransformer transformer = new ClassTransformer(BYTECODE_VERSION, className, EnumSet.of(flag, flags));
        transformer.readAndTransform(bytes);
        if (!transformer.isTransformed())
            return null;
        return transformer.toBytes();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.orientechnologies.orient.graph.sql;

import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
import org.junit.BeforeClass;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class TestOutInChain {

  @BeforeClass
  public static void before() {
    // generate schema
    OrientGraphNoTx graph = new OrientGraphNoTx("memory:" + TestOutInChain.class.getSimpleName(), "admin", "admin");
    graph.command(new OCommandSQL("create class User extends V")).execute();
    graph.command(new OCommandSQL("create class Car extends V")).execute();
    graph.command(new OCommandSQL("create class Owns extends E")).execute();
    graph.shutdown();
  }

  @Test
  public void t() {
    OrientGraph graph = new OrientGraph("memory:" + TestOutInChain.class.getSimpleName(), "admin", "admin");

    Vertex vUser = graph.addVertex("class:User");
    Vertex vCar = graph.addVertex("class:Car");
    graph.addEdge("class:Owns", vUser, vCar, null);

    graph.commit();

    Iterable<Vertex> res = graph.command(new OCommandSQL("select expand( out('Owns') ) from User")).execute();
    assertTrue(res.iterator().hasNext());
    assertEquals("Car", res.iterator().next().getProperty("@class").toString());

    Iterable<Vertex> resEdge = graph.command(new OCommandSQL("select expand( inE('Owns') ) from Car")).execute();
    assertTrue(resEdge.iterator().hasNext());

    // when out('Owns') is executed we have Car vertex (see above)
    // after that inE('Owns') should return Owns edge (see above)
    // but test fails
    resEdge = graph.command(new OCommandSQL("select expand( out('Owns').inE('Owns') ) from User")).execute();
    assertTrue(resEdge.iterator().hasNext());// assertion error here
		graph.shutdown();
  }
}


text:
## Employees Directory

- Angular 2 ( 2.x )
- ExpressJS ( 4.x - with compression )
- Webpack ( angular-cli )

Based on: https://github.com/vladotesanovic/angular2-express-starter

## Install / Development

# Install dependencies
npm install

# start server
npm run start

# Client url: http://localhost:4200
# Application ( epxress ) API: http://localhost:4300
```

## Build / Production

```bash

npm run build

## Deploy dist folder to app server

Structure of dist folder:

/dist/server <-- expressjs
/dist/client <-- angular2

```
Test string to push


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});
exports.readDirectory = readDirectory;
exports.readFile = readFile;
exports.indexFile = indexFile;

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var _fs = require('fs');

var _fs2 = _interopRequireDefault(_fs);

// Liste les documents présents dans un fichier en mode synchrone

function readDirectory(pathname) {
  return _fs2['default'].readdirSync(pathname);
}

// Lecture d'un fichier en mod synchrone

function readFile(pathname) {
  for (var _len = arguments.length, options = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    options[_key - 1] = arguments[_key];
  }

  return _fs2['default'].readFileSync.apply(_fs2['default'], [pathname].concat(options));
}

// Extrait les mot d'un text en minuscule
function extractWords(file_content) {
  return file_content.split(/\s+/).map(function (mot) {
    return mot.toLowerCase();
  });
}

// Index un fichier dans l'indexer

function indexFile(file_content, indexer, document_name) {
  var words = extractWords(file_content);
  words.map(function (word) {
    indexer.ajouterMot(word, document_name);
  });
}


text:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><%= slugName %></title>
    <!-- build:css -->
    <link href="<%= baseUrl %>css/styles.css" rel="stylesheet">
    <!-- endbuild -->
    <!-- build:js -->
    <script src="<%= baseUrl %>node_modules/babel-core/browser-polyfill.js"></script>
    <script src="<%= baseUrl %>app/require.config.js"></script>
    <script data-main="app/startup" src="<%= baseUrl %>bower_components/requirejs/require.js"></script>
    <!-- endbuild -->
</head>

<body>
    <% if(includeDemo) { %><nav-bar></nav-bar><% } %>
    <router data-bind="visible: !dialoger.isDialogOpen()" params="{ title: router.currentRouteTitle }"></router>
    <dialoger data-bind="visible: dialoger.isDialogOpen" params="{ title: dialoger.currentDialogTitle }"></dialoger>
    <modaler class="modal fade" data-bind="visible: modaler.isModalOpen" params="{ title: modaler.currentModalTitle }"></modaler>
</body>

</html>


text:
/*
  Example code to show how to send a string to a function called "reverse" and print the results.
*/

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <libgearman/gearman.h>

int main(void)
{
  gearman_client_st *client= gearman_client_create(NULL);

  gearman_return_t ret= gearman_client_add_server(client, "localhost", 0);
  if (gearman_failed(ret))
  {
    return EXIT_FAILURE;
  }

  gearman_argument_t value= gearman_argument_make(0, 0, "Reverse Me", strlen("Reverse Me"));

  gearman_task_st *task= gearman_execute(client,
                                         "reverse", strlen("reverse"),  // function
                                         NULL, 0,  // no unique value provided
                                         NULL,
                                         &value, 0);

  if (task == NULL) // If gearman_execute() can return NULL on error
  {
    fprintf(stderr, "Error: %s\n", gearman_client_error(client));
    gearman_client_free(client);
    return EXIT_FAILURE;
  }

  // Make sure the task was run successfully
  if (gearman_success(gearman_task_return(task)))
  {
    // Make use of value
    gearman_result_st *result= gearman_task_result(task);
    printf("%.*s\n", (int)gearman_result_size(result), gearman_result_value(result));
  }

  gearman_client_free(client);

  return EXIT_SUCCESS;
}


text:
#ifndef _ARM_DL_TLSDESC_H
# define _ARM_DL_TLSDESC_H 1

/* Use this to access DT_TLSDESC_PLT and DT_TLSDESC_GOT.  */
#ifndef ADDRIDX
# define ADDRIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
		       + DT_EXTRANUM + DT_VALNUM + DT_ADDRTAGIDX (tag))
#endif

/* Type used to represent a TLS descriptor in the GOT.  */
struct tlsdesc
{
  union
    {
      void *pointer;
      long value;
    } argument;
  ptrdiff_t (*entry)(struct tlsdesc *);
};

typedef struct dl_tls_index
{
  unsigned long int ti_module;
  unsigned long int ti_offset;
} tls_index;

/* Type used as the argument in a TLS descriptor for a symbol that
   needs dynamic TLS offsets.  */
struct tlsdesc_dynamic_arg
{
  tls_index tlsinfo;
  size_t gen_count;
};

extern ptrdiff_t attribute_hidden
  _dl_tlsdesc_return(struct tlsdesc *),
  _dl_tlsdesc_undefweak(struct tlsdesc *),
  _dl_tlsdesc_resolve_hold(struct tlsdesc *),
  _dl_tlsdesc_lazy_resolver(struct tlsdesc *);

# ifdef SHARED
extern void *_dl_make_tlsdesc_dynamic (struct link_map *map, size_t ti_offset);

extern ptrdiff_t attribute_hidden
  _dl_tlsdesc_dynamic(struct tlsdesc *);
# endif

#endif


text:
package br.com.rooting.roxana;

public final class RoxanaPackageMapper {

    public static final String PROJECT_ROOT_PACKAGE_PATH = "br.com.rooting.roxana";

    public static final String SWAGGER_CONFIG_PACKAGE_PATH = "br.com.rooting.roxana.config.swagger";

    private RoxanaPackageMapper() {
    }

}


text:
package groovy.util.logging;

import groovy.lang.GroovyClassLoader;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.FieldNode;
import org.codehaus.groovy.ast.expr.*;
import org.codehaus.groovy.transform.GroovyASTTransformationClass;
import org.codehaus.groovy.transform.LogASTTransformation;
import org.objectweb.asm.Opcodes;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Locale;

/**
 * This local transform adds a logging ability to your program using
 * Apache Commons logging. Every method call on a unbound variable named log
 * will be mapped to a call to the logger. For this a log field will be
 * inserted in the class. If the field already exists the usage of this transform
 * will cause a compilation error. The method name will be used to determine
 * what to call on the logger.
 *

 * log.name(exp)
 *
is mapped to
 *

 * if (log.isNameEnabled() {
 *    log.name(exp)
 * }

 * Here name is a place holder for info, debug, warning, error, etc.
 * If the expression exp is a constant or only a variable access the method call will
 * not be transformed. But this will still cause a call on the injected logger.
 *
 * @author Hamlet D'Arcy
 * @author Matthias Cullmann
 * @since 1.8.0
 */
@java.lang.annotation.Documented
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.TYPE})
@GroovyASTTransformationClass("org.codehaus.groovy.transform.LogASTTransformation")
public @interface Commons {
    String value() default "log";
    String category() default LogASTTransformation.DEFAULT_CATEGORY_NAME;
    Class<? extends LogASTTransformation.LoggingStrategy> loggingStrategy() default CommonsLoggingStrategy.class;

    public  static class CommonsLoggingStrategy extends LogASTTransformation.AbstractLoggingStrategy {

        private static final String LOGGER_NAME = "org.apache.commons.logging.Log";
        private static final String LOGGERFACTORY_NAME = "org.apache.commons.logging.LogFactory";

        protected CommonsLoggingStrategy(final GroovyClassLoader loader) {
            super(loader);
        }

        public FieldNode addLoggerFieldToClass(ClassNode classNode, String logFieldName, String categoryName) {
            return classNode.addField(logFieldName,
                    Opcodes.ACC_FINAL | Opcodes.ACC_TRANSIENT | Opcodes.ACC_STATIC | Opcodes.ACC_PRIVATE,
                    classNode(LOGGER_NAME),
                    new MethodCallExpression(
                            new ClassExpression(classNode(LOGGERFACTORY_NAME)),
                            "getLog",
                            new ConstantExpression(getCategoryName(classNode, categoryName))));
        }

        public boolean isLoggingMethod(String methodName) {
            return methodName.matches("fatal|error|warn|info|debug|trace");
        }

        public Expression wrapLoggingMethodCall(Expression logVariable, String methodName, Expression originalExpression) {
            MethodCallExpression condition = new MethodCallExpression(
                    logVariable,
                    "is" + methodName.substring(0, 1).toUpperCase(Locale.ENGLISH) + methodName.substring(1, methodName.length()) + "Enabled",
                    ArgumentListExpression.EMPTY_ARGUMENTS);

            return new TernaryExpression(
                    new BooleanExpression(condition),
                    originalExpression,
                    ConstantExpression.NULL);
        }
   }
}


text:
export interface SystemStatus {
  id: string;
  name: string;
  statusOk: Boolean;
}


text:
- [Example Parameters](#example-parameters)
- [Step-by-Step](#step-by-step)
- [Multipath Considerations](#multipath-considerations)

## Example Parameters

```yaml
 fc:
   targetWWNs:
     - '500a0982991b8dc5'
     - '500a0982891b8dc5'
   lun: 2
   fsType: ext4
   readOnly: true
```

[API Reference](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.18/#fcvolumesource-v1-core)

## Step-by-Step

### Set up a Fibre Channel Target

Using your Fibre Channel SAN Zone manager you must allocate and mask LUNs so that all hosts in the Kubernetes cluster can access them

### Prepare nodes in your Kubernetes cluster

You will need to install and configured a Fibre Channel initiator on the hosts within your Kubernetes cluster.

### Create a Pod using Fibre Channel persistent storage

Create a pod manifest based on  [fc.yaml](fc.yaml). You will need to provide *targetWWNs* (array of Fibre Channel target's World Wide Names), *lun*, and the type of the filesystem that has been created on the LUN if it is not _ext4_

Once you have created a pod manifest you can deploy it by running:

```console
kubectl apply -f ./your_new_pod.yaml
```

You can then confirm that the pod hase been sucessfully deployed by running `kubectl get pod fibre-channel-example-pod -o wide`

```console
# kubectl get pod fibre-channel-example-pod -o wide
NAME                        READY   STATUS          RESTARTS   AGE    IP               NODE    NOMINATED NODE   READINESS GATES
fibre-channel-example-pod   1/1     READY           0          1m8s   192.168.172.11   node0   <none>           <none>

```

If you connect to the console on the Kubernetes node that the pod has been assigned to you can see that the volume is mounted to the pod by running `mount | grep /var/lib/kubelet/plugins/kubernetes.io/fc/`

```console
# mount | grep /var/lib/kubelet/plugins/kubernetes.io/fc/
/dev/mapper/360a98000324669436c2b45666c567946 on /var/lib/kubelet/plugins/kubernetes.io/fc/500a0982991b8dc5-lun-2 type ext4 (relatime,seclabel,stripe=16,data=ordered)
  ```

## Multipath Considerations

To leverage multiple paths for block storage, it is important to perform
multipath configuration on the host.
If your distribution does not provide `/etc/multipath.conf`, then you can
either use the following minimalistic one:

```
defaults {
    find_multipaths yes
    user_friendly_names yes
}
```

or create a new one by running:

```console
$ mpathconf --enable
```

Finally you'll need to ensure to start or reload and enable multipath:

```console
$ systemctl enable --now multipathd.service
```

**Note:** Any change to `multipath.conf` or enabling multipath can lead to
inaccessible block devices as they will be claimed by multipath and
exposed as a device in /dev/mapper/*.

<!-- BEGIN MUNGE: GENERATED_ANALYTICS -->
[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/examples/volumes/fibre_channel/README.md?pixel)]()
<!-- END MUNGE: GENERATED_ANALYTICS -->


text:
import ComponentView from 'dom_components/view/ComponentView';
import Component from 'dom_components/model/Component';
import DomComponents from 'dom_components';
import Editor from 'editor/model/Editor';

describe('ComponentView', () => {
  let fixtures;
  let model;
  let view;
  let dcomp;
  let compOpts;
  let em;
  let el;

  beforeEach(() => {
    em = new Editor({});
    dcomp = new DomComponents(em);
    compOpts = {
      em,
      componentTypes: dcomp.componentTypes,
    };
    model = new Component({}, compOpts);
    view = new ComponentView({
      model,
    });
    em.get('StyleManager').render(); // Enable to listen em.setState
    document.body.innerHTML = '

';
    fixtures = document.body.querySelector('#fixtures');
    el = view.render().el;
    fixtures.appendChild(el);
  });

  afterEach(() => {
    view.remove();
  });

  test('Component empty', () => {
    expect(fixtures.innerHTML).toEqual(
      `<div data-gjs-highlightable="true" id="${el.id}" data-gjs-type="default"></div>`
    );
  });

  test('Clean form helper state', () => {
    em.setSelected(model);
    em.setState('test');
    em.setState();
    expect(fixtures.innerHTML).toEqual(
      `<div data-gjs-highlightable="true" id="${el.id}" data-gjs-type="default" class="selected"></div>`
    );
  });

  test('Add helper class on status update', () => {
    model.set('status', 'selected');
    expect(fixtures.innerHTML).toEqual(
      `<div data-gjs-highlightable="true" id="${el.id}" data-gjs-type="default" class="selected"></div>`
    );
  });

  test('Get string of classes', () => {
    model.set('attributes', { class: ['test', 'test2'] });
    expect(view.getClasses()).toEqual('test test2');
  });

  test('Update attributes', () => {
    model.set('attributes', {
      title: 'value',
      'data-test': 'value2',
    });
    expect(view.el.getAttribute('title')).toEqual('value');
    expect(view.el.getAttribute('data-test')).toEqual('value2');
  });

  test('Update style', () => {
    model.set('style', {
      color: 'red',
      float: 'left',
    });
    expect(view.el.getAttribute('style')).toEqual('color:red;float:left;');
  });

  test('Clean style', () => {
    model.set('style', { color: 'red' });
    model.set('style', {});
    expect(view.el.getAttribute('style')).toEqual(null);
  });

  test('Add class', () => {
    model.get('classes').add({ name: 'test' });
    expect(view.el.getAttribute('class')).toEqual('test');
  });

  test('Add classes', () => {
    model.get('classes').add([{ name: 'test' }, { name: 'test2' }]);
    expect(view.el.getAttribute('class')).toEqual('test test2');
  });

  test('Update on remove of some class', () => {
    var cls1 = model.get('classes').add({ name: 'test' });
    var cls12 = model.get('classes').add({ name: 'test2' });
    model.get('classes').remove(cls1);
    expect(view.el.getAttribute('class')).toEqual('test2');
  });

  test('Init with different tag', () => {
    model = new Component({ tagName: 'span' });
    view = new ComponentView({ model });
    fixtures.innerHTML = '';
    fixtures.appendChild(view.render().el);
    expect(view.render().el.tagName).toEqual('SPAN');
  });

  test('Init with nested components', () => {
    model = new Component(
      {
        components: [{ tagName: 'span' }, { attributes: { title: 'test' } }],
      },
      compOpts
    );
    view = new ComponentView({
      model,
      componentTypes: dcomp.componentTypes,
    });
    fixtures.innerHTML = '';
    el = view.render().el;
    fixtures.appendChild(el);
    const firstId = el.children[0].id;
    const secondId = el.children[1].id;
    expect(view.$el.html()).toEqual(
      `<span data-gjs-highlightable="true" id="${firstId}" data-gjs-type="default"></span><div data-gjs-highlightable="true" id="${secondId}" data-gjs-type="default" title="test"></div>`
    );
  });

  test('removeClass removes classes from attributes', () => {
    model.addClass('class1');
    model.removeClass('class1');
    const result = model.getAttributes();
    expect(result.class).toEqual(undefined);
  });
});


text:
namespace tesseract {

Tesseract::Tesseract()
    : BOOL_MEMBER(tessedit_resegment_from_boxes, false,
                  "Take segmentation and labeling from box file",
                  this->params()),
      BOOL_MEMBER(tessedit_resegment_from_line_boxes, false,
                  "Conversion of word/line box file to char box file",
                  this->params()),
      BOOL_MEMBER(tessedit_train_from_boxes, false,
                  "Generate training data from boxed chars", this->params()),
      BOOL_MEMBER(tessedit_make_boxes_from_boxes, false,
                  "Generate more boxes from boxed chars", this->params()),
      BOOL_MEMBER(tessedit_dump_pageseg_images, false,
                  "Dump intermediate images made during page segmentation",
                  this->params()),
      // The default for pageseg_mode is the old behaviour, so as not to
      // upset anything that relies on that.
      INT_MEMBER(
          tessedit_pageseg_mode, PSM_SINGLE_BLOCK,
          "Page seg mode: 0=osd only, 1=auto+osd, 2=auto, 3=col, 4=block,"
          " 5=line, 6=word, 7=char"
          " (Values from PageSegMode enum in publictypes.h)",
          this->params()),
      INT_INIT_MEMBER(tessedit_ocr_engine_mode, tesseract::OEM_TESSERACT_ONLY,
                      "Which OCR engine(s) to run (Tesseract, Cube, both)."
                      " Defaults to loading and running only Tesseract"
                      " (no Cube,no combiner)."
                      " Values from OcrEngineMode enum in tesseractclass.h)",
                      this->params()),
      STRING_MEMBER(tessedit_char_blacklist, "",
                    "Blacklist of chars not to recognize", this->params()),
      STRING_MEMBER(tessedit_char_whitelist, "",
                    "Whitelist of chars to recognize", this->params()),
      STRING_MEMBER(tessedit_char_unblacklist, "",
                    "List of chars to override tessedit_char_blacklist",
                    this->params()),
      BOOL_MEMBER(tessedit_ambigs_training, false,
                  "Perform training for ambiguities", this->params()),
      INT_MEMBER(pageseg_devanagari_split_strategy,
                 tesseract::ShiroRekhaSplitter::NO_SPLIT,
                 "Whether to use the top-line splitting process for Devanagari "
                 "documents while performing page-segmentation.",
                 this->params()),
      INT_MEMBER(ocr_devanagari_split_strategy,
                 tesseract::ShiroRekhaSplitter::NO_SPLIT,
                 "Whether to use the top-line splitting process for Devanagari "
                 "documents while performing ocr.",
                 this->params()),
      STRING_MEMBER(tessedit_write_params_to_file, "",
                    "Write all parameters to the given file.", this->params()),
      BOOL_MEMBER(tessedit_adaption_debug, false,
                  "Generate and print debug"
                  " information for adaption",
                  this->params()),
      INT_MEMBER(bidi_debug, 0, "Debug level for BiDi", this->params()),
      INT_MEMBER(applybox_debug, 1, "Debug level", this->params()),
      INT_MEMBER(applybox_page, 0, "Page number to apply boxes from",
                 this->params()),
      STRING_MEMBER(applybox_exposure_pattern, ".exp",
                    "Exposure value follows"
                    " this pattern in the image filename. The name of the image"
                    " files are expected to be in the form"
                    " [lang].[fontname].exp[num].tif",
                    this->params()),
      BOOL_MEMBER(applybox_learn_chars_and_char_frags_mode, false,
                  "Learn both character fragments (as is done in the"
                  " special low exposure mode) as well as unfragmented"
                  " characters.",
                  this->params()),
      BOOL_MEMBER(applybox_learn_ngrams_mode, false,
                  "Each bounding box"
                  " is assumed to contain ngrams. Only learn the ngrams"
                  " whose outlines overlap horizontally.",
                  this->params()),
      BOOL_MEMBER(tessedit_display_outwords, false, "Draw output words",
                  this->params()),
      BOOL_MEMBER(tessedit_dump_choices, false, "Dump char choices",
                  this->params()),
      BOOL_MEMBER(tessedit_timing_debug, false, "Print timing stats",
                  this->params()),
      BOOL_MEMBER(tessedit_fix_fuzzy_spaces, true,
                  "Try to improve fuzzy spaces", this->params()),
      BOOL_MEMBER(tessedit_unrej_any_wd, false,
                  "Don't bother with word plausibility", this->params()),
      BOOL_MEMBER(tessedit_fix_hyphens, true, "Crunch double hyphens?",
                  this->params()),
      BOOL_MEMBER(tessedit_redo_xheight, true, "Check/Correct x-height",
                  this->params()),
      BOOL_MEMBER(tessedit_enable_doc_dict, true,
                  "Add words to the document dictionary", this->params()),
      BOOL_MEMBER(tessedit_debug_fonts, false, "Output font info per char",
                  this->params()),
      BOOL_MEMBER(tessedit_debug_block_rejection, false, "Block and Row stats",
                  this->params()),
      BOOL_MEMBER(tessedit_enable_bigram_correction, true,
                  "Enable correction based on the word bigram dictionary.",
                  this->params()),
      BOOL_MEMBER(tessedit_enable_dict_correction, false,
                  "Enable single word correction based on the dictionary.",
                  this->params()),
      INT_MEMBER(tessedit_bigram_debug, 0,
                 "Amount of debug output for bigram correction.",
                 this->params()),
      BOOL_MEMBER(enable_noise_removal, true,
                  "Remove and conditionally reassign small outlines when they"
                  " confuse layout analysis, determining diacritics vs noise",
                  this->params()),
      INT_MEMBER(debug_noise_removal, 0, "Debug reassignment of small outlines",
                 this->params()),
      // Worst (min) certainty, for which a diacritic is allowed to make the
      // base
      // character worse and still be included.
      double_MEMBER(noise_cert_basechar, -8.0,
                    "Hingepoint for base char certainty", this->params()),
      // Worst (min) certainty, for which a non-overlapping diacritic is allowed
      // to make the base character worse and still be included.
      double_MEMBER(noise_cert_disjoint, -1.0,
                    "Hingepoint for disjoint certainty", this->params()),
      // Worst (min) certainty, for which a diacritic is allowed to make a new
      // stand-alone blob.
      double_MEMBER(noise_cert_punc, -3.0,
                    "Threshold for new punc char certainty", this->params()),
      // Factor of certainty margin for adding diacritics to not count as worse.
      double_MEMBER(noise_cert_factor, 0.375,
                    "Scaling on certainty diff from Hingepoint",
                    this->params()),
      INT_MEMBER(noise_maxperblob, 8, "Max diacritics to apply to a blob",
                 this->params()),
      INT_MEMBER(noise_maxperword, 16, "Max diacritics to apply to a word",
                 this->params()),
      INT_MEMBER(debug_x_ht_level, 0, "Reestimate debug", this->params()),
      BOOL_MEMBER(debug_acceptable_wds, false, "Dump word pass/fail chk",
                  this->params()),
      STRING_MEMBER(chs_leading_punct, "('`\"", "Leading punctuation",
                    this->params()),
      STRING_MEMBER(chs_trailing_punct1, ").,;:?!", "1st Trailing punctuation",
                    this->params()),
      STRING_MEMBER(chs_trailing_punct2, ")'`\"", "2nd Trailing punctuation",
                    this->params()),
      double_MEMBER(quality_rej_pc, 0.08,
                    "good_quality_doc lte rejection limit", this->params()),
      double_MEMBER(quality_blob_pc, 0.0,
                    "good_quality_doc gte good blobs limit", this->params()),
      double_MEMBER(quality_outline_pc, 1.0,
                    "good_quality_doc lte outline error limit", this->params()),
      double_MEMBER(quality_char_pc, 0.95,
                    "good_quality_doc gte good char limit", this->params()),
      INT_MEMBER(quality_min_initial_alphas_reqd, 2, "alphas in a good word",
                 this->params()),
      INT_MEMBER(tessedit_tess_adaption_mode, 0x27,
                 "Adaptation decision algorithm for tess", this->params()),
      BOOL_MEMBER(tessedit_minimal_rej_pass1, false,
                  "Do minimal rejection on pass 1 output", this->params()),
      BOOL_MEMBER(tessedit_test_adaption, false, "Test adaption criteria",
                  this->params()),
      BOOL_MEMBER(tessedit_matcher_log, false, "Log matcher activity",
                  this->params()),
      INT_MEMBER(tessedit_test_adaption_mode, 3,
                 "Adaptation decision algorithm for tess", this->params()),
      BOOL_MEMBER(test_pt, false, "Test for point", this->params()),
      double_MEMBER(test_pt_x, 99999.99, "xcoord", this->params()),
      double_MEMBER(test_pt_y, 99999.99, "ycoord", this->params()),
      INT_MEMBER(paragraph_debug_level, 0, "Print paragraph debug info.",
                 this->params()),
      BOOL_MEMBER(paragraph_text_based, true,
                  "Run paragraph detection on the post-text-recognition "
                  "(more accurate)",
                  this->params()),
      INT_MEMBER(cube_debug_level, 0, "Print cube debug info.", this->params()),
      STRING_MEMBER(outlines_odd, "%| ", "Non standard number of outlines",
                    this->params()),
      STRING_MEMBER(outlines_2, "ij!?%\":;", "Non standard number of outlines",
                    this->params()),
      BOOL_MEMBER(docqual_excuse_outline_errs, false,
                  "Allow outline errs in unrejection?", this->params()),
      BOOL_MEMBER(tessedit_good_quality_unrej, true,
                  "Reduce rejection on good docs", this->params()),
      BOOL_MEMBER(tessedit_use_reject_spaces, true, "Reject spaces?",
                  this->params()),
      double_MEMBER(tessedit_reject_doc_percent, 65.00,
                    "%rej allowed before rej whole doc", this->params()),
      double_MEMBER(tessedit_reject_block_percent, 45.00,
                    "%rej allowed before rej whole block", this->params()),
      double_MEMBER(tessedit_reject_row_percent, 40.00,
                    "%rej allowed before rej whole row", this->params()),
      double_MEMBER(tessedit_whole_wd_rej_row_percent, 70.00,
                    "Number of row rejects in whole word rejects"
                    "which prevents whole row rejection",
                    this->params()),
      BOOL_MEMBER(tessedit_preserve_blk_rej_perfect_wds, true,
                  "Only rej partially rejected words in block rejection",
                  this->params()),
      BOOL_MEMBER(tessedit_preserve_row_rej_perfect_wds, true,
                  "Only rej partially rejected words in row rejection",
                  this->params()),
      BOOL_MEMBER(tessedit_dont_blkrej_good_wds, false,
                  "Use word segmentation quality metric", this->params()),
      BOOL_MEMBER(tessedit_dont_rowrej_good_wds, false,
                  "Use word segmentation quality metric", this->params()),
      INT_MEMBER(tessedit_preserve_min_wd_len, 2,
                 "Only preserve wds longer than this", this->params()),
      BOOL_MEMBER(tessedit_row_rej_good_docs, true,
                  "Apply row rejection to good docs", this->params()),
      double_MEMBER(tessedit_good_doc_still_rowrej_wd, 1.1,
                    "rej good doc wd if more than this fraction rejected",
                    this->params()),
      BOOL_MEMBER(tessedit_reject_bad_qual_wds, true,
                  "Reject all bad quality wds", this->params()),
      BOOL_MEMBER(tessedit_debug_doc_rejection, false, "Page stats",
                  this->params()),
      BOOL_MEMBER(tessedit_debug_quality_metrics, false,
                  "Output data to debug file", this->params()),
      BOOL_MEMBER(bland_unrej, false, "unrej potential with no chekcs",
                  this->params()),
      double_MEMBER(quality_rowrej_pc, 1.1,
                    "good_quality_doc gte good char limit", this->params()),
      BOOL_MEMBER(unlv_tilde_crunching, true,
                  "Mark v.bad words for tilde crunch", this->params()),
      BOOL_MEMBER(hocr_font_info, false, "Add font info to hocr output",
                  this->params()),
      BOOL_MEMBER(crunch_early_merge_tess_fails, true, "Before word crunch?",
                  this->params()),
      BOOL_MEMBER(crunch_early_convert_bad_unlv_chs, false,
                  "Take out ~^ early?", this->params()),
      double_MEMBER(crunch_terrible_rating, 80.0, "crunch rating lt this",
                    this->params()),
      BOOL_MEMBER(crunch_terrible_garbage, true, "As it says", this->params()),
      double_MEMBER(crunch_poor_garbage_cert, -9.0,
                    "crunch garbage cert lt this", this->params()),
      double_MEMBER(crunch_poor_garbage_rate, 60,
                    "crunch garbage rating lt this", this->params()),
      double_MEMBER(crunch_pot_poor_rate, 40, "POTENTIAL crunch rating lt this",
                    this->params()),
      double_MEMBER(crunch_pot_poor_cert, -8.0, "POTENTIAL crunch cert lt this",
                    this->params()),
      BOOL_MEMBER(crunch_pot_garbage, true, "POTENTIAL crunch garbage",
                  this->params()),
      double_MEMBER(crunch_del_rating, 60, "POTENTIAL crunch rating lt this",
                    this->params()),
      double_MEMBER(crunch_del_cert, -10.0, "POTENTIAL crunch cert lt this",
                    this->params()),
      double_MEMBER(crunch_del_min_ht, 0.7, "Del if word ht lt xht x this",
                    this->params()),
      double_MEMBER(crunch_del_max_ht, 3.0, "Del if word ht gt xht x this",
                    this->params()),
      double_MEMBER(crunch_del_min_width, 3.0,
                    "Del if word width lt xht x this", this->params()),
      double_MEMBER(crunch_del_high_word, 1.5,
                    "Del if word gt xht x this above bl", this->params()),
      double_MEMBER(crunch_del_low_word, 0.5,
                    "Del if word gt xht x this below bl", this->params()),
      double_MEMBER(crunch_small_outlines_size, 0.6, "Small if lt xht x this",
                    this->params()),
      INT_MEMBER(crunch_rating_max, 10, "For adj length in rating per ch",
                 this->params()),
      INT_MEMBER(crunch_pot_indicators, 1,
                 "How many potential indicators needed", this->params()),
      BOOL_MEMBER(crunch_leave_ok_strings, true, "Don't touch sensible strings",
                  this->params()),
      BOOL_MEMBER(crunch_accept_ok, true, "Use acceptability in okstring",
                  this->params()),
      BOOL_MEMBER(crunch_leave_accept_strings, false,
                  "Don't pot crunch sensible strings", this->params()),
      BOOL_MEMBER(crunch_include_numerals, false, "Fiddle alpha figures",
                  this->params()),
      INT_MEMBER(crunch_leave_lc_strings, 4,
                 "Don't crunch words with long lower case strings",
                 this->params()),
      INT_MEMBER(crunch_leave_uc_strings, 4,
                 "Don't crunch words with long lower case strings",
                 this->params()),
      INT_MEMBER(crunch_long_repetitions, 3,
                 "Crunch words with long repetitions", this->params()),
      INT_MEMBER(crunch_debug, 0, "As it says", this->params()),
      INT_MEMBER(fixsp_non_noise_limit, 1,
                 "How many non-noise blbs either side?", this->params()),
      double_MEMBER(fixsp_small_outlines_size, 0.28, "Small if lt xht x this",
                    this->params()),
      BOOL_MEMBER(tessedit_prefer_joined_punct, false,
                  "Reward punctation joins", this->params()),
      INT_MEMBER(fixsp_done_mode, 1, "What constitues done for spacing",
                 this->params()),
      INT_MEMBER(debug_fix_space_level, 0, "Contextual fixspace debug",
                 this->params()),
      STRING_MEMBER(numeric_punctuation, ".,",
                    "Punct. chs expected WITHIN numbers", this->params()),
      INT_MEMBER(x_ht_acceptance_tolerance, 8,
                 "Max allowed deviation of blob top outside of font data",
                 this->params()),
      INT_MEMBER(x_ht_min_change, 8,
                 "Min change in xht before actually trying it", this->params()),
      INT_MEMBER(superscript_debug, 0,
                 "Debug level for sub & superscript fixer", this->params()),
      double_MEMBER(
          superscript_worse_certainty, 2.0,
          "How many times worse "
          "certainty does a superscript position glyph need to be for "
          "us to try classifying it as a char with a different "
          "baseline?",
          this->params()),
      double_MEMBER(
          superscript_bettered_certainty, 0.97,
          "What reduction in "
          "badness do we think sufficient to choose a superscript "
          "over what we'd thought.  For example, a value of 0.6 means "
          "we want to reduce badness of certainty by at least 40%",
          this->params()),
      double_MEMBER(superscript_scaledown_ratio, 0.4,
                    "A superscript scaled down more than this is unbelievably "
                    "small.  For example, 0.3 means we expect the font size to "
                    "be no smaller than 30% of the text line font size.",
                    this->params()),
      double_MEMBER(subscript_max_y_top, 0.5,
                    "Maximum top of a character measured as a multiple of "
                    "x-height above the baseline for us to reconsider whether "
                    "it's a subscript.",
                    this->params()),
      double_MEMBER(superscript_min_y_bottom, 0.3,
                    "Minimum bottom of a character measured as a multiple of "
                    "x-height above the baseline for us to reconsider whether "
                    "it's a superscript.",
                    this->params()),
      BOOL_MEMBER(tessedit_write_block_separators, false,
                  "Write block separators in output", this->params()),
      BOOL_MEMBER(tessedit_write_rep_codes, false, "Write repetition char code",
                  this->params()),
      BOOL_MEMBER(tessedit_write_unlv, false, "Write .unlv output file",
                  this->params()),
      BOOL_MEMBER(tessedit_create_txt, false, "Write .txt output file",
                  this->params()),
      BOOL_MEMBER(tessedit_create_hocr, false, "Write .html hOCR output file",
                  this->params()),
      BOOL_MEMBER(tessedit_create_pdf, false, "Write .pdf output file",
                  this->params()),
      STRING_MEMBER(unrecognised_char, "|",
                    "Output char for unidentified blobs", this->params()),
      INT_MEMBER(suspect_level, 99, "Suspect marker level", this->params()),
      INT_MEMBER(suspect_space_level, 100,
                 "Min suspect level for rejecting spaces", this->params()),
      INT_MEMBER(suspect_short_words, 2,
                 "Don't suspect dict wds longer than this", this->params()),
      BOOL_MEMBER(suspect_constrain_1Il, false, "UNLV keep 1Il chars rejected",
                  this->params()),
      double_MEMBER(suspect_rating_per_ch, 999.9, "Don't touch bad rating limit",
                    this->params()),
      double_MEMBER(suspect_accept_rating, -999.9, "Accept good rating limit",
                    this->params()),
      BOOL_MEMBER(tessedit_minimal_rejection, false,
                  "Only reject tess failures", this->params()),
      BOOL_MEMBER(tessedit_zero_rejection, false, "Don't reject ANYTHING",
                  this->params()),
      BOOL_MEMBER(tessedit_word_for_word, false,
                  "Make output have exactly one word per WERD", this->params()),
      BOOL_MEMBER(tessedit_zero_kelvin_rejection, false,
                  "Don't reject ANYTHING AT ALL", this->params()),
      BOOL_MEMBER(tessedit_consistent_reps, true,
                  "Force all rep chars the same", this->params()),
      INT_MEMBER(tessedit_reject_mode, 0, "Rejection algorithm",
                 this->params()),
      BOOL_MEMBER(tessedit_rejection_debug, false, "Adaption debug",
                  this->params()),
      BOOL_MEMBER(tessedit_flip_0O, true, "Contextual 0O O0 flips",
                  this->params()),
      double_MEMBER(tessedit_lower_flip_hyphen, 1.5,
                    "Aspect ratio dot/hyphen test", this->params()),
      double_MEMBER(tessedit_upper_flip_hyphen, 1.8,
                    "Aspect ratio dot/hyphen test", this->params()),
      BOOL_MEMBER(rej_trust_doc_dawg, false,
                  "Use DOC dawg in 11l conf. detector", this->params()),
      BOOL_MEMBER(rej_1Il_use_dict_word, false, "Use dictword test",
                  this->params()),
      BOOL_MEMBER(rej_1Il_trust_permuter_type, true, "Don't double check",
                  this->params()),
      BOOL_MEMBER(rej_use_tess_accepted, true, "Individual rejection control",
                  this->params()),
      BOOL_MEMBER(rej_use_tess_blanks, true, "Individual rejection control",
                  this->params()),
      BOOL_MEMBER(rej_use_good_perm, true, "Individual rejection control",
                  this->params()),
      BOOL_MEMBER(rej_use_sensible_wd, false, "Extend permuter check",
                  this->params()),
      BOOL_MEMBER(rej_alphas_in_number_perm, false, "Extend permuter check",
                  this->params()),
      double_MEMBER(rej_whole_of_mostly_reject_word_fract, 0.85,
                    "if >this fract", this->params()),
      INT_MEMBER(tessedit_image_border, 2, "Rej blbs near image edge limit",
                 this->params()),
      STRING_MEMBER(ok_repeated_ch_non_alphanum_wds, "-?*\075",
                    "Allow NN to unrej", this->params()),
      STRING_MEMBER(conflict_set_I_l_1, "Il1[]", "Il1 conflict set",
                    this->params()),
      INT_MEMBER(min_sane_x_ht_pixels, 8, "Reject any x-ht lt or eq than this",
                 this->params()),
      BOOL_MEMBER(tessedit_create_boxfile, false, "Output text with boxes",
                  this->params()),
      INT_MEMBER(tessedit_page_number, -1,
                 "-1 -> All pages"
                 " , else specifc page to process",
                 this->params()),
      BOOL_MEMBER(tessedit_write_images, false,
                  "Capture the image from the IPE", this->params()),
      BOOL_MEMBER(interactive_display_mode, false, "Run interactively?",
                  this->params()),
      STRING_MEMBER(file_type, ".tif", "Filename extension", this->params()),
      BOOL_MEMBER(tessedit_override_permuter, true, "According to dict_word",
                  this->params()),
      INT_MEMBER(tessdata_manager_debug_level, 0,
                 "Debug level for"
                 " TessdataManager functions.",
                 this->params()),
      STRING_MEMBER(tessedit_load_sublangs, "",
                    "List of languages to load with this one", this->params()),
      BOOL_MEMBER(tessedit_use_primary_params_model, false,
                  "In multilingual mode use params model of the"
                  " primary language",
                  this->params()),
      double_MEMBER(min_orientation_margin, 7.0,
                    "Min acceptable orientation margin", this->params()),
      BOOL_MEMBER(textord_tabfind_show_vlines, false, "Debug line finding",
                  this->params()),
      BOOL_MEMBER(textord_use_cjk_fp_model, FALSE, "Use CJK fixed pitch model",
                  this->params()),
      BOOL_MEMBER(poly_allow_detailed_fx, false,
                  "Allow feature extractors to see the original outline",
                  this->params()),
      BOOL_INIT_MEMBER(tessedit_init_config_only, false,
                       "Only initialize with the config file. Useful if the "
                       "instance is not going to be used for OCR but say only "
                       "for layout analysis.",
                       this->params()),
      BOOL_MEMBER(textord_equation_detect, false, "Turn on equation detector",
                  this->params()),
      BOOL_MEMBER(textord_tabfind_vertical_text, true,
                  "Enable vertical detection", this->params()),
      BOOL_MEMBER(textord_tabfind_force_vertical_text, false,
                  "Force using vertical text page mode", this->params()),
      double_MEMBER(
          textord_tabfind_vertical_text_ratio, 0.5,
          "Fraction of textlines deemed vertical to use vertical page "
          "mode",
          this->params()),
      double_MEMBER(
          textord_tabfind_aligned_gap_fraction, 0.75,
          "Fraction of height used as a minimum gap for aligned blobs.",
          this->params()),
      INT_MEMBER(tessedit_parallelize, 0, "Run in parallel where possible",
                 this->params()),
      BOOL_MEMBER(preserve_interword_spaces, false,
                  "Preserve multiple interword spaces", this->params()),
      BOOL_MEMBER(include_page_breaks, FALSE,
                  "Include page separator string in output text after each "
                  "image/page.",
                  this->params()),
      STRING_MEMBER(page_separator, "\f",
                    "Page separator (default is form feed control character)",
                    this->params()),

      // The following parameters were deprecated and removed from their
      // original
      // locations. The parameters are temporarily kept here to give Tesseract
      // users a chance to updated their [lang].traineddata and config files
      // without introducing failures during Tesseract initialization.
      // TODO(ocr-team): remove these parameters from the code once we are
      // reasonably sure that Tesseract users have updated their data files.
      //
      // BEGIN DEPRECATED PARAMETERS
      BOOL_MEMBER(textord_tabfind_vertical_horizontal_mix, true,
                  "find horizontal lines such as headers in vertical page mode",
                  this->params()),
      INT_MEMBER(tessedit_ok_mode, 5, "Acceptance decision algorithm",
                 this->params()),
      BOOL_INIT_MEMBER(load_fixed_length_dawgs, true,
                       "Load fixed length dawgs"
                       " (e.g. for non-space delimited languages)",
                       this->params()),
      INT_MEMBER(segment_debug, 0, "Debug the whole segmentation process",
                 this->params()),
      BOOL_MEMBER(permute_debug, 0, "Debug char permutation process",
                  this->params()),
      double_MEMBER(bestrate_pruning_factor, 2.0,
                    "Multiplying factor of"
                    " current best rate to prune other hypotheses",
                    this->params()),
      BOOL_MEMBER(permute_script_word, 0,
                  "Turn on word script consistency permuter", this->params()),
      BOOL_MEMBER(segment_segcost_rating, 0,
                  "incorporate segmentation cost in word rating?",
                  this->params()),
      double_MEMBER(segment_reward_script, 0.95,
                    "Score multipler for script consistency within a word. "
                    "Being a 'reward' factor, it should be <= 1. "
                    "Smaller value implies bigger reward.",
                    this->params()),
      BOOL_MEMBER(permute_fixed_length_dawg, 0,
                  "Turn on fixed-length phrasebook search permuter",
                  this->params()),
      BOOL_MEMBER(permute_chartype_word, 0,
                  "Turn on character type (property) consistency permuter",
                  this->params()),
      double_MEMBER(segment_reward_chartype, 0.97,
                    "Score multipler for char type consistency within a word. ",
                    this->params()),
      double_MEMBER(segment_reward_ngram_best_choice, 0.99,
                    "Score multipler for ngram permuter's best choice"
                    " (only used in the Han script path).",
                    this->params()),
      BOOL_MEMBER(ngram_permuter_activated, false,
                  "Activate character-level n-gram-based permuter",
                  this->params()),
      BOOL_MEMBER(permute_only_top, false, "Run only the top choice permuter",
                  this->params()),
      INT_MEMBER(language_model_fixed_length_choices_depth, 3,
                 "Depth of blob choice lists to explore"
                 " when fixed length dawgs are on",
                 this->params()),
      BOOL_MEMBER(use_new_state_cost, FALSE,
                  "use new state cost heuristics for segmentation state"
                  " evaluation",
                  this->params()),
      double_MEMBER(heuristic_segcost_rating_base, 1.25,
                    "base factor for adding segmentation cost into word rating."
                    "It's a multiplying factor, the larger the value above 1, "
                    "the bigger the effect of segmentation cost.",
                    this->params()),
      double_MEMBER(heuristic_weight_rating, 1.0,
                    "weight associated with char rating in combined cost of"
                    "state",
                    this->params()),
      double_MEMBER(heuristic_weight_width, 1000.0,
                    "weight associated with width evidence in combined cost of"
                    " state",
                    this->params()),
      double_MEMBER(heuristic_weight_seamcut, 0.0,
                    "weight associated with seam cut in combined cost of state",
                    this->params()),
      double_MEMBER(heuristic_max_char_wh_ratio, 2.0,
                    "max char width-to-height ratio allowed in segmentation",
                    this->params()),
      BOOL_MEMBER(enable_new_segsearch, true,
                  "Enable new segmentation search path.", this->params()),
      double_MEMBER(segsearch_max_fixed_pitch_char_wh_ratio, 2.0,
                    "Maximum character width-to-height ratio for"
                    " fixed-pitch fonts",
                    this->params()),
      // END DEPRECATED PARAMETERS

      backup_config_file_(NULL),
      pix_binary_(NULL),
      cube_binary_(NULL),
      pix_grey_(NULL),
      pix_thresholds_(NULL),
      source_resolution_(0),
      textord_(this),
      right_to_left_(false),
      scaled_color_(NULL),
      scaled_factor_(-1),
      deskew_(1.0f, 0.0f),
      reskew_(1.0f, 0.0f),
      most_recently_used_(this),
      font_table_size_(0),
#ifndef NO_CUBE_BUILD
      cube_cntxt_(NULL),
      tess_cube_combiner_(NULL),
#endif
      equ_detect_(NULL) {
}

Tesseract::~Tesseract() {
  Clear();
  end_tesseract();
  sub_langs_.delete_data_pointers();
#ifndef NO_CUBE_BUILD
  // Delete cube objects.
  if (cube_cntxt_ != NULL) {
    delete cube_cntxt_;
    cube_cntxt_ = NULL;
  }
  if (tess_cube_combiner_ != NULL) {
    delete tess_cube_combiner_;
    tess_cube_combiner_ = NULL;
  }
#endif
}

void Tesseract::Clear() {
  pixDestroy(&pix_binary_);
  pixDestroy(&cube_binary_);
  pixDestroy(&pix_grey_);
  pixDestroy(&pix_thresholds_);
  pixDestroy(&scaled_color_);
  deskew_ = FCOORD(1.0f, 0.0f);
  reskew_ = FCOORD(1.0f, 0.0f);
  splitter_.Clear();
  scaled_factor_ = -1;
  for (int i = 0; i < sub_langs_.size(); ++i)
    sub_langs_[i]->Clear();
}

void Tesseract::SetEquationDetect(EquationDetect* detector) {
  equ_detect_ = detector;
  equ_detect_->SetLangTesseract(this);
}

// Clear all memory of adaption for this and all subclassifiers.
void Tesseract::ResetAdaptiveClassifier() {
  ResetAdaptiveClassifierInternal();
  for (int i = 0; i < sub_langs_.size(); ++i) {
    sub_langs_[i]->ResetAdaptiveClassifierInternal();
  }
}

// Clear the document dictionary for this and all subclassifiers.
void Tesseract::ResetDocumentDictionary() {
  getDict().ResetDocumentDictionary();
  for (int i = 0; i < sub_langs_.size(); ++i) {
    sub_langs_[i]->getDict().ResetDocumentDictionary();
  }
}

void Tesseract::SetBlackAndWhitelist() {
  // Set the white and blacklists (if any)
  unicharset.set_black_and_whitelist(tessedit_char_blacklist.string(),
                                     tessedit_char_whitelist.string(),
                                     tessedit_char_unblacklist.string());
  // Black and white lists should apply to all loaded classifiers.
  for (int i = 0; i < sub_langs_.size(); ++i) {
    sub_langs_[i]->unicharset.set_black_and_whitelist(
        tessedit_char_blacklist.string(), tessedit_char_whitelist.string(),
        tessedit_char_unblacklist.string());
  }
}

// Perform steps to prepare underlying binary image/other data structures for
// page segmentation.
void Tesseract::PrepareForPageseg() {
  textord_.set_use_cjk_fp_model(textord_use_cjk_fp_model);
  pixDestroy(&cube_binary_);
  cube_binary_ = pixClone(pix_binary());
  // Find the max splitter strategy over all langs.
  ShiroRekhaSplitter::SplitStrategy max_pageseg_strategy =
      static_cast<ShiroRekhaSplitter::SplitStrategy>(
      static_cast<inT32>(pageseg_devanagari_split_strategy));
  for (int i = 0; i < sub_langs_.size(); ++i) {
    ShiroRekhaSplitter::SplitStrategy pageseg_strategy =
        static_cast<ShiroRekhaSplitter::SplitStrategy>(
        static_cast<inT32>(sub_langs_[i]->pageseg_devanagari_split_strategy));
    if (pageseg_strategy > max_pageseg_strategy)
      max_pageseg_strategy = pageseg_strategy;
    // Clone the cube image to all the sub langs too.
    pixDestroy(&sub_langs_[i]->cube_binary_);
    sub_langs_[i]->cube_binary_ = pixClone(pix_binary());
    pixDestroy(&sub_langs_[i]->pix_binary_);
    sub_langs_[i]->pix_binary_ = pixClone(pix_binary());
  }
  // Perform shiro-rekha (top-line) splitting and replace the current image by
  // the newly splitted image.
  splitter_.set_orig_pix(pix_binary());
  splitter_.set_pageseg_split_strategy(max_pageseg_strategy);
  if (splitter_.Split(true)) {
    ASSERT_HOST(splitter_.splitted_image());
    pixDestroy(&pix_binary_);
    pix_binary_ = pixClone(splitter_.splitted_image());
  }
}

// Perform steps to prepare underlying binary image/other data structures for
// OCR. The current segmentation is required by this method.
// Note that this method resets pix_binary_ to the original binarized image,
// which may be different from the image actually used for OCR depending on the
// value of devanagari_ocr_split_strategy.
void Tesseract::PrepareForTessOCR(BLOCK_LIST* block_list,
                                  Tesseract* osd_tess, OSResults* osr) {
  // Find the max splitter strategy over all langs.
  ShiroRekhaSplitter::SplitStrategy max_ocr_strategy =
      static_cast<ShiroRekhaSplitter::SplitStrategy>(
      static_cast<inT32>(ocr_devanagari_split_strategy));
  for (int i = 0; i < sub_langs_.size(); ++i) {
    ShiroRekhaSplitter::SplitStrategy ocr_strategy =
        static_cast<ShiroRekhaSplitter::SplitStrategy>(
        static_cast<inT32>(sub_langs_[i]->ocr_devanagari_split_strategy));
    if (ocr_strategy > max_ocr_strategy)
      max_ocr_strategy = ocr_strategy;
  }
  // Utilize the segmentation information available.
  splitter_.set_segmentation_block_list(block_list);
  splitter_.set_ocr_split_strategy(max_ocr_strategy);
  // Run the splitter for OCR
  bool split_for_ocr = splitter_.Split(false);
  // Restore pix_binary to the binarized original pix for future reference.
  ASSERT_HOST(splitter_.orig_pix());
  pixDestroy(&pix_binary_);
  pix_binary_ = pixClone(splitter_.orig_pix());
  // If the pageseg and ocr strategies are different, refresh the block list
  // (from the last SegmentImage call) with blobs from the real image to be used
  // for OCR.
  if (splitter_.HasDifferentSplitStrategies()) {
    BLOCK block("", TRUE, 0, 0, 0, 0, pixGetWidth(pix_binary_),
                pixGetHeight(pix_binary_));
    Pix* pix_for_ocr = split_for_ocr ? splitter_.splitted_image() :
        splitter_.orig_pix();
    extract_edges(pix_for_ocr, &block);
    splitter_.RefreshSegmentationWithNewBlobs(block.blob_list());
  }
  // The splitter isn't needed any more after this, so save memory by clearing.
  splitter_.Clear();
}

}  // namespace tesseract


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Sagedia macrospora Miyoshi

### Remarks
null


text:
package com.emitrom.touch4j.client.core.handlers.component;

import com.emitrom.touch4j.client.core.Component;
import com.emitrom.touch4j.client.core.handlers.AbstractHandler;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.GWT.UncaughtExceptionHandler;
import com.google.gwt.core.client.JavaScriptObject;

public abstract class RightChangeHandler extends AbstractHandler {

    final JavaScriptObject jsoPeer = createPeer(this);

    private static native JavaScriptObject createPeer(RightChangeHandler listener) /*-{
		return function(component, existingValue, newValue, eOpts) {
			var comp = @com.emitrom.touch4j.client.core.Component::new(Lcom/google/gwt/core/client/JavaScriptObject;)(component);
			listener.@com.emitrom.touch4j.client.core.handlers.component.RightChangeHandler::onRightChange(Lcom/emitrom/touch4j/client/core/Component;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)(comp, existingValue, newValue, eOpts);
		};
    }-*/;

    @Override
    public JavaScriptObject getJsoPeer() {
        return jsoPeer;
    }

    // Called from JSNI
    private final void fireOnEvent(Component component, Object existingValue, Object newValue, Object eOpts) {
        UncaughtExceptionHandler handler = GWT.getUncaughtExceptionHandler();
        if (handler != null) {
            fireOnEventAndCatch(component, existingValue, newValue, eOpts, handler);
        } else {
            onRightChange(component, existingValue, newValue, eOpts);
        }
    }

    private void fireOnEventAndCatch(Component component, Object existingValue, Object newValue, Object eOpts,
                    UncaughtExceptionHandler handler) {
        try {
            onRightChange(component, existingValue, newValue, eOpts);
        } catch (Throwable e) {
            handler.onUncaughtException(e);
        }
    }

    public abstract void onRightChange(Component component, Object existingValue, Object newValue, Object eOpts);

}


text:
require 'rails_helper'

RSpec.describe CorsSupport, type: :concern do
  let(:cors_controller_class) { Class.new(UnauthenticatedApiController) { include CorsSupport } }
  subject { cors_controller_class.new }

  before(:each) do
    # HTTP_ORIGIN includes protocol and host
    allow(subject).to receive(:origin).and_return("https://my.domain.tld")
  end

  def allow_hosts(hosts)
    allow(subject).to receive(:whitelisted_hosts).and_return(hosts.join(','))
  end

  describe "cors_support" do
    it "allows from identical URI" do
      allow_hosts %w(https://my.domain.tld)

      expect(subject.send(:cors_allowed?)).to be_truthy
    end

    it "allows from identical host" do
      allow_hosts %w(my.domain.tld)

      expect(subject.send(:cors_allowed?)).to be_truthy
    end

    it "allows from matching, partial host" do
      allow_hosts %w(.domain.tld)

      expect(subject.send(:cors_allowed?)).to be_truthy
    end

    it "allows if any one domain matches" do
      allow_hosts %w(no.domain.tld nope.domain.tld .domain.tld)

      expect(subject.send(:cors_allowed?)).to be_truthy
    end

    it "denies if no domain matches" do
      allow_hosts %w(no.domain.tld nope.domain.tld)

      expect(subject.send(:cors_allowed?)).to be_falsey
    end
  end
end


text:
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Text.RegularExpressions;
using Moq.Matchers;
using System.Reflection;
using System.Linq;

namespace Moq.Protected
{
	///
	/// Allows the specification of a matching condition for an
	/// argument in a protected member setup, rather than a specific
	/// argument value. "ItExpr" refers to the argument being matched.
	///
	/// <remarks>
	/// <para>Use this variant of argument matching instead of
	/// <see cref="It"/> for protected setups.</para>
	/// This class allows the setup to match a method invocation
	/// with an arbitrary value, with a value in a specified range, or
	/// even one that matches a given predicate, or null.
	/// </remarks>
	[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Expr")]
	public static class ItExpr
	{
		///
		/// Contains matchers for <see langword="ref"/> (C#) / <see langword="ByRef"/> (VB.NET) parameters of type <typeparamref name="TValue"/>.
		///
		/// <typeparam name="TValue">The parameter type.</typeparam>
		public static class Ref<TValue>
		{
			///
			/// Matches any value that is assignment-compatible with type <typeparamref name="TValue"/>.
			///
			/// <returns></returns>
			public static Expression IsAny
			{
				get
				{
					Expression<Func<TValue>> expr = () => It.Ref<TValue>.IsAny;
					return expr.Body;
				}
			}
		}

		///
		/// Matches a null value of the given <typeparamref name="TValue"/> type.
		///
		/// <remarks>
		/// Required for protected mocks as the null value cannot be used
		/// directly as it prevents proper method overload selection.
		/// </remarks>
		/// <example>
		///
		/// // Throws an exception for a call to Remove with a null string value.
		/// mock.Protected()
		///     .Setup("Remove", ItExpr.IsNull<string>())
		///     .Throws(new InvalidOperationException());
		///
		/// </example>
		/// <typeparam name="TValue">Type of the value.</typeparam>
		[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
		[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
		public static Expression IsNull<TValue>()
		{
			Expression<Func<TValue>> expr = () => It.Is<TValue>(v => Object.Equals(v, default(TValue)));

			return expr.Body;
		}

		///
		/// Matches any value of the given <typeparamref name="TValue"/> type.
		///
		/// <remarks>
		/// Typically used when the actual argument value for a method
		/// call is not relevant.
		/// </remarks>
		/// <example>
		///
		/// // Throws an exception for a call to Remove with any string value.
		/// mock.Protected()
		///     .Setup("Remove", ItExpr.IsAny<string>())
		///     .Throws(new InvalidOperationException());
		///
		/// </example>
		/// <typeparam name="TValue">Type of the value.</typeparam>
		[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
		[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
		public static Expression IsAny<TValue>()
		{
			Expression<Func<TValue>> expr = () => It.IsAny<TValue>();
			return expr.Body;
		}

		///
		/// Matches any value that satisfies the given predicate.
		///
		/// <typeparam name="TValue">Type of the argument to check.</typeparam>
		/// <param name="match">The predicate used to match the method argument.</param>
		/// <remarks>
		/// Allows the specification of a predicate to perform matching
		/// of method call arguments.
		/// </remarks>
		/// <example>
		/// This example shows how to return the value <c>1</c> whenever the argument to the
		/// <c>Do</c> method is an even number.
		///
		/// mock.Protected()
		///     .Setup("Do", ItExpr.Is<int>(i => i % 2 == 0))
		///     .Returns(1);
		///
		/// This example shows how to throw an exception if the argument to the
		/// method is a negative number:
		///
		/// mock.Protected()
		///     .Setup("GetUser", ItExpr.Is<int>(i => i < 0))
		///     .Throws(new ArgumentException());
		///
		/// </example>
		[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
		public static Expression Is<TValue>(Expression<Func<TValue, bool>> match)
		{
			Expression<Func<TValue>> expr = () => It.Is((Expression<Func<TValue, bool>>)null);
			return Expression.Call(((MethodCallExpression)expr.Body).Method, match);
		}

		///
		/// Matches any value that is in the range specified.
		///
		/// <typeparam name="TValue">Type of the argument to check.</typeparam>
		/// <param name="from">The lower bound of the range.</param>
		/// <param name="to">The upper bound of the range.</param>
		/// <param name="rangeKind">The kind of range. See <see cref="Range"/>.</param>
		/// <example>
		/// The following example shows how to expect a method call
		/// with an integer argument within the 0..100 range.
		///
		/// mock.Protected()
		///     .Setup("HasInventory",
		///             ItExpr.IsAny<string>(),
		///             ItExpr.IsInRange(0, 100, Range.Inclusive))
		///     .Returns(false);
		///
		/// </example>
		public static Expression IsInRange<TValue>(TValue from, TValue to, Range rangeKind)
			where TValue : IComparable
		{
			Expression<Func<TValue>> expr = () => It.IsInRange<TValue>(from, to, rangeKind);

			return expr.Body;
		}

		///
		/// Matches a string argument if it matches the given regular expression pattern.
		///
		/// <param name="regex">The pattern to use to match the string argument value.</param>
		/// <example>
		/// The following example shows how to expect a call to a method where the
		/// string argument matches the given regular expression:
		///
		/// mock.Protected()
		///     .Setup("Check", ItExpr.IsRegex("[a-z]+"))
		///     .Returns(1);
		///
		/// </example>
		public static Expression IsRegex(string regex)
		{
			Expression<Func<string>> expr = () => It.IsRegex(regex);

			return expr.Body;
		}

		///
		/// Matches a string argument if it matches the given regular expression pattern.
		///
		/// <param name="regex">The pattern to use to match the string argument value.</param>
		/// <param name="options">The options used to interpret the pattern.</param>
		/// <example>
		/// The following example shows how to expect a call to a method where the
		/// string argument matches the given regular expression, in a case insensitive way:
		///
		/// mock.Protected()
		///     .Setup("Check", ItExpr.IsRegex("[a-z]+", RegexOptions.IgnoreCase))
		///     .Returns(1);
		///
		/// </example>
		public static Expression IsRegex(string regex, RegexOptions options)
		{
			Expression<Func<string>> expr = () => It.IsRegex(regex, options);

			return expr.Body;
		}
	}
}


text:
/**
 * Demonstrates how to use named values in template parameters.
 *
 * The boost parameter library is designed to use named types for template
 * parameters. This shows how to use values instead.
 *
 * Limitation: it appears that a maximum of 8 template parameters can be used.
 */
#ifndef TEMPLATE_NAMED_VALUES_HPP_
#define TEMPLATE_NAMED_VALUES_HPP_

#include <ratio>

#include <boost/parameter/keyword.hpp>
#include <boost/parameter/name.hpp>
#include <boost/parameter/preprocessor.hpp>
#include <boost/parameter.hpp>
#include <boost/mpl/placeholders.hpp>

#include <cpp_named_params/template_named_value_macros.hpp>

using boost::mpl::placeholders::_;
using boost::parameter::parameters;
using boost::parameter::required;
using boost::parameter::optional;
using boost::parameter::void_;

namespace rb {

// Create the keywords
PARAMETER_TEMPLATE_KEYWORD_SIZE(width)
PARAMETER_TEMPLATE_KEYWORD_SIZE(height)
PARAMETER_TEMPLATE_KEYWORD_RATIO(scale)

// Create the template signature
using rectangle_signature = parameters<
    required<tag::width, std::is_object<_>>,
    required<tag::height, std::is_object<_>>,
    required<tag::scale, std::is_object<_>>
>;

/**
 * Rectangle that has width, height and scale. Area is computed at compile
 * time.
 */
template <class A, class B, class C>
struct rectangle {
    using args = typename rb::rectangle_signature::bind<
        A, B, C
    >::type;

    // Create accessors
    PARAMETER_TEMPLATE_ACCESSOR_SIZE(width)
    PARAMETER_TEMPLATE_ACCESSOR_SIZE(height)
    PARAMETER_TEMPLATE_ACCESSOR_RATIO(scale, float)

    /**
     * Constructor
     */
    rectangle() {
        if (validate_template()) {
            // Do something only if template validates
        }
    }

    /**
     * Validate the template parameters
     *
     * @return true if template parameters validated, false otherwise
     */
    static constexpr bool validate_template() {
        constexpr bool width_gt_0 = width() > 0;
        constexpr bool height_gt_0 = height() > 0;

        static_assert(width_gt_0, "width must be greater than 0");
        static_assert(height_gt_0, "height must be greater than 0");

        return width_gt_0 && height_gt_0;
    }

    /**
     * The area of the rectangle. The return value is calculated at compile
     * time. The compile time calculation is guaranteed by the constexpr
     * keyword.
     *
     * @return the area of the rectangle
     */
    static constexpr auto
    area() -> decltype (width() * height()) {
        return width() * height();
    }
};

} // namespace rb

#endif /* end of include guard: TEMPLATE_NAMED_VALUES_HPP_ */