text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.redkale.convert;

import java.io.File;
import java.lang.reflect.*;
import java.math.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.CompletionHandler;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.*;
import java.util.regex.Pattern;
import java.util.stream.*;
import org.redkale.convert.bson.BsonConvert;
import org.redkale.convert.ext.*;
import org.redkale.convert.json.JsonConvert;
import org.redkale.util.*;

/**
 * 序列化模块的工厂类,用于注册自定义的序列化类型,获取Convert
 *
 *

 * 详情见: https://redkale.org
 *
 * @author zhangjx
 * @param <R> Reader输入的子类
 * @param <W> Writer输出的子类
 */
@SuppressWarnings("unchecked")
public abstract class ConvertFactory<R extends Reader, W extends Writer> {

    private static final AtomicBoolean loaderInited = new AtomicBoolean();

    private static Convert defProtobufConvert;

    private final ConvertFactory parent;

    protected Convert<R, W> convert;

    protected boolean tiny;

    private final Encodeable<W, ?> anyEncoder = new AnyEncoder(this);

    //-----------------------------------------------------------------------------------
    private final ConcurrentHashMap<Class, Creator> creators = new ConcurrentHashMap();

    private final ConcurrentHashMap<String, Class> entitys = new ConcurrentHashMap();

    private final ConcurrentHashMap<Type, Map<String, SimpledCoder<R, W, ?>>> fieldCoders = new ConcurrentHashMap();

    private final ConcurrentHashMap<Type, Decodeable<R, ?>> decoders = new ConcurrentHashMap();

    private final ConcurrentHashMap<Type, Encodeable<W, ?>> encoders = new ConcurrentHashMap();

    private final ConcurrentHashMap<AccessibleObject, ConvertColumnEntry> columnEntrys = new ConcurrentHashMap();

    private final Set<Class> skipIgnores = new HashSet();

    //key:需要屏蔽的字段;value:排除的字段名
    private final ConcurrentHashMap<Class, Set<String>> ignoreAlls = new ConcurrentHashMap();

    private boolean skipAllIgnore = false;

    protected ConvertFactory(ConvertFactory<R, W> parent, boolean tiny) {
        this.tiny = tiny;
        this.parent = parent;
        if (parent == null) {
            //---------------------------------------------------------
            this.register(boolean.class, BoolSimpledCoder.instance);
            this.register(Boolean.class, BoolSimpledCoder.instance);

            this.register(byte.class, ByteSimpledCoder.instance);
            this.register(Byte.class, ByteSimpledCoder.instance);

            this.register(short.class, ShortSimpledCoder.instance);
            this.register(Short.class, ShortSimpledCoder.instance);

            this.register(char.class, CharSimpledCoder.instance);
            this.register(Character.class, CharSimpledCoder.instance);

            this.register(int.class, IntSimpledCoder.instance);
            this.register(Integer.class, IntSimpledCoder.instance);

            this.register(long.class, LongSimpledCoder.instance);
            this.register(Long.class, LongSimpledCoder.instance);

            this.register(float.class, FloatSimpledCoder.instance);
            this.register(Float.class, FloatSimpledCoder.instance);

            this.register(double.class, DoubleSimpledCoder.instance);
            this.register(Double.class, DoubleSimpledCoder.instance);

            this.register(Number.class, NumberSimpledCoder.instance);
            this.register(String.class, StringSimpledCoder.instance);
            this.register(StringWrapper.class, StringWrapperSimpledCoder.instance);
            this.register(CharSequence.class, CharSequenceSimpledCoder.instance);
            this.register(StringBuilder.class, CharSequenceSimpledCoder.StringBuilderSimpledCoder.instance);
            this.register(java.util.Date.class, DateSimpledCoder.instance);
            this.register(java.time.Duration.class, DurationSimpledCoder.instance);
            this.register(AtomicInteger.class, AtomicIntegerSimpledCoder.instance);
            this.register(AtomicLong.class, AtomicLongSimpledCoder.instance);
            this.register(BigInteger.class, BigIntegerSimpledCoder.instance);
            this.register(BigDecimal.class, BigDecimalSimpledCoder.instance);
            this.register(InetAddress.class, InetAddressSimpledCoder.instance);
            this.register(DLong.class, DLongSimpledCoder.instance);
            this.register(Class.class, TypeSimpledCoder.instance);
            this.register(InetSocketAddress.class, InetAddressSimpledCoder.InetSocketAddressSimpledCoder.instance);
            this.register(Pattern.class, PatternSimpledCoder.instance);
            this.register(File.class, FileSimpledCoder.instance);
            this.register(CompletionHandler.class, CompletionHandlerSimpledCoder.instance);
            this.register(URL.class, URLSimpledCoder.instance);
            this.register(URI.class, URISimpledCoder.instance);
            //---------------------------------------------------------
            this.register(ByteBuffer.class, ByteBufferSimpledCoder.instance);
            this.register(boolean[].class, BoolArraySimpledCoder.instance);
            this.register(byte[].class, ByteArraySimpledCoder.instance);
            this.register(short[].class, ShortArraySimpledCoder.instance);
            this.register(char[].class, CharArraySimpledCoder.instance);
            this.register(int[].class, IntArraySimpledCoder.instance);
            this.register(IntStream.class, IntArraySimpledCoder.IntStreamSimpledCoder.instance);
            this.register(long[].class, LongArraySimpledCoder.instance);
            this.register(LongStream.class, LongArraySimpledCoder.LongStreamSimpledCoder.instance);
            this.register(float[].class, FloatArraySimpledCoder.instance);
            this.register(double[].class, DoubleArraySimpledCoder.instance);
            this.register(DoubleStream.class, DoubleArraySimpledCoder.DoubleStreamSimpledCoder.instance);
            this.register(String[].class, StringArraySimpledCoder.instance);
            //---------------------------------------------------------
            this.register(AnyValue.class, Creator.create(AnyValue.DefaultAnyValue.class));
            this.register(HttpCookie.class, new Creator<HttpCookie>() {
                @Override
                @ConstructorParameters({"name", "value"})
                public HttpCookie create(Object... params) {
                    return new HttpCookie((String) params[0], (String) params[1]);
                }

            });
            try {
                Class sqldateClass = Class.forName("java.sql.Date");
                this.register(sqldateClass, new SimpledCoder<R, W, java.sql.Date>() {

                    @Override
                    public void convertTo(W out, java.sql.Date value) {
                        out.writeSmallString(value == null ? null : value.toString());
                    }

                    @Override
                    public java.sql.Date convertFrom(R in) {
                        String t = in.readSmallString();
                        return t == null ? null : java.sql.Date.valueOf(t);
                    }

                });
                Class sqltimeClass = Class.forName("java.sql.Time");
                this.register(sqltimeClass, new SimpledCoder<R, W, java.sql.Time>() {

                    @Override
                    public void convertTo(W out, java.sql.Time value) {
                        out.writeSmallString(value == null ? null : value.toString());
                    }

                    @Override
                    public java.sql.Time convertFrom(R in) {
                        String t = in.readSmallString();
                        return t == null ? null : java.sql.Time.valueOf(t);
                    }

                });
                Class timestampClass = Class.forName("java.sql.Timestamp");
                this.register(timestampClass, new SimpledCoder<R, W, java.sql.Timestamp>() {

                    @Override
                    public void convertTo(W out, java.sql.Timestamp value) {
                        out.writeSmallString(value == null ? null : value.toString());
                    }

                    @Override
                    public java.sql.Timestamp convertFrom(R in) {
                        String t = in.readSmallString();
                        return t == null ? null : java.sql.Timestamp.valueOf(t);
                    }

                });
            } catch (Throwable t) {
            }
        }
    }

    public ConvertFactory parent() {
        return this.parent;
    }

    public static Convert findConvert(ConvertType type) {
        if (type == null) return null;
        if (type == ConvertType.JSON) return JsonConvert.root();
        if (type == ConvertType.BSON) return BsonConvert.root();
        if (loaderInited.get()) {
            if (type == ConvertType.PROTOBUF) return defProtobufConvert;
        }
        synchronized (loaderInited) {
            if (!loaderInited.get()) {
                Iterator<ConvertLoader> it = ServiceLoader.load(ConvertLoader.class).iterator();
                while (it.hasNext()) {
                    ConvertLoader cl = it.next();
                    if (cl.type() == ConvertType.PROTOBUF) defProtobufConvert = cl.convert();
                }
                loaderInited.set(true);
            }
        }
        return type == ConvertType.PROTOBUF ? defProtobufConvert : null;
    }

    protected static boolean getSystemPropertyBoolean(String key, String parentkey, boolean defvalue) {
        return Boolean.parseBoolean(System.getProperty(key, System.getProperty(parentkey, String.valueOf(defvalue))));
    }

    public abstract ConvertType getConvertType();

    public abstract boolean isReversible(); //是否可逆的

    public abstract boolean isFieldSort(); //当ConvertColumn.index相同时是否按字段名称排序

    public abstract ConvertFactory createChild();

    public abstract ConvertFactory createChild(boolean tiny);

    protected SimpledCoder createEnumSimpledCoder(Class enumClass) {
        return new EnumSimpledCoder(enumClass);
    }

    protected ObjectDecoder createObjectDecoder(Type type) {
        return new ObjectDecoder(type);
    }

    protected ObjectEncoder createObjectEncoder(Type type) {
        return new ObjectEncoder(type);
    }

    protected <E> Decodeable<R, E> createMapDecoder(Type type) {
        return new MapDecoder(this, type);
    }

    protected <E> Encodeable<W, E> createMapEncoder(Type type) {
        return new MapEncoder(this, type);
    }

    protected <E> Decodeable<R, E> createArrayDecoder(Type type) {
        return new ArrayDecoder(this, type);
    }

    protected <E> Encodeable<W, E> createArrayEncoder(Type type) {
        return new ArrayEncoder(this, type);
    }

    protected <E> Decodeable<R, E> createCollectionDecoder(Type type) {
        return new CollectionDecoder(this, type);
    }

    protected <E> Encodeable<W, E> createCollectionEncoder(Type type) {
        return new CollectionEncoder(this, type);
    }

    protected <E> Decodeable<R, E> createStreamDecoder(Type type) {
        return new StreamDecoder(this, type);
    }

    protected <E> Encodeable<W, E> createStreamEncoder(Type type) {
        return new StreamEncoder(this, type);
    }

    public Convert getConvert() {
        return convert;
    }

    public ConvertFactory tiny(boolean tiny) {
        this.tiny = tiny;
        return this;
    }

    public boolean isConvertDisabled(AccessibleObject element) {
        ConvertDisabled[] ccs = element.getAnnotationsByType(ConvertDisabled.class);
        if (ccs.length == 0 && element instanceof Method) {
            final Method method = (Method) element;
            String fieldName = readGetSetFieldName(method);
            if (fieldName != null) {
                try {
                    ccs = method.getDeclaringClass().getDeclaredField(fieldName).getAnnotationsByType(ConvertDisabled.class);
                } catch (Exception e) { //说明没有该字段,忽略异常
                }
            }
        }
        final ConvertType ct = this.getConvertType();
        for (ConvertDisabled ref : ccs) {
            if (ref.type().contains(ct)) return true;
        }
        return false;
    }

    public ConvertColumnEntry findRef(Class clazz, AccessibleObject element) {
        if (element == null) return null;
        ConvertColumnEntry en = this.columnEntrys.get(element);
        Set<String> onlyColumns = ignoreAlls.get(clazz);
        if (en != null && onlyColumns == null) return en;
        final ConvertType ct = this.getConvertType();
        ConvertColumn[] ccs = element.getAnnotationsByType(ConvertColumn.class);
        String fieldName = null;
        if (ccs.length == 0 && element instanceof Method) {
            final Method method = (Method) element;
            fieldName = readGetSetFieldName(method);
            if (fieldName != null) {
                Class mclz = method.getDeclaringClass();
                do {
                    try {
                        ccs = mclz.getDeclaredField(fieldName).getAnnotationsByType(ConvertColumn.class);
                        break;
                    } catch (Exception e) { //说明没有该字段,忽略异常
                    }
                } while (mclz != Object.class && (mclz = mclz.getSuperclass()) != Object.class);
            }
        }
        if (onlyColumns != null && fieldName == null) {
            if (element instanceof Method) {
                fieldName = readGetSetFieldName((Method) element);
            } else if (element instanceof Field) {
                fieldName = ((Field) element).getName();
            }
        }
        if (ccs.length == 0 && onlyColumns != null && fieldName != null) {
            if (!onlyColumns.contains(fieldName)) return new ConvertColumnEntry(fieldName, true);
        }
        for (ConvertColumn ref : ccs) {
            if (ref.type().contains(ct)) {
                String realName = ref.name().isEmpty() ? fieldName : ref.name();
                if (onlyColumns != null && fieldName != null) {
                    if (!onlyColumns.contains(realName)) return new ConvertColumnEntry(realName, true);
                }
                ConvertColumnEntry entry = new ConvertColumnEntry(ref);
                if (skipAllIgnore) {
                    entry.setIgnore(false);
                    return entry;
                }
                if (skipIgnores.isEmpty()) {
                    if (onlyColumns != null && realName != null && onlyColumns.contains(realName)) entry.setIgnore(false);
                    return entry;
                }
                if (skipIgnores.contains(((Member) element).getDeclaringClass())) entry.setIgnore(false);
                return entry;
            }
        }
        return null;
    }

    static String readGetSetFieldName(Method method) {
        if (method == null) return null;
        String fname = method.getName();
        if (!fname.startsWith("is") && !fname.startsWith("get") && !fname.startsWith("set")) return fname;
        fname = fname.substring(fname.startsWith("is") ? 2 : 3);
        if (fname.length() > 1 && !(fname.charAt(1) >= 'A' && fname.charAt(1) <= 'Z')) {
            fname = Character.toLowerCase(fname.charAt(0)) + fname.substring(1);
        } else if (fname.length() == 1) {
            fname = "" + Character.toLowerCase(fname.charAt(0));
        }
        return fname;
    }

    final String getEntityAlias(Class clazz) {
        if (clazz == String.class) return "A";
        if (clazz == int.class) return "I";
        if (clazz == Integer.class) return "i";
        if (clazz == long.class) return "J";
        if (clazz == Long.class) return "j";
        if (clazz == byte.class) return "B";
        if (clazz == Byte.class) return "b";
        if (clazz == boolean.class) return "Z";
        if (clazz == Boolean.class) return "z";
        if (clazz == short.class) return "S";
        if (clazz == Short.class) return "s";
        if (clazz == char.class) return "C";
        if (clazz == Character.class) return "c";
        if (clazz == float.class) return "F";
        if (clazz == Float.class) return "f";
        if (clazz == double.class) return "D";
        if (clazz == Double.class) return "d";

        if (clazz == String[].class) return "[A";
        if (clazz == int[].class) return "[I";
        if (clazz == long[].class) return "[J";
        if (clazz == byte[].class) return "[B";
        if (clazz == boolean[].class) return "[Z";
        if (clazz == short[].class) return "[S";
        if (clazz == char[].class) return "[C";
        if (clazz == float[].class) return "[F";
        if (clazz == double[].class) return "[D";

        ConvertEntity ce = (ConvertEntity) clazz.getAnnotation(ConvertEntity.class);
        if (ce != null && findEntityAlias(ce.value()) == null) entitys.put(ce.value(), clazz);
        return ce == null ? clazz.getName() : ce.value();
    }

    final Class getEntityAlias(String name) {
        if ("A".equals(name)) return String.class;
        if ("I".equals(name)) return int.class;
        if ("i".equals(name)) return Integer.class;
        if ("J".equals(name)) return long.class;
        if ("j".equals(name)) return Long.class;
        if ("B".equals(name)) return byte.class;
        if ("b".equals(name)) return Byte.class;
        if ("Z".equals(name)) return boolean.class;
        if ("z".equals(name)) return Boolean.class;
        if ("S".equals(name)) return short.class;
        if ("s".equals(name)) return Short.class;
        if ("C".equals(name)) return char.class;
        if ("c".equals(name)) return Character.class;
        if ("F".equals(name)) return float.class;
        if ("f".equals(name)) return Float.class;
        if ("D".equals(name)) return double.class;
        if ("d".equals(name)) return Double.class;

        if ("[A".equals(name)) return String[].class;
        if ("[I".equals(name)) return int[].class;
        if ("[J".equals(name)) return long[].class;
        if ("[B".equals(name)) return byte[].class;
        if ("[Z".equals(name)) return boolean[].class;
        if ("[S".equals(name)) return short[].class;
        if ("[C".equals(name)) return char[].class;
        if ("[F".equals(name)) return float[].class;
        if ("[D".equals(name)) return double[].class;

        Class clazz = findEntityAlias(name);
        try {
            return clazz == null ? Thread.currentThread().getContextClassLoader().loadClass(name) : clazz;
        } catch (Exception ex) {
            throw new ConvertException("convert entity is " + name, ex);
        }
    }

    private Class findEntityAlias(String name) {
        Class clazz = entitys.get(name);
        return parent == null ? clazz : parent.findEntityAlias(name);
    }

    /**
     * 使所有类的所有被声明为ConvertColumn.ignore = true 的字段或方法变为ConvertColumn.ignore = false
     *
     * @param skipIgnore 是否忽略Ignore注解
     */
    public final void registerSkipAllIgnore(final boolean skipIgnore) {
        this.skipAllIgnore = skipIgnore;
    }

    /**
     * 使所有类的所有被声明为ConvertColumn.ignore = true 的字段或方法变为ConvertColumn.ignore = false
     *
     * @param skipIgnore 忽略ignore
     *
     * @return 自身
     */
    public ConvertFactory<R, W> skipAllIgnore(final boolean skipIgnore) {
        this.skipAllIgnore = skipIgnore;
        return this;
    }

    /**
     * 使该类所有被声明为ConvertColumn.ignore = true 的字段或方法变为ConvertColumn.ignore = false
     *
     * @param type 指定的类
     */
    public final void registerSkipIgnore(final Class type) {
        skipIgnores.add(type);
    }

    /**
     * 屏蔽指定类所有字段,仅仅保留指定字段

     * 注意: 该配置优先级高于skipAllIgnore和ConvertColumnEntry配置
     *
     * @param type           指定的类
     * @param excludeColumns 需要排除的字段名
     */
    public final void registerIgnoreAll(final Class type, String... excludeColumns) {
        Set<String> set = ignoreAlls.get(type);
        if (set == null) {
            ignoreAlls.put(type, new HashSet<>(Arrays.asList(excludeColumns)));
        } else {
            set.addAll(Arrays.asList(excludeColumns));
        }
    }

    public final void registerIgnoreAll(final Class type, Collection<String> excludeColumns) {
        Set<String> set = ignoreAlls.get(type);
        if (set == null) {
            ignoreAlls.put(type, new HashSet<>(excludeColumns));
        } else {
            set.addAll(new ArrayList(excludeColumns));
        }
    }

    public final void register(final Class type, boolean ignore, String... columns) {
        for (String column : columns) {
            register(type, column, new ConvertColumnEntry(column, ignore));
        }
    }

    public final void register(final Class type, boolean ignore, Collection<String> columns) {
        for (String column : columns) {
            register(type, column, new ConvertColumnEntry(column, ignore));
        }
    }

    public final boolean register(final Class type, String column, String alias) {
        return register(type, column, new ConvertColumnEntry(alias));
    }

    public final boolean register(final Class type, String column, ConvertColumnEntry entry) {
        if (type == null || column == null || entry == null) return false;
        Field field = null;
        try {
            field = type.getDeclaredField(column);
        } catch (Exception e) {
        }
        String get = "get";
        if (field != null && (field.getType() == boolean.class || field.getType() == Boolean.class)) get = "is";
        char[] cols = column.toCharArray();
        cols[0] = Character.toUpperCase(cols[0]);
        final String bigColumn = new String(cols);
        try {
            register(type.getMethod(get + bigColumn), entry);
        } catch (NoSuchMethodException mex) {
            if (get.length() >= 3) { //get
                try {
                    register(type.getMethod("is" + bigColumn), entry);
                } catch (Exception ex) {
                }
            }
        } catch (Exception ex) {
        }
        try {
            register(type.getMethod("set" + bigColumn, field.getType()), entry);
        } catch (Exception ex) {
        }
        return field == null ? true : register(field, entry);
    }

    public final <E> boolean register(final AccessibleObject field, final ConvertColumnEntry entry) {
        if (field == null || entry == null) return false;
        this.columnEntrys.put(field, entry);
        return true;
    }

    public final void reloadCoder(final Type type) {
        this.register(type, this.createDecoder(type));
        this.register(type, this.createEncoder(type));
    }

    public final void reloadCoder(final Type type, final Class clazz) {
        this.register(type, this.createDecoder(type, clazz));
        this.register(type, this.createEncoder(type, clazz));
    }

    public final <E> void register(final Class<E> clazz, final Creator<? extends E> creator) {
        creators.put(clazz, creator);
    }

    public final <T> Creator<T> findCreator(Class<T> type) {
        Creator<T> creator = creators.get(type);
        if (creator != null) return creator;
        return this.parent == null ? null : this.parent.findCreator(type);
    }

    public final <T> Creator<T> loadCreator(Class<T> type) {
        Creator result = findCreator(type);
        if (result == null) {
            result = Creator.create(type);
            if (result != null) creators.put(type, result);
        }
        return result;
    }

    //----------------------------------------------------------------------
    public final <E> Encodeable<W, E> getAnyEncoder() {
        return (Encodeable<W, E>) anyEncoder;
    }

    public final <E> void register(final Type clazz, final SimpledCoder<R, W, E> coder) {
        decoders.put(clazz, coder);
        encoders.put(clazz, coder);
    }

    public final <E> void register(final Type clazz, final Decodeable<R, E> decoder, final Encodeable<W, E> encoder) {
        decoders.put(clazz, decoder);
        encoders.put(clazz, encoder);
    }

    public final <E> void register(final Type clazz, final Decodeable<R, E> decoder) {
        decoders.put(clazz, decoder);
    }

    public final <E> void register(final Type clazz, final Encodeable<W, E> encoder) {
        encoders.put(clazz, encoder);
    }

    //coder = null表示删除该字段的指定SimpledCoder
    public final <E> void register(final Class clazz, final String field, final SimpledCoder<R, W, E> coder) {
        if (field == null || clazz == null) return;
        try {
            clazz.getDeclaredField(field);
        } catch (Exception e) {
            throw new RuntimeException(clazz + " not found field(" + field + ")");
        }
        if (coder == null) {
            Map map = this.fieldCoders.get(clazz);
            if (map != null) map.remove(field);
        } else {
            this.fieldCoders.computeIfAbsent(clazz, c -> new ConcurrentHashMap<>()).put(field, coder);
        }
    }

    public final <E> SimpledCoder<R, W, E> findFieldCoder(final Type clazz, final String field) {
        if (field == null) return null;
        Map<String, SimpledCoder<R, W, ?>> map = this.fieldCoders.get(clazz);
        if (map == null) return parent == null ? null : parent.findFieldCoder(clazz, field);
        return (SimpledCoder) map.get(field);
    }

    public final <E> Decodeable<R, E> findDecoder(final Type type) {
        Decodeable<R, E> rs = (Decodeable<R, E>) decoders.get(type);
        if (rs != null) return rs;
        return this.parent == null ? null : this.parent.findDecoder(type);
    }

    public final <E> Encodeable<W, E> findEncoder(final Type type) {
        Encodeable<W, E> rs = (Encodeable<W, E>) encoders.get(type);
        if (rs != null) return rs;
        return this.parent == null ? null : this.parent.findEncoder(type);
    }

    public final <E> Decodeable<R, E> loadDecoder(final Type type) {
        Decodeable<R, E> decoder = findDecoder(type);
        if (decoder != null) return decoder;
        if (type instanceof GenericArrayType) return createArrayDecoder(type);
        Class clazz;
        if (type instanceof ParameterizedType) {
            final ParameterizedType pts = (ParameterizedType) type;
            clazz = (Class) (pts).getRawType();
        } else if (type instanceof TypeVariable) { // e.g.  <? extends E>
            final TypeVariable tv = (TypeVariable) type;
            Class cz = tv.getBounds().length == 0 ? Object.class : null;
            for (Type f : tv.getBounds()) {
                if (f instanceof Class) {
                    cz = (Class) f;
                    break;
                }
            }
            clazz = cz;
            if (cz == null) throw new ConvertException("not support the type (" + type + ")");
        } else if (type instanceof WildcardType) { // e.g. <? extends Serializable>
            final WildcardType wt = (WildcardType) type;
            Class cz = null;
            for (Type f : wt.getUpperBounds()) {
                if (f instanceof Class) {
                    cz = (Class) f;
                    break;
                }
            }
            clazz = cz;
            if (cz == null) throw new ConvertException("not support the type (" + type + ")");
        } else if (type instanceof Class) {
            clazz = (Class) type;
        } else {
            throw new ConvertException("not support the type (" + type + ")");
        }
        //此处不能再findDecoder,否则type与class不一致, 如: RetResult 和 RetResult<Integer>
        return createDecoder(type, clazz);
    }

    public final <E> Decodeable<R, E> createDecoder(final Type type) {
        Class clazz;
        if (type instanceof ParameterizedType) {
            final ParameterizedType pts = (ParameterizedType) type;
            clazz = (Class) (pts).getRawType();
        } else if (type instanceof Class) {
            clazz = (Class) type;
        } else {
            throw new ConvertException("not support the type (" + type + ")");
        }
        return createDecoder(type, clazz);
    }

    private <E> Decodeable<R, E> createDecoder(final Type type, final Class clazz) {
        Decodeable<R, E> decoder = null;
        ObjectDecoder od = null;
        if (clazz.isEnum()) {
            decoder = createEnumSimpledCoder(clazz);
        } else if (clazz.isArray()) {
            decoder = createArrayDecoder(type);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            decoder = createCollectionDecoder(type);
        } else if (Stream.class.isAssignableFrom(clazz)) {
            decoder = createStreamDecoder(type);
        } else if (Map.class.isAssignableFrom(clazz)) {
            decoder = createMapDecoder(type);
        } else if (Optional.class == clazz) {
            decoder = new OptionalCoder(this, type);
        } else if (clazz == Object.class) {
            od = createObjectDecoder(type);
            decoder = od;
        } else if (!clazz.getName().startsWith("java.")
            || java.net.HttpCookie.class == clazz
            || java.util.AbstractMap.SimpleEntry.class == clazz
            || clazz.getName().startsWith("java.awt.geom.Point2D")) {
            Decodeable simpleCoder = null;
            for (final Method method : clazz.getDeclaredMethods()) {
                if (!Modifier.isStatic(method.getModifiers())) continue;
                Class[] paramTypes = method.getParameterTypes();
                if (paramTypes.length != 1) continue;
                if (paramTypes[0] != ConvertFactory.class && paramTypes[0] != this.getClass()) continue;
                if (!Decodeable.class.isAssignableFrom(method.getReturnType())) continue;
                try {
                    method.setAccessible(true);
                    simpleCoder = (Decodeable) method.invoke(null, this);
                    break;
                } catch (Exception e) {
                }
            }
            if (simpleCoder == null) {
                od = createObjectDecoder(type);
                decoder = od;
            } else {
                decoder = simpleCoder;
            }
        }
        if (decoder == null) throw new ConvertException("not support the type (" + type + ")");
        register(type, decoder);
        if (od != null) od.init(this);
        return decoder;
    }

    public final <E> Encodeable<W, E> loadEncoder(final Type type) {
        Encodeable<W, E> encoder = findEncoder(type);
        if (encoder != null) return encoder;
        if (type instanceof GenericArrayType) return createArrayEncoder(type);
        Class clazz;
        if (type instanceof ParameterizedType) {
            final ParameterizedType pts = (ParameterizedType) type;
            clazz = (Class) (pts).getRawType();
        } else if (type instanceof TypeVariable) {
            TypeVariable tv = (TypeVariable) type;
            Type t = Object.class;
            if (tv.getBounds().length == 1) {
                t = tv.getBounds()[0];
            }
            if (!(t instanceof Class)) t = Object.class;
            clazz = (Class) t;
        } else if (type instanceof Class) {
            clazz = (Class) type;
        } else {
            throw new ConvertException("not support the type (" + type + ")");
        }
        //此处不能再findEncoder,否则type与class不一致, 如: RetResult 和 RetResult<Integer>
        return createEncoder(type, clazz);
    }

    public final <E> Encodeable<W, E> createEncoder(final Type type) {
        Class clazz;
        if (type instanceof ParameterizedType) {
            final ParameterizedType pts = (ParameterizedType) type;
            clazz = (Class) (pts).getRawType();
        } else if (type instanceof Class) {
            clazz = (Class) type;
        } else {
            throw new ConvertException("not support the type (" + type + ")");
        }
        return createEncoder(type, clazz);
    }

    private <E> Encodeable<W, E> createEncoder(final Type type, final Class clazz) {
        Encodeable<W, E> encoder = null;
        ObjectEncoder oe = null;
        if (clazz.isEnum()) {
            encoder = createEnumSimpledCoder(clazz);
        } else if (clazz.isArray()) {
            encoder = createArrayEncoder(type);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            encoder = createCollectionEncoder(type);
        } else if (Stream.class.isAssignableFrom(clazz)) {
            encoder = createStreamEncoder(type);
        } else if (Map.class.isAssignableFrom(clazz)) {
            encoder = createMapEncoder(type);
        } else if (Optional.class == clazz) {
            encoder = new OptionalCoder(this, type);
        } else if (clazz == Object.class) {
            return (Encodeable<W, E>) this.anyEncoder;
        } else if (!clazz.getName().startsWith("java.") || java.net.HttpCookie.class == clazz
            || java.util.Map.Entry.class == clazz || java.util.AbstractMap.SimpleEntry.class == clazz) {
            Encodeable simpleCoder = null;
            for (final Method method : clazz.getDeclaredMethods()) {
                if (!Modifier.isStatic(method.getModifiers())) continue;
                Class[] paramTypes = method.getParameterTypes();
                if (paramTypes.length != 1) continue;
                if (paramTypes[0] != ConvertFactory.class && paramTypes[0] != this.getClass()) continue;
                if (!Encodeable.class.isAssignableFrom(method.getReturnType())) continue;
                try {
                    method.setAccessible(true);
                    simpleCoder = (Encodeable) method.invoke(null, this);
                    break;
                } catch (Exception e) {
                }
            }
            if (simpleCoder == null) {
                oe = createObjectEncoder(type);
                encoder = oe;
            } else {
                encoder = simpleCoder;
            }
        }
        if (encoder == null) throw new ConvertException("not support the type (" + type + ")");
        register(type, encoder);
        if (oe != null) oe.init(this);
        return encoder;

    }

}


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

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Newtonsoft.Json.Linq;
using Potato.Core.Shared;
using Potato.Core.Shared.Models;
using Potato.Core.Shared.Serialization;
using Potato.Core.Variables;
using Potato.Net.Shared.Utils;

#endregion

namespace Potato.Core.Test.Variables {
    [TestFixture]
    public class TestVariableController {
        [SetUp]
        public void Initialize() {
            SharedReferences.Setup();

            if (File.Exists(ConfigFileInfo.FullName)) {
                File.Delete(ConfigFileInfo.FullName);
            }
        }

        protected static FileInfo ConfigFileInfo = new FileInfo("Potato.Core.Test.Variables.xml");

        /// <summary>
        ///     Tests that an empty namespace will result in the common VariableModel name being returned.
        /// </summary>
        [Test]
        public void TestBuildNamespaceVariableKeyEmptyNamespace() {
            Assert.AreEqual("CommandServerEnabled", VariableModel.NamespaceVariableName("", CommonVariableNames.CommandServerEnabled));
        }

        /// <summary>
        ///     Tests that a key is generated correctly with a dot seperator when a
        ///     namespace is passed in.
        /// </summary>
        [Test]
        public void TestBuildNamespaceVariableKeyWithNamespace() {
            Assert.AreEqual("my.namespace.CommandServerEnabled", VariableModel.NamespaceVariableName("my.namespace", CommonVariableNames.CommandServerEnabled));
        }

        /// <summary>
        ///     Tests that when disposing of the variables object, all other items are cleaned up.
        /// </summary>
        [Test]
        public void TestDispose() {
            var variables = new VariableController();

            variables.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.VariablesSet,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "VolatileKey",
                    "value"
                })
            });

            variables.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.VariablesSetA,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "ArchiveKey",
                    "value"
                })
            });

            VariableModel volatileVariable = variables.VolatileVariables.Values.First();

            variables.Dispose();

            // Test that all the lists and data within each item has been nulled.
            Assert.IsNull(variables.VolatileVariables);

            Assert.IsNull(volatileVariable.Name);
            Assert.IsNull(volatileVariable.Value);
        }

        /// <summary>
        ///     Tests that a VariableModel will be created and added if it does not exist
        ///     to begin with.
        /// </summary>
        [Test]
        public void TestDynamicCreationCommonVariableKey() {
            var variables = new VariableController();

            // Validate the VariableModel does not exist first.
            Assert.IsNull(variables.VolatileVariables.Values.FirstOrDefault(v => v.Name == CommonVariableNames.TextCommandPrivatePrefix.ToString()));

            // Fetch the VariableModel. This should create and add the VariableModel.
            variables.Variable(CommonVariableNames.TextCommandPrivatePrefix);

            // Now validate that the VariableModel has been added.
            Assert.IsNotNull(variables.VolatileVariables.Values.First(v => v.Name == CommonVariableNames.TextCommandPrivatePrefix.ToString()));
        }

        /// <summary>
        ///     Tests that a VariableModel will be created and added if it does not exist
        ///     to begin with.
        /// </summary>
        [Test]
        public void TestDynamicCreationStringKey() {
            String key = "TestDynamicCreation" + StringExtensions.RandomString(20);

            var variables = new VariableController();

            // Validate the VariableModel does not exist first.
            Assert.IsNull(variables.VolatileVariables.Values.FirstOrDefault(v => v.Name == key));

            // Fetch the VariableModel. This should create and add the VariableModel.
            variables.Variable(key);

            // Now validate that the VariableModel has been added.
            Assert.IsNotNull(variables.VolatileVariables.Values.First(v => v.Name == key));
        }

        /// <summary>
        ///     Tests that a config can be successfully loaded
        /// </summary>
        [Test]
        public void TestLoadConfig() {
            var saveVariables = (VariableController)new VariableController().Execute();
            saveVariables.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.VariablesSetA,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "KeyToWriteString",
                    "this is a string"
                })
            });

            saveVariables.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.VariablesSetA,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "KeyToWriteInteger",
                    1
                })
            });

            saveVariables.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.VariablesSet,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "KeyToNotWrite",
                    "This shouldn't appear in the saved file."
                })
            });

            saveVariables.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.VariablesSetA,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    CommonVariableNames.MaximumProtocolConnections,
                    10
                })
            });

            // Save a config of the variables controller
            var saveConfig = new Config();
            saveConfig.Create(typeof (VariableController));
            saveVariables.WriteConfig(saveConfig);
            saveConfig.Save(ConfigFileInfo);

            // Load the config in a new config.
            var loadVariables = (VariableController)new VariableController().Execute();
            var loadConfig = new Config();
            loadConfig.Load(ConfigFileInfo);
            loadVariables.Execute(loadConfig);

            Assert.AreEqual("this is a string", loadVariables.ArchiveVariables.Values.First(v => v.Name == "KeyToWriteString").ToType<String>());
            Assert.AreEqual(1, loadVariables.ArchiveVariables.Values.First(v => v.Name == "KeyToWriteInteger").ToType<int>());
            Assert.AreEqual(10, loadVariables.ArchiveVariables.Values.First(v => v.Name == "MaximumProtocolConnections").ToType<int>());
        }

        /// <summary>
        ///     Tests that a config can be written in a specific format.
        /// </summary>
        [Test]
        public void TestWriteConfig() {
            var variables = (VariableController)new VariableController().Execute();
            variables.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.VariablesSetA,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "NameToWriteString",
                    "this is a string"
                })
            });

            variables.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.VariablesSetA,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "NameToWriteInteger",
                    1
                })
            });

            // Empty strings should not be written. No point saving nothing.
            variables.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.VariablesSetA,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "NameToignore",
                    ""
                })
            });

            variables.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.VariablesSet,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    "NameToNotWrite",
                    "This shouldn't appear in the saved file."
                })
            });

            variables.Tunnel(new Command() {
                Origin = CommandOrigin.Local,
                CommandType = CommandType.VariablesSetA,
                Parameters = TestHelpers.ObjectListToContentList(new List<Object>() {
                    CommonVariableNames.MaximumProtocolConnections,
                    10
                })
            });

            // Save a config of the variables controller
            var saveConfig = new Config();
            saveConfig.Create(typeof (VariableController));
            variables.WriteConfig(saveConfig);
            saveConfig.Save(ConfigFileInfo);

            // Load the config in a new config.
            var loadConfig = new Config();
            loadConfig.Load(ConfigFileInfo);

            var commands = loadConfig.RootOf<VariableController>().Children<JObject>().Select(item => item.ToObject<IConfigCommand>(JsonSerialization.Minimal)).ToList();

            // Order is not maintained so we can only check that the values in some disorder are output.
            // Nope, not perfect.
            foreach (var command in commands) {
                Assert.AreEqual("VariablesSetA", command.Command.Name);
                Assert.IsTrue(new List<String>() { "NameToWriteString", "NameToWriteInteger", "MaximumProtocolConnections" }.Contains(command.Command.Parameters[0].First<String>()));
                Assert.IsTrue(new List<String>() { "this is a string", "1", "10" }.Contains(command.Command.Parameters[1].First<String>()));
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
=pod

=head1 NAME

UI,
UI_new, UI_new_method, UI_free, UI_add_input_string, UI_dup_input_string,
UI_add_verify_string, UI_dup_verify_string, UI_add_input_boolean,
UI_dup_input_boolean, UI_add_info_string, UI_dup_info_string,
UI_add_error_string, UI_dup_error_string, UI_construct_prompt,
UI_add_user_data, UI_dup_user_data, UI_get0_user_data, UI_get0_result,
UI_get_result_length,
UI_process, UI_ctrl, UI_set_default_method, UI_get_default_method,
UI_get_method, UI_set_method, UI_OpenSSL, UI_null - user interface

=head1 SYNOPSIS

 #include <openssl/ui.h>

 typedef struct ui_st UI;

 UI *UI_new(void);
 UI *UI_new_method(const UI_METHOD *method);
 void UI_free(UI *ui);

 int UI_add_input_string(UI *ui, const char *prompt, int flags,
                         char *result_buf, int minsize, int maxsize);
 int UI_dup_input_string(UI *ui, const char *prompt, int flags,
                         char *result_buf, int minsize, int maxsize);
 int UI_add_verify_string(UI *ui, const char *prompt, int flags,
                          char *result_buf, int minsize, int maxsize,
                          const char *test_buf);
 int UI_dup_verify_string(UI *ui, const char *prompt, int flags,
                          char *result_buf, int minsize, int maxsize,
                          const char *test_buf);
 int UI_add_input_boolean(UI *ui, const char *prompt, const char *action_desc,
                          const char *ok_chars, const char *cancel_chars,
                          int flags, char *result_buf);
 int UI_dup_input_boolean(UI *ui, const char *prompt, const char *action_desc,
                          const char *ok_chars, const char *cancel_chars,
                          int flags, char *result_buf);
 int UI_add_info_string(UI *ui, const char *text);
 int UI_dup_info_string(UI *ui, const char *text);
 int UI_add_error_string(UI *ui, const char *text);
 int UI_dup_error_string(UI *ui, const char *text);

 char *UI_construct_prompt(UI *ui_method,
        const char *object_desc, const char *object_name);

 void *UI_add_user_data(UI *ui, void *user_data);
 int UI_dup_user_data(UI *ui, void *user_data);
 void *UI_get0_user_data(UI *ui);

 const char *UI_get0_result(UI *ui, int i);
 int UI_get_result_length(UI *ui, int i);

 int UI_process(UI *ui);

 int UI_ctrl(UI *ui, int cmd, long i, void *p, void (*f)());

 void UI_set_default_method(const UI_METHOD *meth);
 const UI_METHOD *UI_get_default_method(void);
 const UI_METHOD *UI_get_method(UI *ui);
 const UI_METHOD *UI_set_method(UI *ui, const UI_METHOD *meth);

 UI_METHOD *UI_OpenSSL(void);
 const UI_METHOD *UI_null(void);

=head1 DESCRIPTION

UI stands for User Interface, and is general purpose set of routines to
prompt the user for text-based information.  Through user-written methods
(see L<UI_create_method(3)>), prompting can be done in any way
imaginable, be it plain text prompting, through dialog boxes or from a
cell phone.

All the functions work through a context of the type UI.  This context
contains all the information needed to prompt correctly as well as a
reference to a UI_METHOD, which is an ordered vector of functions that
carry out the actual prompting.

The first thing to do is to create a UI with UI_new() or UI_new_method(),
then add information to it with the UI_add or UI_dup functions.  Also,
user-defined random data can be passed down to the underlying method
through calls to UI_add_user_data() or UI_dup_user_data().  The default
UI method doesn't care about these data, but other methods might.  Finally,
use UI_process() to actually perform the prompting and UI_get0_result()
and UI_get_result_length() to find the result to the prompt and its length.

A UI can contain more than one prompt, which are performed in the given
sequence.  Each prompt gets an index number which is returned by the
UI_add and UI_dup functions, and has to be used to get the corresponding
result with UI_get0_result() and UI_get_result_length().

UI_process() can be called more than once on the same UI, thereby allowing
a UI to have a long lifetime, but can just as well have a short lifetime.

The functions are as follows:

UI_new() creates a new UI using the default UI method.  When done with
this UI, it should be freed using UI_free().

UI_new_method() creates a new UI using the given UI method.  When done with
this UI, it should be freed using UI_free().

UI_OpenSSL() returns the built-in UI method (note: not necessarily the
default one, since the default can be changed.  See further on).  This
method is the most machine/OS dependent part of OpenSSL and normally
generates the most problems when porting.

UI_null() returns a UI method that does nothing.  Its use is to avoid
getting internal defaults for passed UI_METHOD pointers.

UI_free() removes a UI from memory, along with all other pieces of memory
that's connected to it, like duplicated input strings, results and others.
If B<ui> is NULL nothing is done.

UI_add_input_string() and UI_add_verify_string() add a prompt to the UI,
as well as flags and a result buffer and the desired minimum and maximum
sizes of the result, not counting the final NUL character.  The given
information is used to prompt for information, for example a password,
and to verify a password (i.e. having the user enter it twice and check
that the same string was entered twice).  UI_add_verify_string() takes
and extra argument that should be a pointer to the result buffer of the
input string that it's supposed to verify, or verification will fail.

UI_add_input_boolean() adds a prompt to the UI that's supposed to be answered
in a boolean way, with a single character for yes and a different character
for no.  A set of characters that can be used to cancel the prompt is given
as well.  The prompt itself is divided in two, one part being the
descriptive text (given through the I<prompt> argument) and one describing
the possible answers (given through the I<action_desc> argument).

UI_add_info_string() and UI_add_error_string() add strings that are shown at
the same time as the prompt for extra information or to show an error string.
The difference between the two is only conceptual.  With the builtin method,
there's no technical difference between them.  Other methods may make a
difference between them, however.

The flags currently supported are B<UI_INPUT_FLAG_ECHO>, which is relevant for
UI_add_input_string() and will have the users response be echoed (when
prompting for a password, this flag should obviously not be used, and
B<UI_INPUT_FLAG_DEFAULT_PWD>, which means that a default password of some
sort will be used (completely depending on the application and the UI
method).

UI_dup_input_string(), UI_dup_verify_string(), UI_dup_input_boolean(),
UI_dup_info_string() and UI_dup_error_string() are basically the same
as their UI_add counterparts, except that they make their own copies
of all strings.

UI_construct_prompt() is a helper function that can be used to create
a prompt from two pieces of information: an description and a name.
The default constructor (if there is none provided by the method used)
creates a string "Enter I<description> for I<name>:".  With the
description "pass phrase" and the file name "foo.key", that becomes
"Enter pass phrase for foo.key:".  Other methods may create whatever
string and may include encodings that will be processed by the other
method functions.

UI_add_user_data() adds a user data pointer for the method to use at any
time.  The builtin UI method doesn't care about this info.  Note that several
calls to this function doesn't add data, it replaces the previous blob
with the one given as argument.

UI_dup_user_data() duplicates the user data and works as an alternative
to UI_add_user_data() when the user data needs to be preserved for a longer
duration, perhaps even the lifetime of the application.  The UI object takes
ownership of this duplicate and will free it whenever it gets replaced or
the UI is destroyed.  UI_dup_user_data() returns 0 on success, or -1 on memory
allocation failure or if the method doesn't have a duplicator function.

UI_get0_user_data() retrieves the data that has last been given to the
UI with UI_add_user_data() or UI_dup_user_data.

UI_get0_result() returns a pointer to the result buffer associated with
the information indexed by I<i>.

UI_get_result_length() returns the length of the result buffer associated with
the information indexed by I<i>.

UI_process() goes through the information given so far, does all the printing
and prompting and returns the final status, which is -2 on out-of-band events
(Interrupt, Cancel, ...), -1 on error and 0 on success.

UI_ctrl() adds extra control for the application author.  For now, it
understands two commands: B<UI_CTRL_PRINT_ERRORS>, which makes UI_process()
print the OpenSSL error stack as part of processing the UI, and
B<UI_CTRL_IS_REDOABLE>, which returns a flag saying if the used UI can
be used again or not.

UI_set_default_method() changes the default UI method to the one given.
This function is not thread-safe and should not be called at the same time
as other OpenSSL functions.

UI_get_default_method() returns a pointer to the current default UI method.

UI_get_method() returns the UI method associated with a given UI.

UI_set_method() changes the UI method associated with a given UI.

=head1 NOTES

The resulting strings that the built in method UI_OpenSSL() generate
are assumed to be encoded according to the current locale or (for
Windows) code page.
For applications having different demands, these strings need to be
converted appropriately by the caller.
For Windows, if the OPENSSL_WIN32_UTF8 environment variable is set,
the built-in method UI_OpenSSL() will produce UTF-8 encoded strings
instead.

=head1 RETURN VALUES

UI_new() and UI_new_method() return a valid B<UI> structure or NULL if an error
occurred.

UI_add_input_string(), UI_dup_input_string(), UI_add_verify_string(),
UI_dup_verify_string(), UI_add_input_boolean(), UI_dup_input_boolean(),
UI_add_info_string(), UI_dup_info_string(), UI_add_error_string()
and UI_dup_error_string() return a positive number on success or a value which
is less than or equal to 0 otherwise.

UI_construct_prompt() returns a string or NULL if an error occurred.

UI_dup_user_data() returns 0 on success or -1 on error.

UI_get0_result() returns a string or NULL on error.

UI_get_result_length() returns a positive integer or 0 on success; otherwise it
returns -1 on error.

UI_process() returns 0 on success or a negative value on error.

UI_ctrl() returns a mask on success or -1 on error.

UI_get_default_method(), UI_get_method(), UI_OpenSSL(), UI_null() and
UI_set_method() return either a valid B<UI_METHOD> structure or NULL
respectively.

=head1 HISTORY

The UI_dup_user_data() function was added in OpenSSL 1.1.1.

=head1 COPYRIGHT

Copyright 2001-2018 The OpenSSL Project Authors. All Rights Reserved.

Licensed under the OpenSSL license (the "License").  You may not use
this file except in compliance with the License.  You can obtain a copy
in the file LICENSE in the source distribution or at
L<https://www.openssl.org/source/license.html>.

=cut


text:
InitScript
**********

Links
=====

`Gentoo Linux InitScripts`_

Example
=======

I have set-up a very simple init script for Continuum:

Created a new shell script ``/etc/init.d/continuum``:

::

  #!/sbin/runscript
  # Copyright 1999-2004 Gentoo Foundation
  # Distributed under the terms of the GNU General Public License v2

  start() {
          ebegin "Starting Continuum"
          start-stop-daemon --start --quiet \
                  --chuid integration \
                  --env JAVA_HOME="/etc/java-config-2/current-system-vm/" \
                  --exec /usr/local/bin/continuum-1.0.3/bin/linux/run.sh -- start
          sleep 5
          eend $?
  }

  stop()  {
          ebegin "Stopping Continuum"
          start-stop-daemon --start --quiet \
                  --chuid integration \
                  --exec /usr/local/bin/continuum-1.0.3/bin/linux/run.sh -- stop
          sleep 5
          eend $?
  }

The options on this script are fairly simple:

=======================  ===============================================================
``start-stop-daemon``    Is the special Gentoo script.  Have a look at the ``man`` page.
``--chuid integration``  Run the script as the ``integration`` user.
``--exec``               Execute this command.
``-- stop``              Any parameters after the ``--`` are passed to the application
=======================  ===============================================================

Change the permissions on the script:

::

  chmod 755 /etc/init.d/continuum

Then add Continuum to the Gentoo startup:

::

  rc-update add continuum default

The actual script can be viewed in Subversion:
https://weezy/svn/backup/linux-config/weezy/etc/init.d/continuum

.. _`Gentoo Linux InitScripts`: http://www.gentoo.org/doc/en/handbook/handbook-x86.xml?part=2&chap=4


text:
package org.apache.drill.common.expression;

import org.apache.drill.test.BaseTest;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class SchemaPathTest extends BaseTest {

  @Test
  public void testUnIndexedWithOutArray() {
    SchemaPath oneElementSchema = SchemaPath.parseFromString("`a`");
    assertEquals("Schema path should match", oneElementSchema, oneElementSchema.getUnIndexed());

    SchemaPath severalElementsSchema = SchemaPath.parseFromString("`a`.`b`.`c`");
    assertEquals("Schema path should match", severalElementsSchema, severalElementsSchema.getUnIndexed());
  }

  @Test
  public void testUnIndexedEndingWithArray() {
    SchemaPath schemaPath = SchemaPath.parseFromString("`a`.`b`[0]");
    assertEquals("Schema path should match", SchemaPath.parseFromString("`a`.`b`"), schemaPath.getUnIndexed());
  }

  @Test
  public void testUnIndexedArrayInTheMiddle() {
    SchemaPath schemaPath = SchemaPath.parseFromString("`a`.`b`[0].`c`.`d`");
    assertEquals("Schema path should match", SchemaPath.parseFromString("`a`.`b`.`c`.`d`"), schemaPath.getUnIndexed());
  }

  @Test
  public void testUnIndexedMultipleArrays() {
    SchemaPath schemaPath = SchemaPath.parseFromString("`a`.`b`[0][1].`c`.`d`[2][0]");
    assertEquals("Schema path should match", SchemaPath.parseFromString("`a`.`b`.`c`.`d`"), schemaPath.getUnIndexed());
  }

  @Test
  public void testCompoundPathN() {
    SchemaPath schemaPath = SchemaPath.getCompoundPath(3, "a", "b", "c", "d", "e");
    assertEquals("Schema path should match", SchemaPath.getCompoundPath("a", "b", "c"), schemaPath);
  }
}


text:
<?php

namespace MjBiz\Bundle\GithubBundle\Tests;

use MjBiz\Bundle\GithubBundle\Entity\Repository;

require_once __DIR__ . '/TestHelper.php';

class RepositoryTest extends \PHPUnit_Framework_TestCase
	{

	public function testOne()
		{
		$repodata = repodata();
		$repo = new Repository($repodata);

		$this->assertSame('vim-cmake', $repo->getName());
		$this->assertSame(5374340, $repo->getId());
		$this->assertSame('https://github.com/jansenm/vim-cmake.git', $repo->getCheckoutURL());
		$this->assertSame('A cmake reference and autocompletion plugin for vim', $repo->getDescription());
		$this->assertSame('https://github.com/jansenm/vim-cmake', $repo->getHtmlUrl());
		$this->assertSame('master', $repo->getDefaultBranch());
		$this->assertSame(4, $repo->getStarred());
		}
	}


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace FlickrNet.Exceptions
{
    /// <summary>
    /// Error: 99: User not logged in / Insufficient permissions
    /// </summary>
    /// <remarks>
    /// The method requires user authentication but the user was not logged in,
    /// or the authenticated method call did not have the required permissions.
    /// </remarks>
    public class UserNotLoggedInInsufficientPermissionsException : FlickrApiException
    {
        internal UserNotLoggedInInsufficientPermissionsException(string message)
            : base(99, message)
        {
        }
    }
}


text:
<link rel="import" href="chrome://resources/polymer/v1_0/polymer/polymer.html">
<link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/neon-animatable.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
<link rel="import" href="chrome://md-settings/controls/settings_checkbox.html">
<link rel="import" href="chrome://md-settings/search_engines_page/search_engines_page.html">
<link rel="import" href="chrome://md-settings/settings_page/settings_animated_pages.html">
<link rel="import" href="chrome://md-settings/settings_page/settings_subheader.html">

<dom-module id="settings-search-page">
  <link rel="import" type="css"
      href="chrome://md-settings/settings_shared.css">
  <link rel="import" type="css" href="search_page.css">
  <template>
    <settings-animated-pages id="pages" current-route="{{currentRoute}}"
        section="search">
      <neon-animatable id="main">

          <select id="searchEnginesMenu"
                on-change="defaultEngineGuidChanged_">
            <template is="dom-repeat" items="[[searchEngines]]">
              <option value="[[item.guid]]">[[item.name]]</option>
            </template>
          </select>

          <paper-button class="link-button"
              i18n-content="searchManageButtonLabel"
              on-tap="onSearchEnginesTap_">
          </paper-button>

      </neon-animatable>
      <neon-animatable id="search-engines">
        <settings-subheader i18n-values="page-title:searchEnginesLabel">
        </settings-subheader>
        <settings-search-engines-page></settings-search-engines-page>
      </neon-animatable>
    </settings-animated-pages>
  </template>

</dom-module>


text:
#include <WinSock2.h>
#include <Ws2ipdef.h>
#include <Ws2tcpip.h>
#include <cassert>
#include <aws/core/net/SimpleUDP.h>
#include <aws/core/utils/logging/LogMacros.h>
namespace Aws
{
    namespace Net
    {
        static const char ALLOC_TAG[] = "SimpleUDP";
        static const char IPV4_LOOP_BACK_ADDRESS[] = "127.0.0.1";
        static const char IPV6_LOOP_BACK_ADDRESS[] = "::1";

        static inline bool IsValidIPAddress(const char* ip, int addressFamily/*AF_INET or AF_INET6*/)
        {
            char buffer[128];
            return inet_pton(addressFamily, ip, (void*)buffer) == 1 ?true :false;
        }

        static bool GetASockAddrFromHostName(const char* hostName, void* sockAddrBuffer, size_t& addrLength, int& addressFamily)
        {
            struct addrinfo hints, *res;

            memset(&hints, 0, sizeof(hints));

            hints.ai_family = PF_UNSPEC;
            hints.ai_socktype = SOCK_DGRAM;
            if (getaddrinfo(hostName, nullptr, &hints, &res))
            {
                return false;
            }

            memcpy(sockAddrBuffer, res->ai_addr, res->ai_addrlen);
            addrLength = res->ai_addrlen;
            addressFamily = res->ai_family;
            freeaddrinfo(res);
            return true;
        }

        static sockaddr_in BuildAddrInfoIPV4(const char* hostIP, short port)
        {
            sockaddr_in addrinfo {};
            addrinfo.sin_family = AF_INET;
            addrinfo.sin_port = htons(port);
            inet_pton(AF_INET, hostIP, &addrinfo.sin_addr);
            return addrinfo;
        }

        static sockaddr_in6 BuildAddrInfoIPV6(const char* hostIP, short port)
        {
            sockaddr_in6 addrinfo {};
            addrinfo.sin6_family = AF_INET6;
            addrinfo.sin6_port = htons(port);
            inet_pton(AF_INET6, hostIP, &addrinfo.sin6_addr);
            return addrinfo;
        }

        SimpleUDP::SimpleUDP(int addressFamily, size_t sendBufSize, size_t receiveBufSize, bool nonBlocking):
            m_addressFamily(addressFamily), m_connected(false), m_socket(-1), m_port(0)
        {
            CreateSocket(addressFamily, sendBufSize, receiveBufSize, nonBlocking);
        }

        SimpleUDP::SimpleUDP(bool IPV4, size_t sendBufSize, size_t receiveBufSize, bool nonBlocking) :
            m_addressFamily(IPV4 ? AF_INET : AF_INET6), m_connected(false), m_socket(-1), m_port(0)
        {
            CreateSocket(m_addressFamily, sendBufSize, receiveBufSize, nonBlocking);
        }

        SimpleUDP::SimpleUDP(const char* host, unsigned short port, size_t sendBufSize, size_t receiveBufSize, bool nonBlocking) :
            m_addressFamily(AF_INET), m_connected(false), m_socket(-1), m_port(port)
        {
            if (IsValidIPAddress(host, AF_INET))
            {
                m_addressFamily = AF_INET;
                m_hostIP = Aws::String(host);
            }
            else if (IsValidIPAddress(host, AF_INET6))
            {
                m_addressFamily = AF_INET6;
                m_hostIP = Aws::String(host);
            }
            else
            {
                char sockAddrBuffer[100];
                char hostBuffer[100];
                size_t addrLength = 0;
                if (GetASockAddrFromHostName(host, (void*)sockAddrBuffer, addrLength, m_addressFamily))
                {
                    if (m_addressFamily == AF_INET)
                    {
                        struct sockaddr_in* sockaddr = reinterpret_cast<struct sockaddr_in*>(sockAddrBuffer);
                        inet_ntop(m_addressFamily, &(sockaddr->sin_addr), hostBuffer, sizeof(hostBuffer));
                    }
                    else
                    {
                        struct sockaddr_in6* sockaddr = reinterpret_cast<struct sockaddr_in6*>(sockAddrBuffer);
                        inet_ntop(m_addressFamily, &(sockaddr->sin6_addr), hostBuffer, sizeof(hostBuffer));
                    }
                    m_hostIP = Aws::String(hostBuffer);
                }
                else
                {
                    AWS_LOGSTREAM_ERROR(ALLOC_TAG, "Can't retrieve a valid ip address based on provided host: " << host);
                }
            }
            CreateSocket(m_addressFamily, sendBufSize, receiveBufSize, nonBlocking);
        }

        SimpleUDP::~SimpleUDP()
        {
            closesocket(GetUnderlyingSocket());
        }

        void SimpleUDP::CreateSocket(int addressFamily, size_t sendBufSize, size_t receiveBufSize, bool nonBlocking)
        {
            SOCKET sock = socket(addressFamily, SOCK_DGRAM, IPPROTO_UDP);
            assert(sock != INVALID_SOCKET);

            // Try to set sock to nonblocking mode.
            if (nonBlocking)
            {
                u_long enable = 1;
                ioctlsocket(sock, FIONBIO, &enable);
            }

            // if sendBufSize is not zero, try to set send buffer size
            if (sendBufSize)
            {
                int ret = setsockopt(sock, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<const char*>(&sendBufSize), sizeof(sendBufSize));
                if (ret)
                {
                    AWS_LOGSTREAM_WARN(ALLOC_TAG, "Failed to set UDP send buffer size to " << sendBufSize << " for socket " << sock << " error code: " << WSAGetLastError());
                }
                assert(ret == 0);
            }

            // if receiveBufSize is not zero, try to set receive buffer size
            if (receiveBufSize)
            {
                int ret = setsockopt(sock, SOL_SOCKET, SO_RCVBUF, reinterpret_cast<const char*>(&receiveBufSize), sizeof(receiveBufSize));
                if (ret)
                {
                    AWS_LOGSTREAM_WARN(ALLOC_TAG, "Failed to set UDP receive buffer size to " << receiveBufSize << " for socket " << sock << " error code: " << WSAGetLastError());
                }
                assert(ret == 0);
            }

            SetUnderlyingSocket(static_cast<int>(sock));
        }

        int SimpleUDP::Connect(const sockaddr* address, size_t addressLength)
        {
            int ret = connect(GetUnderlyingSocket(), address, static_cast<socklen_t>(addressLength));
            m_connected = ret ? false : true;
            return ret;
        }

        int SimpleUDP::ConnectToHost(const char* hostIP, unsigned short port) const
        {
            int ret;
            if (m_addressFamily == AF_INET6)
            {
                sockaddr_in6 addrinfo = BuildAddrInfoIPV6(hostIP, port);
                ret = connect(GetUnderlyingSocket(), reinterpret_cast<sockaddr*>(&addrinfo), sizeof(sockaddr_in6));
            }
            else
            {
                sockaddr_in addrinfo = BuildAddrInfoIPV4(hostIP, port);
                ret = connect(GetUnderlyingSocket(), reinterpret_cast<sockaddr*>(&addrinfo), sizeof(sockaddr_in));
            }
            m_connected = ret ? false : true;
            return ret;
        }

        int SimpleUDP::ConnectToLocalHost(unsigned short port) const
        {
            if (m_addressFamily == AF_INET6)
            {
                return ConnectToHost(IPV6_LOOP_BACK_ADDRESS, port);
            }
            else
            {
                return ConnectToHost(IPV4_LOOP_BACK_ADDRESS, port);
            }
        }

        int SimpleUDP::Bind(const sockaddr* address, size_t addressLength) const
        {
            return bind(GetUnderlyingSocket(), address, static_cast<socklen_t>(addressLength));
        }

        int SimpleUDP::BindToLocalHost(unsigned short port) const
        {
            if (m_addressFamily == AF_INET6)
            {
                sockaddr_in6 addrinfo = BuildAddrInfoIPV6(IPV6_LOOP_BACK_ADDRESS, port);
                return bind(GetUnderlyingSocket(), reinterpret_cast<sockaddr*>(&addrinfo), sizeof(sockaddr_in6));
            }
            else
            {
                sockaddr_in addrinfo = BuildAddrInfoIPV4(IPV4_LOOP_BACK_ADDRESS, port);
                return bind(GetUnderlyingSocket(), reinterpret_cast<sockaddr*>(&addrinfo), sizeof(sockaddr_in));
            }
        }

        int SimpleUDP::SendData(const uint8_t* data, size_t dataLen) const
        {
            if (!m_connected)
            {
                ConnectToHost(m_hostIP.c_str(), m_port);
            }
            return send(GetUnderlyingSocket(), reinterpret_cast<const char*>(data), static_cast<int>(dataLen), 0);
        }

        int SimpleUDP::SendDataTo(const sockaddr* address, size_t addressLength, const uint8_t* data, size_t dataLen) const
        {
            if (m_connected)
            {
                return send(GetUnderlyingSocket(), reinterpret_cast<const char*>(data), static_cast<int>(dataLen), 0);
            }
            else
            {
                return sendto(GetUnderlyingSocket(), reinterpret_cast<const char*>(data), static_cast<int>(dataLen), 0, address, static_cast<socklen_t>(addressLength));
            }
        }

        int SimpleUDP::SendDataToLocalHost(const uint8_t* data, size_t dataLen, unsigned short port) const
        {
            if (m_connected)
            {
                return send(GetUnderlyingSocket(), reinterpret_cast<const char*>(data), static_cast<int>(dataLen), 0);
            }
            else if (m_addressFamily == AF_INET6)
            {
                sockaddr_in6 addrinfo = BuildAddrInfoIPV6(IPV6_LOOP_BACK_ADDRESS, port);
                return sendto(GetUnderlyingSocket(), reinterpret_cast<const char*>(data), static_cast<int>(dataLen), 0, reinterpret_cast<sockaddr*>(&addrinfo), sizeof(sockaddr_in6));
            }
            else
            {
                sockaddr_in addrinfo = BuildAddrInfoIPV4(IPV4_LOOP_BACK_ADDRESS, port);
                return sendto(GetUnderlyingSocket(), reinterpret_cast<const char*>(data), static_cast<int>(dataLen), 0, reinterpret_cast<sockaddr*>(&addrinfo), sizeof(sockaddr_in));
            }
        }

        int SimpleUDP::ReceiveData(uint8_t* buffer, size_t bufferLen) const
        {
            return recv(GetUnderlyingSocket(), reinterpret_cast<char*>(buffer), static_cast<int>(bufferLen), 0);
        }

        int SimpleUDP::ReceiveDataFrom(sockaddr* address, size_t* addressLength, uint8_t* buffer, size_t bufferLen) const
        {
            return recvfrom(GetUnderlyingSocket(), reinterpret_cast<char*>(buffer), static_cast<int>(bufferLen), 0, address, reinterpret_cast<socklen_t*>(addressLength));
        }
    }
}


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

#include "globals.h"
#include "hamming.h"
#include "algorithms.h"
#include <helper.h>

#include <omp.h>
#include <math.h>
#include <iostream>
#include <string.h>
using namespace std;
using namespace Hamming;

typedef uintll_t (*computeHamming_ft)(const uintll_t &);

template<typename T,
         uintll_t BITCNT_DATA,
         computeHamming_ft func,
         bool WITH_1BIT,
         uintll_t BITCNT_HAMMING = (BITCNT_DATA == 8 ? 5 : ((BITCNT_DATA == 16) | (BITCNT_DATA == 24) ? 6 : 7)),
         uintll_t BITCNT_MSG = BITCNT_DATA + BITCNT_HAMMING,
         uintll_t CNT_COUNTS = BITCNT_MSG + 1ull,
         uintll_t CNT_MESSAGES = 0x1ull << BITCNT_DATA,
         uintll_t CNT_WORDS = 1ull<<BITCNT_MSG
>
void countHammingUndetectableErrors(uint128_t* result_counts)
{
  T counts[ CNT_COUNTS ] = {0};
#pragma omp parallel
  {
    T counts_local[ CNT_COUNTS ] = {0};
    T x,y;
    T distance;
/*
#pragma omp master
    {
      cout << "OpenMP using " << omp_get_num_threads() << " threads" << endl;
    }*/
#pragma omp for schedule(dynamic,1)
    for(T a=0; a<CNT_MESSAGES; ++a)
    {
      memset(counts_local, 0, CNT_COUNTS*sizeof(T));
      x = func(a);
      // valid codewords transitions
      for(T b=0; b<CNT_MESSAGES; ++b)
      {
        y = func(b);
        distance = computeDistance(x,y);
        ++counts_local[distance];
        if(WITH_1BIT)
        {
          for(T p=0;p<BITCNT_MSG;++p)
          {
            distance=computeDistance(x,y^(static_cast<T>(1)<<p));
            ++counts_local[distance];
          }
        }
      }
      // 4) Sum the counts
      for (uint_t i = 0; i < CNT_COUNTS; ++i) {
#pragma omp atomic
        counts[i] += counts_local[i];
      }
    }
  }

  for(uint_t i=0;i<CNT_COUNTS; ++i){
    result_counts[i] = static_cast<uint128_t>(counts[i]);
    //printf("%u %12llu\n", i, counts[i]);
  }
}

void run_hamming_cpu_native_short(uintll_t n, int with_1bit, int file_output)
{
  Statistics stats;
  TimeStatistics results_cpu (&stats,CPU_WALL_TIME);
  int i_totaltime = results_cpu.add("Total Runtime", "s");
  results_cpu.setFactorAll(0.001);

  const uintll_t h = ( n==8 ? 5 : (n<32?6:7) );
  uint128_t* counts = new uint128_t[n+h+1];
  memset(counts, 0, (n+h+1)*sizeof(uint128_t));

  printf("Start Hamming Coding Algorithm - Native Short Approach (CPU)\n");
  results_cpu.start(i_totaltime);

  if(with_1bit)
  {
    if(n==8)
      countHammingUndetectableErrors<uintll_t, 8, computeHamming08,true>(counts);
    else if(n==16)
      countHammingUndetectableErrors<uintll_t, 16, computeHamming16,true>(counts);
    else
      countHammingUndetectableErrors<uintll_t, 24, computeHamming24,true>(counts);
  }else{
    if(n==8)
      countHammingUndetectableErrors<uintll_t, 8, computeHamming08,false>(counts);
    else if(n==16)
      countHammingUndetectableErrors<uintll_t, 16, computeHamming16,false>(counts);
    else
      countHammingUndetectableErrors<uintll_t, 24, computeHamming24,false>(counts);
  }

//    countHammingUndetectableErrors<uint64_t, 32>();

  results_cpu.stop(i_totaltime);
  process_result_hamming(counts, stats, n, h, file_output?"hamming_cpu_native_short":nullptr);
  delete[] counts;
}


text:
module Hicube
  class PageMailer < Hicube::ApplicationMailer

    def notify(options = {})
      logger.debug "Sending contact-form email using option - #{options}"
      @name = options[:name]
      @phone = options[:phone]
      @message = options[:message]
      mail(reply_to: options[:reply_to], subject: options[:subject])
    end

  end
end


text:
<?php
/**
 * Search observer.
 *
 * @category Bubble
 * @package Bubble_Search
 * @author Johann Reinke <johann@bubblecode.net>
 */
class Bubble_Search_Model_Observer
{
    /**
     * Adds search weight parameter in attribute form.
     *
     * @param Varien_Event_Observer $observer
     */
    public function eavAttributeEditFormInit(Varien_Event_Observer $observer)
    {
        /** @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
        $attribute = $observer->getEvent()->getAttribute();
        $form = $observer->getEvent()->getForm();
        $fieldset = $form->getElement('front_fieldset');

        $fieldset->addField('search_weight', 'select', array(
            'name' => 'search_weight',
            'label' => Mage::helper('catalog')->__('Search Weight'),
            'values' => array(
                1 => 1,
                2 => 2,
                3 => 3,
                4 => 4,
                5 => 5
            ),
        ), 'is_searchable');

        if ($attribute->getAttributeCode() == 'name') {
            $form->getElement('is_searchable')->setDisabled(1);
        }
    }

    /**
     * Requires catalog search indexation.
     *
     * @param Varien_Event_Observer $observer
     */
    public function requireCatalogsearchReindex(Varien_Event_Observer $observer)
    {
        if (Mage::helper('bubble_search')->isActiveEngine()) {
            /** @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
            $attribute = $observer->getEvent()->getAttribute();
            if ($attribute->getData('search_weight') != $attribute->getOrigData('search_weight')) {
                Mage::getSingleton('index/indexer')->getProcessByCode('catalogsearch_fulltext')
                    ->changeStatus(Mage_Index_Model_Process::STATUS_REQUIRE_REINDEX);
            }
        }
    }

    /**
     * Deletes index if full catalog search reindexation is asked.
     *
     * @param Varien_Event_Observer $observer
     */
    public function beforeIndexProcessStart(Varien_Event_Observer $observer)
    {
        $storeId = $observer->getEvent()->getStoreId();
        $productIds = $observer->getEvent()->getProductIds();
        if (null === $storeId && null === $productIds) {
            $engine = Mage::helper('catalogsearch')->getEngine();
            if ($engine instanceof Bubble_Search_Model_Resource_Engine_Abstract) {
                $engine->cleanCache();
                $engine->deleteIndex();
            }
        }
    }
}


text:
package com.google.template.soy.data.internal;

import com.google.template.soy.data.SoyValueProvider;
import java.util.Map;
import javax.annotation.ParametersAreNonnullByDefault;

/**
 * Internal implementation of SoyDict in terms of a map. Do not use directly; instead, use {@link
 * SoyValueConverter#convert}.
 *
 *
Important: Do not use outside of Soy code (treat as superpackage-private).
 *
 */
@ParametersAreNonnullByDefault
public final class DictImpl extends AbstractDict {

  /**
   * Creates a SoyDict implementation for a particular underlying provider map.
   *
   *
The map may be mutable, but will not be mutated by the DictImpl.
   */
  public static DictImpl forProviderMap(Map<String, ? extends SoyValueProvider> providerMap) {
    return new DictImpl(providerMap);
  }

  private DictImpl(Map<String, ? extends SoyValueProvider> providerMap) {
    super(providerMap);
  }
}


text:
package com.google.leafcoin.core;

import com.google.leafcoin.script.Script;
import com.google.leafcoin.store.BlockStoreException;
import com.google.leafcoin.store.FullPrunedBlockStore;

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

import javax.annotation.Nullable;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.concurrent.*;

import static com.google.common.base.Preconditions.checkState;

/**
 *
A FullPrunedBlockChain works in conjunction with a {@link FullPrunedBlockStore} to verify all the rules of the
 * Bitcoin system, with the downside being a larg cost in system resources. Fully verifying means all unspent transaction
 * outputs are stored. Once a transaction output is spent and that spend is buried deep enough, the data related to it
 * is deleted to ensure disk space usage doesn't grow forever. For this reason a pruning node cannot serve the full
 * block chain to other clients, but it nevertheless provides the same security guarantees as a regular Satoshi
 * client does.

 */
public class FullPrunedBlockChain extends AbstractBlockChain {
    private static final Logger log = LoggerFactory.getLogger(FullPrunedBlockChain.class);

    /** Keeps a map of block hashes to StoredBlocks. */
    protected final FullPrunedBlockStore blockStore;

    // Whether or not to execute scriptPubKeys before accepting a transaction (i.e. check signatures).
    private boolean runScripts = true;

    /**
     * Constructs a BlockChain connected to the given wallet and store. To obtain a {@link Wallet} you can construct
     * one from scratch, or you can deserialize a saved wallet from disk using {@link Wallet#loadFromFile(java.io.File)}
     */
    public FullPrunedBlockChain(NetworkParameters params, Wallet wallet, FullPrunedBlockStore blockStore) throws BlockStoreException {
        this(params, new ArrayList<BlockChainListener>(), blockStore);
        if (wallet != null)
            addWallet(wallet);
    }

    /**
     * Constructs a BlockChain that has no wallet at all. This is helpful when you don't actually care about sending
     * and receiving coins but rather, just want to explore the network data structures.
     */
    public FullPrunedBlockChain(NetworkParameters params, FullPrunedBlockStore blockStore) throws BlockStoreException {
        this(params, new ArrayList<BlockChainListener>(), blockStore);
    }

    /**
     * Constructs a BlockChain connected to the given list of wallets and a store.
     */
    public FullPrunedBlockChain(NetworkParameters params, List<BlockChainListener> listeners,
                                FullPrunedBlockStore blockStore) throws BlockStoreException {
        super(params, listeners, blockStore);
        this.blockStore = blockStore;
        // Ignore upgrading for now
        this.chainHead = blockStore.getVerifiedChainHead();
    }

    @Override
    protected StoredBlock addToBlockStore(StoredBlock storedPrev, Block header, TransactionOutputChanges txOutChanges)
            throws BlockStoreException, VerificationException {
        StoredBlock newBlock = storedPrev.build(header);
        blockStore.put(newBlock, new StoredUndoableBlock(newBlock.getHeader().getHash(), txOutChanges));
        return newBlock;
    }

    @Override
    protected StoredBlock addToBlockStore(StoredBlock storedPrev, Block block)
            throws BlockStoreException, VerificationException {
        StoredBlock newBlock = storedPrev.build(block);
        blockStore.put(newBlock, new StoredUndoableBlock(newBlock.getHeader().getHash(), block.transactions));
        return newBlock;
    }

    @Override
    protected boolean shouldVerifyTransactions() {
        return true;
    }

    /**
     * Whether or not to run scripts whilst accepting blocks (i.e. checking signatures, for most transactions).
     * If you're accepting data from an untrusted node, such as one found via the P2P network, this should be set
     * to true (which is the default). If you're downloading a chain from a node you control, script execution
     * is redundant because you know the connected node won't relay bad data to you. In that case it's safe to set
     * this to false and obtain a significant speedup.
     */
    public void setRunScripts(boolean value) {
        this.runScripts = value;
    }

    //TODO: Remove lots of duplicated code in the two connectTransactions

    // TODO: execute in order of largest transaction (by input count) first
    ExecutorService scriptVerificationExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    /** A job submitted to the executor which verifies signatures. */
    private static class Verifier implements Callable<VerificationException> {
        final Transaction tx;
        final List


text:
from rpath_job import api1 as rpath_job
HistoryEntry = rpath_job.HistoryEntry
ResultResource = rpath_job.ResultResource

class InstanceLaunchJob(rpath_job.HistoryBaseJob):
    _fieldTypes = rpath_job.HistoryBaseJob._fieldTypes.copy()
    _fieldTypes['cloudType'] = rpath_job.FieldString
    _fieldTypes['cloudName'] = rpath_job.FieldString
    _fieldTypes['system'] = rpath_job.FieldInteger

class DeployImageJob(InstanceLaunchJob):
    pass

class VersionUpdateLaunchJob(rpath_job.HistoryBaseJob):
    _fieldTypes = rpath_job.HistoryBaseJob._fieldTypes.copy()
    _fieldTypes['instanceId'] = rpath_job.FieldString
    _fieldTypes['cloudType'] = rpath_job.FieldString
    _fieldTypes['cloudName'] = rpath_job.FieldString

class InstanceUpdateJob(rpath_job.HistoryBaseJob):
    _fieldTypes = rpath_job.HistoryBaseJob._fieldTypes.copy()
    _fieldTypes['instanceId'] = rpath_job.FieldString
    _fieldTypes['cloudType'] = rpath_job.FieldString
    _fieldTypes['cloudName'] = rpath_job.FieldString

class CatalogJobStore(rpath_job.JobStore):
    _storageSubdir = "catalog-jobs"

class LaunchJobStore(CatalogJobStore):
    jobType = "instance-launch"
    jobFactory = InstanceLaunchJob
    resultClass = ResultResource

class DeployImageJobStore(CatalogJobStore):
    jobType = "image-deployment"
    jobFactory = DeployImageJob
    resultClass = ResultResource

class ApplianceVersionUpdateJobStore(CatalogJobStore):
    jobType = "software-version-refresh"
    jobFactory = VersionUpdateLaunchJob
    resultClass = unicode

class ApplianceUpdateJobStore(CatalogJobStore):
    jobType = "instance-update"
    jobFactory = InstanceUpdateJob
    resultClass = unicode

class CatalogSqlJobStore(rpath_job.SqlJobStore):
    pass

class LaunchJobSqlStore(CatalogSqlJobStore):
    jobType = LaunchJobStore.jobType
    jobFactory = InstanceLaunchJob
    resultClass = ResultResource
    BackingStore = rpath_job.TargetSqlBacking

class DeployImageJobSqlStore(LaunchJobSqlStore):
    jobType = DeployImageJobStore.jobType
    jobFactory = LaunchJobSqlStore.jobFactory

class ApplianceVersionUpdateJobSqlStore(CatalogSqlJobStore):
    jobType = ApplianceVersionUpdateJobStore.jobType
    jobFactory = VersionUpdateLaunchJob
    resultClass = unicode
    BackingStore = rpath_job.ManagedSystemsSqlBacking

class ApplianceUpdateJobSqlStore(CatalogSqlJobStore):
    jobType = ApplianceUpdateJobStore.jobType
    jobFactory = InstanceUpdateJob
    resultClass = unicode
    BackingStore = rpath_job.ManagedSystemsSqlBacking


text:
namespace Content.Client.PowerCell;

[RegisterComponent]
public sealed class PowerCellVisualsComponent : Component {}


text:
<resources>
    <string name="app_name">Bummer TV</string>
    <string name="please_wait">Please wait</string>
    <string name="error">Error</string>
    <string name="jenkins_connection_failed">Cannot connect to Jenkins</string>
    <string name="jenkins_connection_passed">Jenkins connection passed</string>
    <string name="freshdesk_connection_failed">Cannot connect to freshdesk</string>
    <string name="freshdesk_connection_passed">Freshdesk connection passed</string>
    <string name="connecting">Connecting ...</string>
</resources>


text:
package com.siyeh.ipp.expression;

import com.intellij.psi.JavaTokenType;
import com.intellij.psi.PsiExpression;
import com.intellij.psi.PsiJavaToken;
import com.intellij.psi.PsiPolyadicExpression;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.ObjectUtils;
import com.siyeh.ig.psiutils.ParenthesesUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ExpandLogicalBracketsIntention extends ExpandBracketsBaseIntention {

  private static final IElementType[] ADDITIVE_OPS = {JavaTokenType.OROR};
  private static final IElementType[] MULTIPLICATIVE_OPS = {JavaTokenType.ANDAND};

  @NotNull
  @Override
  protected IElementType[] getConjunctionTokens() {
    return MULTIPLICATIVE_OPS;
  }

  @NotNull
  @Override
  protected IElementType[] getDisjunctionTokens() {
    return ADDITIVE_OPS;
  }

  @NotNull
  @Override
  protected IElementType[] getPrefixes() {
    return IElementType.EMPTY_ARRAY;
  }

  @Override
  protected boolean addReplacement(@Nullable PsiJavaToken token, @NotNull PsiExpression operand,
                                   @NotNull PsiExpression innerExpr, @NotNull StringBuilder sb) {
    if (token != null) sb.append(" || ");

    Stream<String> operands = getInnerOperands(innerExpr);
    if (operands == null) return false;

    final PsiPolyadicExpression polyadicExpression = ObjectUtils.tryCast(operand, PsiPolyadicExpression.class);

    if (polyadicExpression != null && polyadicExpression != innerExpr) {
      final String fmt = getConjunctionFormat(polyadicExpression, innerExpr);
      operands = operands.map(op -> String.format(fmt, op));
    }

    sb.append(operands.collect(Collectors.joining(" || ")));
    return true;
  }

  @Nullable
  private static Stream<String> getInnerOperands(@NotNull PsiExpression innerExpr) {
    innerExpr = ParenthesesUtils.stripParentheses(innerExpr);
    if (innerExpr == null) return null;

    final PsiPolyadicExpression polyadicExpression = ObjectUtils.tryCast(innerExpr, PsiPolyadicExpression.class);
    if (polyadicExpression == null) return null;

    if (polyadicExpression.getOperationTokenType().equals(JavaTokenType.ANDAND)) {
      return Stream.of(getOperandText(innerExpr, false));
    }

    return Arrays.stream(polyadicExpression.getOperands())
      .map(operand -> processPrefixed(operand, ExpandLogicalBracketsIntention::getOperandText, JavaTokenType.EXCL));
  }

  @NotNull
  private static String getOperandText(@NotNull PsiExpression operand, boolean isInverted) {
    return isInverted ? "! " + operand.getText() : operand.getText();
  }
}


text:
package com.google.cloud.genomics.dataflow.functions;

import com.google.genomics.v1.VariantCall;

public interface CallSimilarityCalculator {

  double similarity(VariantCall call1, VariantCall call2);

}


text:
=================================================
Welcome to django-admin-honeypot's documentation!
=================================================

`django-admin-honeypot`_ is a fake Django admin login screen to log and notify
admins of attempted unauthorized access. This app was inspired by discussion in
and around Paul McMillan's security talk at DjangoCon 2011.

:Author: `Derek Payton`_
:Version: 0.4.0
:License: `MIT`_

|travis-ci|_

.. |travis-ci| image:: https://secure.travis-ci.org/dmpayton/django-admin-honeypot.png
.. _travis-ci: http://travis-ci.org/dmpayton/django-admin-honeypot

**Source**
    `github.com/dmpayton/django-admin-honeypot <https://github.com/dmpayton/django-admin-honeypot>`_

**Documentation**
    `django-admin-honeypot.readthedocs.org <https://django-admin-honeypot.readthedocs.org/>`_

**Contents**

.. toctree::
   :maxdepth: 2

   manual/install
   manual/usage
   manual/reference
   manual/faq
   manual/testing

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

.. _django-admin-honeypot: https://github.com/dmpayton/django-admin-honeypot
.. _Derek Payton: http://dmpayton.com
.. _MIT: https://github.com/dmpayton/django-admin-honeypot/blob/master/LICENSE


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/compute/v1/compute.proto

namespace Google\Cloud\Compute\V1\LicenseCode;

use UnexpectedValueException;

/**
 * [Output Only] Current state of this License Code.
 *
 * Protobuf type google.cloud.compute.v1.LicenseCode.State
 */
class State
{
    /**
     * A value indicating that the enum field is not set.
     *
     * Generated from protobuf enum UNDEFINED_STATE = 0;
     */
    const UNDEFINED_STATE = 0;
    /**
     * Machines are not allowed to attach boot disks with this License Code. Requests to create new resources with this license will be rejected.
     *
     * Generated from protobuf enum DISABLED = 516696700;
     */
    const DISABLED = 516696700;
    /**
     * Use is allowed for anyone with USE_READ_ONLY access to this License Code.
     *
     * Generated from protobuf enum ENABLED = 182130465;
     */
    const ENABLED = 182130465;
    /**
     * Use of this license is limited to a project whitelist.
     *
     * Generated from protobuf enum RESTRICTED = 261551195;
     */
    const RESTRICTED = 261551195;
    /**
     * Generated from protobuf enum STATE_UNSPECIFIED = 470755401;
     */
    const STATE_UNSPECIFIED = 470755401;
    /**
     * Reserved state.
     *
     * Generated from protobuf enum TERMINATED = 250018339;
     */
    const TERMINATED = 250018339;

    private static $valueToName = [
        self::UNDEFINED_STATE => 'UNDEFINED_STATE',
        self::DISABLED => 'DISABLED',
        self::ENABLED => 'ENABLED',
        self::RESTRICTED => 'RESTRICTED',
        self::STATE_UNSPECIFIED => 'STATE_UNSPECIFIED',
        self::TERMINATED => 'TERMINATED',
    ];

    public static function name($value)
    {
        if (!isset(self::$valueToName[$value])) {
            throw new UnexpectedValueException(sprintf(
                    'Enum %s has no name defined for value %s', __CLASS__, $value));
        }
        return self::$valueToName[$value];
    }

    public static function value($name)
    {
        $const = __CLASS__ . '::' . strtoupper($name);
        if (!defined($const)) {
            throw new UnexpectedValueException(sprintf(
                    'Enum %s has no value defined for name %s', __CLASS__, $name));
        }
        return constant($const);
    }
}


text:
package eu.ydp.empiria.player.client.module.ordering.presenter;

import com.google.common.collect.Lists;
import eu.ydp.empiria.player.client.module.ordering.model.OrderingItem;
import org.fest.assertions.api.Assertions;
import org.junit.Test;

import java.util.List;

public class ItemsOrderByAnswersFinderJUnitTest {

    private ItemsOrderByAnswersFinder itemsOrderByAnswersFinder = new ItemsOrderByAnswersFinder();

    @Test
    public void shouldFindCorrectItemsOrderByUserAnswers() throws Exception {
        List<String> currentAnswers = Lists.newArrayList("answer1", "answer3", "answer2");
        List<OrderingItem> items = Lists.newArrayList(createItem("id2", "answer2"), createItem("id1", "answer1"), createItem("id3", "answer3"));
        List<String> itemsOrder = itemsOrderByAnswersFinder.findCorrectItemsOrderByAnswers(currentAnswers, items);

        List<String> expectedItemsOrder = Lists.newArrayList("id1", "id3", "id2");
        Assertions.assertThat(itemsOrder).isEqualTo(expectedItemsOrder);
    }

    @Test(expected = CannotMatchOrderingItemsToUserAnswersException.class)
    public void shouldThrowExceptionWhenCannotMatchOrderingItemsToUserAnswer() throws Exception {
        List<String> currentAnswers = Lists.newArrayList("not match any OrderingItem", "answer3", "answer2");
        List<OrderingItem> items = Lists.newArrayList(createItem("id2", "answer2"), createItem("id1", "answer1"), createItem("id3", "answer3"));

        itemsOrderByAnswersFinder.findCorrectItemsOrderByAnswers(currentAnswers, items);
    }

    private OrderingItem createItem(String id, String answerValue) {
        return new OrderingItem(id, answerValue);
    }

}


text:
{% extends 'layout.html' %}
{% import '_macros.html' as macros %}
{% block content %}
{{ macros.reports_table(reports, reports_count, report_event_counts, condensed=False, hash_truncate=False, show_conf_col=True, show_agent_col=True, show_host_col=True, show_search_bar=True, searchable=True, current_env=current_env)}}
{{ macros.render_pagination(pagination)}}

Limit

    {{config.REPORTS_COUNT}}
    25
    50
    100
    All

Filter By

    Failed
    Changed
    Unchanged
    Noop

{% endblock content %}


text:
require 'spec_helper'

RSpec.describe Gitlab::AppLogger do
  subject { described_class }

  it 'builds a Gitlab::Logger object twice' do
    expect(Gitlab::Logger).to receive(:new)
      .exactly(described_class.loggers.size)
      .and_call_original

    subject.info('Hello World!')
  end

  it 'logs info to AppLogger and AppJsonLogger' do
    expect_any_instance_of(Gitlab::AppTextLogger).to receive(:info).and_call_original
    expect_any_instance_of(Gitlab::AppJsonLogger).to receive(:info).and_call_original

    subject.info('Hello World!')
  end

  it 'logs info to only the AppJsonLogger when unstructured logs are disabled' do
    stub_env('UNSTRUCTURED_RAILS_LOG', 'false')
    expect_any_instance_of(Gitlab::AppTextLogger).not_to receive(:info).and_call_original
    expect_any_instance_of(Gitlab::AppJsonLogger).to receive(:info).and_call_original

    subject.info('Hello World!')
  end
end


text:
This project is a simple Docker image that runs [Vault](https://vaultproject.io/), saving you from having to install it.

#Prerequisites
* a working [Docker](http://docker.io) engine
* a working [Docker Compose](http://docker.io) installation

#Building
Type `docker-compose build` to build the image.

#Installation
Docker Compose will automatically install the newly built image into the cache.

#Tips and Tricks

##Launching The Image

`docker-compose up` will launch the image, proving it built correctly.  For everyday use, run `./valut.sh`.

#Troubleshooting

##User Account
The image assumes that the account running the continer will have a user and group id of 1000:1000.  This allows the container
to save files in your home directory and keep the proper permissions.

#License and Credits
This project is licensed under the [Apache License Version 2.0, January 2004](http://www.apache.org/licenses/).

#List of Changes