text:
package com.strobel.reflection;

import com.strobel.annotations.NotNull;
import com.strobel.collections.ImmutableList;
import com.strobel.core.Comparer;
import com.strobel.core.Fences;
import com.strobel.core.StringUtilities;
import com.strobel.core.VerifyArgument;
import com.strobel.util.ContractUtils;

import javax.lang.model.type.TypeKind;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

enum MemberListType {
    All,
    CaseSensitive,
    CaseInsensitive,
    HandleToInfo,
}

/**
 * @author strobelm
 */
final class RuntimeTypeCache<T> {
    private enum WhatsCached {
        Nothing,
        EnclosingType
    }

    private enum CacheType {
        Method,
        Constructor,
        Field,
        Property,
        Event,
        Interface,
        NestedType
    }

    private WhatsCached _whatsCached;
    private Class<T> _erasedClass;
    private final Type<T> _runtimeType;
    private Type<?> _enclosingType;
    private final TypeKind _typeKind;
    private String _name;
    private String _fullName;
    private String _internalName;
    private String _genericSignature;
    private Package _package;
    private MemberInfoCache<RuntimeMethodInfo> _methodCache;
    private MemberInfoCache<RuntimeConstructorInfo> _constructorCache;
    private MemberInfoCache<RuntimeFieldInfo> _fieldCache;
    private MemberInfoCache<Type<?>> _interfaceCache;
    private MemberInfoCache<Type<?>> _nestedTypeCache;

//    private static HashMap<RuntimeMethodInfo, RuntimeMethodInfo> _methodInstantiations;

    RuntimeTypeCache(final Type<T> runtimeType) {
        _typeKind = TypeKind.DECLARED;
        _runtimeType = runtimeType;
    }

    @SuppressWarnings("unchecked")
    Class<T> getErasedClass() {
        if (_erasedClass == null) {
            final String fullName = getFullName();

            try {
                _erasedClass = (Class<T>) Class.forName(fullName);
            }
            catch (final ClassNotFoundException e) {
                throw Error.couldNotResolveType(fullName);
            }
        }

        return _erasedClass;
    }

    Package getPackage() {
        if (_package == null) {
            final String fullName = _runtimeType.getClassFullName();
            final int lastDotPosition = fullName.lastIndexOf('.');
            if (lastDotPosition < 0) {
                _package = Package.getPackage(StringUtilities.EMPTY);
            }
            else {
                _package = Package.getPackage(fullName.substring(0, lastDotPosition));
            }
        }
        return _package;
    }

    TypeKind getTypeKind() {
        return _typeKind;
    }

    String getName() {
        if (_name == null) {
            _name = _runtimeType._appendClassName(new StringBuilder(), false, true).toString();
        }
        return _name;
    }

    String getFullName() {
        if (_fullName == null) {
            _fullName = _runtimeType._appendClassName(new StringBuilder(), true, true).toString();
        }
        return _fullName;
    }

    String getInternalName() {
        if (_internalName == null) {
            _internalName = _runtimeType._appendClassName(new StringBuilder(), true, false).toString();
        }
        return _internalName;
    }

    String getGenericSignature() {
        if (_genericSignature == null) {
            _genericSignature = _runtimeType.appendGenericSignature(new StringBuilder()).toString();
        }
        return _genericSignature;
    }

    Type<T> getRuntimeType() {
        return _runtimeType;
    }

    Type<?> getEnclosingType() {
        if (_whatsCached != WhatsCached.EnclosingType) {
            _enclosingType = getRuntimeType().getDeclaringType();
            _whatsCached = WhatsCached.EnclosingType;
        }
        return _enclosingType;
    }

    private final static class Filter {
        private final String _name;
        private final MemberListType _listType;

        private Filter(final String name, final MemberListType listType) {
            this._name = name;
            this._listType = VerifyArgument.notNull(listType, "listType");
        }

        private boolean match(final String name) {
            if (_listType == MemberListType.CaseSensitive) {
                return _name == null || _name.equals(name);
            }
            return _listType != MemberListType.CaseInsensitive ||
                   _name == null ||
                   _name.equalsIgnoreCase(name);
        }
    }

/*
    final MethodInfo getGenericMethodInfo(final RuntimeMethodInfo genericMethod) {
        if (_methodInstantiations == null) {
            synchronized (Type.CACHE_LOCK) {
                if (_methodInstantiations == null) {
                    _methodInstantiations = new HashMap<>();
                }
            }
        }

        final Type<T> reflectedType = getRuntimeType();

        final ParameterList oldParameters = genericMethod.getParameters();
        final ParameterList newParameters = GenericType.GenericBinder.visitParameters(
            oldParameters,
            reflectedType.getTypeBindings()
        );

        final Type<?> oldReturnType = genericMethod.getReturnType();
        final Type<?> newReturnType = GenericType.GenericBinder.visit(
            oldReturnType,
            reflectedType.getTypeBindings()
        );

        final TypeList oldThrownTypes = genericMethod.getThrownTypes();
        final TypeList newThrownTypes = GenericType.GenericBinder.visit(
            oldThrownTypes,
            reflectedType.getTypeBindings()
        );

        final RuntimeMethodInfo runtimeMethod = new RuntimeMethodInfo(
            genericMethod.getRawMethod(),
            genericMethod.getDeclaringType(),
            this,
            genericMethod.getModifiers(),
            genericMethod.getBindingFlags(),
            newParameters,
            newReturnType,
            newThrownTypes
        );

        final RuntimeMethodInfo currentRuntimeMethod;

        synchronized (Type.CACHE_LOCK) {
            currentRuntimeMethod = _methodInstantiations.get(genericMethod);

            if (currentRuntimeMethod != null) {
                return currentRuntimeMethod;
            }

            _methodInstantiations.put(runtimeMethod, runtimeMethod);
        }

        return runtimeMethod;
    }
*/

    ArrayList<RuntimeMethodInfo> getMethodList(final MemberListType listType, final String name) {
        if (_methodCache == null) {
            synchronized (Type.CACHE_LOCK) {
                if (_methodCache == null) {
                    _methodCache = new MemberInfoCache<>(this);
                }
            }
        }

        return _methodCache.getMemberList(listType, name, CacheType.Method);
    }

    ArrayList<RuntimeConstructorInfo> getConstructorList(final MemberListType listType, final String name) {
        if (_constructorCache == null) {
            synchronized (Type.CACHE_LOCK) {
                if (_constructorCache == null) {
                    _constructorCache = new MemberInfoCache<>(this);
                }
            }
        }

        return _constructorCache.getMemberList(listType, name, CacheType.Constructor);
    }

    ArrayList<RuntimeFieldInfo> getFieldList(final MemberListType listType, final String name) {
        if (_fieldCache == null) {
            synchronized (Type.CACHE_LOCK) {
                if (_fieldCache == null) {
                    _fieldCache = new MemberInfoCache<>(this);
                }
            }
        }

        return _fieldCache.getMemberList(listType, name, CacheType.Field);
    }

    ArrayList<Type<?>> getInterfaceList(final MemberListType listType, final String name) {
        if (_interfaceCache == null) {
            synchronized (Type.CACHE_LOCK) {
                if (_interfaceCache == null) {
                    _interfaceCache = new MemberInfoCache<>(this);
                }
            }
        }

        return _interfaceCache.getMemberList(listType, name, CacheType.Interface);
    }

    ArrayList<Type<?>> getNestedTypeList(final MemberListType listType, final String name) {
        if (_nestedTypeCache == null) {
            synchronized (Type.CACHE_LOCK) {
                if (_nestedTypeCache == null) {
                    _nestedTypeCache = new MemberInfoCache<>(this);
                }
            }
        }

        return _nestedTypeCache.getMemberList(listType, name, CacheType.NestedType);
    }

    MethodBase getMethod(final Type<? super T> declaringType, final MethodInfo method) {
        if (_methodCache == null) {
            synchronized (Type.CACHE_LOCK) {
                if (_methodCache == null) {
                    _methodCache = new MemberInfoCache<>(this);
                }
            }
        }

        return _methodCache.addMethod(declaringType, method, CacheType.Method);
    }

    MethodBase getConstructor(final Type<? super T> declaringType, final MethodInfo constructor) {
        if (_constructorCache == null) {
            synchronized (Type.CACHE_LOCK) {
                if (_constructorCache == null) {
                    _constructorCache = new MemberInfoCache<>(this);
                }
            }
        }

        return _constructorCache.addMethod(declaringType, constructor, CacheType.Constructor);
    }

    FieldInfo getField(final FieldInfo field) {
        if (_fieldCache == null) {
            synchronized (Type.CACHE_LOCK) {
                if (_fieldCache == null) {
                    _fieldCache = new MemberInfoCache<>(this);
                }
            }
        }
        return _fieldCache.addField(field);
    }

    @SuppressWarnings("unchecked")
    final static class MemberInfoCache<T extends MemberInfo> {
        private HashMap<String, ArrayList<T>> _caseSensitiveMembers;
        private HashMap<String, ArrayList<T>> _caseInsensitiveMembers;
        private ArrayList<T> _root;
        private boolean _cacheComplete;

        // This is the strong reference back to the cache
        private final RuntimeTypeCache<?> _typeCache;

        private MemberInfoCache(final RuntimeTypeCache<?> typeCache) {
            _typeCache = VerifyArgument.notNull(typeCache, "typeCache");
            _cacheComplete = false;
        }

        Type<?> getReflectedType() {
            return _typeCache.getRuntimeType();
        }

        private void mergeWithGlobalList(final ArrayList<T> list) {
            final int cachedCount = _root.size();

            for (int i = 0, n = list.size(); i < n; i++) {
                final T newMemberInfo = list.get(i);

                T cachedMemberInfo = null;

                for (int j = 0; j < cachedCount; j++) {
                    cachedMemberInfo = _root.get(j);

                    if (newMemberInfo.equals(cachedMemberInfo)) {
                        list.set(i, cachedMemberInfo);
                        break;
                    }
                }

                if (list.get(i) != cachedMemberInfo) {
                    _root.add(newMemberInfo);
                }
            }
        }

        final ArrayList<T> getMemberList(final MemberListType listType, final String name, final CacheType cacheType) {
            final ArrayList<T> list;

            switch (listType) {
                case CaseSensitive:
                    if (_caseSensitiveMembers == null) {
                        return populate(name, listType, cacheType);
                    }

                    list = _caseSensitiveMembers.get(name);

                    if (list == null) {
                        return populate(name, listType, cacheType);
                    }

                    return list;

                case All:
                    if (_cacheComplete) {
                        return _root;
                    }

                    return populate(null, listType, cacheType);

                default:
                    if (_caseInsensitiveMembers == null) {
                        return populate(name, listType, cacheType);
                    }

                    list = _caseInsensitiveMembers.get(name);

                    if (list == null) {
                        return populate(name, listType, cacheType);
                    }

                    return list;
            }
        }

        final ArrayList<T> insert(final ArrayList<T> list, final String name, final MemberListType listType) {
            boolean preallocationComplete = false;

            ArrayList<T> result = list;

            synchronized (this) {
                try {

                    if (listType == MemberListType.CaseSensitive) {
                        if (_caseSensitiveMembers == null) {
                            _caseSensitiveMembers = new HashMap<>(1);
                        }
                    }
                    else if (listType == MemberListType.CaseInsensitive) {
                        if (_caseInsensitiveMembers == null) {
                            _caseInsensitiveMembers = new HashMap<>(1);
                        }
                    }

                    if (_root == null) {
                        _root = new ArrayList<>(list.size());
                    }

                    preallocationComplete = true;
                }
                finally {
                    if (preallocationComplete) {
                        if (listType == MemberListType.CaseSensitive) {
                            // Ensure we always return a list that has been merged with the global list.
                            final ArrayList<T> cachedList = _caseSensitiveMembers.get(name);
                            if (cachedList == null) {
                                mergeWithGlobalList(list);
                                _caseSensitiveMembers.put(name, list);
                            }
                            else {
                                result = cachedList;
                            }
                        }
                        else if (listType == MemberListType.CaseInsensitive) {
                            // Ensure we always return a list that has been merged with the global list.
                            final ArrayList<T> cachedList = _caseInsensitiveMembers.get(name);
                            if (cachedList == null) {
                                mergeWithGlobalList(list);
                                _caseInsensitiveMembers.put(name, list);
                            }
                            else {
                                result = cachedList;
                            }
                        }
                        else {
                            mergeWithGlobalList(list);
                        }

                        if (listType == MemberListType.All) {
                            _cacheComplete = true;
                        }
                    }
                }
            }

            return result;
        }

        final MethodBase addMethod(final Type<?> declaringType, final MethodBase method, final CacheType cacheType) {
            final ArrayList<T> list;

            final int modifiers = VerifyArgument.notNull(method, "method").getModifiers();
            final boolean isPublic = Modifier.isPublic(modifiers);
            final boolean isStatic = Modifier.isStatic(modifiers);
            final boolean isInherited = !Comparer.equals(declaringType, getReflectedType());
            final Set<BindingFlags> bindingFlags = Type.filterPreCalculate(isPublic, isInherited, isStatic);

            switch (cacheType) {
                case Method:
                    final ArrayList<MethodInfo> methodList = new ArrayList<>(1);
                    final MethodInfo sourceMethod = (MethodInfo) method;

                    methodList.add(
                        new RuntimeMethodInfo(
                            sourceMethod,
                            sourceMethod.getRawMethod(),
                            declaringType,
                            _typeCache,
                            modifiers,
                            bindingFlags,
                            method.getParameters(),
                            sourceMethod.getReturnType(),
                            method.getThrownTypes(),
                            sourceMethod.getTypeBindings()
                        )
                    );

                    list = (ArrayList<T>) methodList;
                    break;

                case Constructor:
                    final ArrayList<RuntimeConstructorInfo> constructorList = new ArrayList<>(1);
                    constructorList.add(
                        new RuntimeConstructorInfo(
                            ((ConstructorInfo) method).getRawConstructor(),
                            _typeCache,
                            modifiers,
                            bindingFlags,
                            method.getParameters()
                        )
                    );
                    list = (ArrayList<T>) constructorList;
                    break;

                default:
                    throw ContractUtils.unreachable();
            }

            return (MethodBase) insert(list, null, MemberListType.HandleToInfo).get(0);
        }

        final FieldInfo addField(final FieldInfo field) {
            final ArrayList<T> list = new ArrayList<>(1);
            final int modifiers = VerifyArgument.notNull(field, "field").getModifiers();
            final boolean isPublic = Modifier.isPublic(modifiers);
            final boolean isStatic = Modifier.isStatic(modifiers);
            final Type declaringType = field.getDeclaringType();
            final boolean isInherited = !Comparer.equals(declaringType, getReflectedType());
            final Set<BindingFlags> bindingFlags = Type.filterPreCalculate(isPublic, isInherited, isStatic);

            list.add(
                (T) new RuntimeFieldInfo(
                    field.getRawField(),
                    declaringType,
                    _typeCache,
                    modifiers,
                    bindingFlags,
                    field.getFieldType()
                )
            );

            return (FieldInfo) insert(list, null, MemberListType.HandleToInfo).get(0);
        }

        private void populateRuntimeFields(
            final Filter filter,
            final FieldList declaredFields,
            final Type<?> declaringType,
            final ArrayList<RuntimeFieldInfo> list) {
            final Type<?> reflectedType = getReflectedType();

            assert declaringType != Type.NullType;
            assert reflectedType != Type.NullType;

            final boolean isInherited = !declaringType.equals(reflectedType);

            for (int i = 0, n = declaredFields.size(); i < n; i++) {
                final FieldInfo declaredField = declaredFields.get(i);

                if (!filter.match(declaredField.getName())) {
                    continue;
                }

                assert declaredField.getFieldType() != Type.NullType;

                final int fieldModifiers = declaredField.getModifiers();

                if (isInherited && Modifier.isPrivate(fieldModifiers)) {
                    continue;
                }

                final boolean isPublic = Modifier.isPublic(fieldModifiers);
                final boolean isStatic = Modifier.isStatic(fieldModifiers);
                final Set<BindingFlags> bindingFlags = Type.filterPreCalculate(isPublic, isInherited, isStatic);

                final RuntimeFieldInfo runtimeFieldInfo =
                    new RuntimeFieldInfo(
                        declaredField.getRawField(),
                        declaringType,
                        _typeCache,
                        fieldModifiers,
                        bindingFlags,
                        declaredField.getFieldType()
                    );

                list.add(runtimeFieldInfo);
            }
        }

        private ArrayList<RuntimeFieldInfo> populateFields(final Filter filter) {
            final ArrayList<RuntimeFieldInfo> list = new ArrayList<>();
            final Type<?> reflectedType = getReflectedType();

            Type<?> declaringType = reflectedType;

            while (declaringType.isGenericParameter()) {
                declaringType = declaringType.getExtendsBound();
            }

            while (declaringType != null && declaringType != Type.NullType) {
                populateRuntimeFields(filter, declaringType.getDeclaredFields(), declaringType, list);
                declaringType = declaringType.getBaseType();
            }

            final TypeList interfaces = reflectedType.isGenericParameter()
                                        ? reflectedType.getExtendsBound().getExplicitInterfaces()
                                        : reflectedType.getExplicitInterfaces();

            for (int i = 0, n = interfaces.size(); i < n; i++) {
                // Populate literal fields defined on any of the interfaces implemented by the declaring type
                final Type<?> interfaceType = interfaces.get(i);
                populateRuntimeFields(filter, interfaceType.getDeclaredFields(), interfaceType, list);
            }

            return list;
        }

        @SuppressWarnings("ConstantConditions")
        private ArrayList<RuntimeMethodInfo> populateMethods(final Filter filter) {
            final HashMap<String, ArrayList<RuntimeMethodInfo>> nameLookup = new HashMap<>();
            final ArrayList<RuntimeMethodInfo> list = new ArrayList<>();
            final Type<?> reflectedType = getReflectedType();

            Type<?> declaringType = reflectedType;

            while (declaringType.isGenericParameter()) {
                declaringType = declaringType.getExtendsBound();
            }

            final HashSet<String> included = new HashSet<>();
            final ArrayDeque<Type<?>> stack = new ArrayDeque<>();

            stack.add(declaringType);

            while (!stack.isEmpty()) {
                declaringType = stack.removeFirst();

                final boolean isInterface = declaringType.isInterface();

                for (final MethodInfo method : declaringType.getDeclaredMethods()) {
                    final String name = method.getName();

                    if ((method.getModifiers() & Flags.ACC_BRIDGE) == Flags.ACC_BRIDGE || !filter.match(name)) {
                        continue;
                    }

                    assert method.getReturnType() != Type.NullType;

                    final int methodModifiers = method.getModifiers();

                    if (isInterface) {
                        assert !Modifier.isFinal(methodModifiers);
                    }

                    final boolean isVirtual = !Modifier.isFinal(methodModifiers);
                    final boolean isPrivate = Modifier.isPrivate(methodModifiers);
                    final boolean isInherited = !declaringType.equals(reflectedType);

                    if (isInherited && isPrivate) {
                        continue;
                    }

                    ArrayList<RuntimeMethodInfo> nameCollisions = nameLookup.get(name);

                    if (overrideExists(method, nameCollisions)) {
                        continue;
                    }

                    if (!isVirtual) {
                        assert !Modifier.isAbstract(methodModifiers);
                    }

                    final boolean isPublic = Modifier.isPublic(methodModifiers);
                    final boolean isStatic = Modifier.isStatic(methodModifiers);

                    final Set<BindingFlags> bindingFlags = Type.filterPreCalculate(isPublic, isInherited, isStatic);

                    final RuntimeMethodInfo runtimeMethod = new RuntimeMethodInfo(
                        method,
                        method.getRawMethod(),
                        declaringType,
                        _typeCache,
                        methodModifiers,
                        bindingFlags,
                        method.getParameters(),
                        method.getReturnType(),
                        method.getThrownTypes(),
                        method.getTypeBindings()
                    );

                    if (nameCollisions == null) {
                        nameCollisions = new ArrayList<>(1);
                        nameLookup.put(name, nameCollisions);
                    }

                    nameCollisions.add(runtimeMethod);
                    list.add(runtimeMethod);
                }

                if (!isInterface) {
                    final Type<?> baseType = declaringType.getBaseType();

                    if (baseType != null &&
                        baseType != Type.NullType &&
                        included.add(baseType.getInternalName())) {

                        stack.addLast(baseType);
                    }
                }

                for (final Type<?> interfaceType : declaringType.getInterfaces()) {
                    if (included.add(interfaceType.getInternalName())) {
                        stack.addLast(interfaceType);
                    }
                }
            }

            return list;
        }

        private static boolean overrideExists(final MethodInfo method, final ArrayList<? extends MethodInfo> methods) {
            if (methods == null) {
                return false;
            }
            for (int i = 0, n = methods.size(); i < n; i++) {
                final MethodInfo otherMethod = methods.get(i);

                if (otherMethod.getDeclaringType() != method.getDeclaringType() &&
                    Helper.overrides(otherMethod, method)) {

                    return true;
                }
            }
            return false;
        }

        private ArrayList<RuntimeConstructorInfo> populateConstructors(final Filter filter) {
            final Type<?> reflectedType = getReflectedType();
            final ArrayList<RuntimeConstructorInfo> list = new ArrayList<>();

            if (reflectedType.isGenericParameter()) {
                return list;
            }

            for (final ConstructorInfo constructor : reflectedType.getDeclaredConstructors()) {
                final String name = constructor.getName();

                if (!filter.match(name)) {
                    continue;
                }

                final int modifiers = constructor.getModifiers();

                assert constructor.getDeclaringType() != Type.NullType;

                final boolean isPublic = Modifier.isPublic(modifiers);
                final boolean isStatic = false;
                final boolean isInherited = false;
                final Set<BindingFlags> bindingFlags = Type.filterPreCalculate(isPublic, isInherited, isStatic);

                final RuntimeConstructorInfo runtimeConstructorInfo = new RuntimeConstructorInfo(
                    constructor.getRawConstructor(),
                    _typeCache,
                    modifiers,
                    bindingFlags,
                    constructor.getParameters()
                );

                list.add(runtimeConstructorInfo);
            }

            return list;
        }

        private ArrayList<Type<?>> populateInterfaces(final Filter filter) {
            final ArrayList<Type<?>> list = new ArrayList<>();

            final Type<?> reflectedType = getReflectedType();

            final HashSet<Type<?>> set = new HashSet<>();
            final ImmutableList<Type<?>> interfaceList = Helper.interfaces(reflectedType);

            for (final Type interfaceType : interfaceList) {
                final String name = interfaceType.getFullName();

                if (filter.match(name) && set.add(interfaceType)) {
                    list.add(interfaceType);
                }
            }

            return list;
        }

        private ArrayList<Type<?>> populateNestedClasses(final Filter filter) {
            final ArrayList<Type<?>> list = new ArrayList<>();

            Type<?> declaringType = getReflectedType();

            if (declaringType.isGenericParameter()) {
                while (declaringType.isGenericParameter()) {
                    declaringType = declaringType.getExtendsBound();
                }
            }

            if (declaringType == Type.NullType) {
                return list;
            }

            final TypeList declaredTypes = declaringType.getDeclaredTypes();

            for (int i = 0, n = declaredTypes.size(); i < n; i++) {
                final Type<?> nestedType = declaredTypes.get(i);

                if (!filter.match(nestedType.getName())) {
                    continue;
                }

                list.add(nestedType);
            }

            return list;
        }

        private ArrayList<T> populate(final String name, final MemberListType listType, final CacheType cacheType) {
            final Filter filter;

            if (name == null || name.length() == 0 ||
                (cacheType == CacheType.Constructor && name.charAt(0) != '.' && name.charAt(0) != '*')) {
                filter = new Filter(null, listType);
            }
            else {
                filter = new Filter(name, listType);
            }

            final ArrayList<T> list;

            switch (cacheType) {
                case Method:
                    list = (ArrayList<T>) populateMethods(filter);
                    break;
                case Field:
                    list = (ArrayList<T>) populateFields(filter);
                    break;
                case Constructor:
                    list = (ArrayList<T>) populateConstructors(filter);
                    break;
                case NestedType:
                    list = (ArrayList<T>) populateNestedClasses(filter);
                    break;
                case Interface:
                    list = (ArrayList<T>) populateInterfaces(filter);
                    break;
                default:
                    throw ContractUtils.unreachable();
            }

            return insert(list, name, listType);
        }
    }
}

final class RuntimeConstructorInfo extends ConstructorInfo {

    private final Constructor<?> _rawConstructor;
    private final RuntimeTypeCache<?> _reflectedTypeCache;
    private final Set<BindingFlags> _bindingFlags;
    private final int _modifiers;
    private final ParameterList _parameters;
    private final SignatureType _signatureType;

    RuntimeConstructorInfo(
        final Constructor<?> rawConstructor,
        final RuntimeTypeCache<?> reflectedTypeCache,
        final int modifiers,
        final Set<BindingFlags> bindingFlags,
        final ParameterList parameters) {

        _rawConstructor = VerifyArgument.notNull(rawConstructor, "rawConstructor");
        _reflectedTypeCache = VerifyArgument.notNull(reflectedTypeCache, "reflectedTypeCache");
        _bindingFlags = VerifyArgument.notNull(bindingFlags, "bindingFlags");
        _modifiers = modifiers;
        _parameters = VerifyArgument.notNull(parameters, "parameters");
        _signatureType = new SignatureType(PrimitiveTypes.Void, _parameters.getParameterTypes());
    }

    Set<BindingFlags> getBindingFlags() {
        return _bindingFlags;
    }

    @Override
    public SignatureType getSignatureType() {
        return _signatureType;
    }

    @Override
    public ParameterList getParameters() {
        return _parameters;
    }

    @Override
    public Constructor<?> getRawConstructor() {
        return _rawConstructor;
    }

/*
    @Override
    public String getName() {
        return _rawConstructor.getName();
    }
*/

    @Override
    public Type getDeclaringType() {
        return _reflectedTypeCache.getRuntimeType();
    }

    @Override
    public Type getReflectedType() {
        return _reflectedTypeCache.getRuntimeType();
    }

    @Override
    public int getModifiers() {
        return _modifiers;
    }

    @Override
    public boolean isEquivalentTo(final MemberInfo m) {
        if (m == this) {
            return true;
        }
        if ((m instanceof RuntimeConstructorInfo)) {
            final RuntimeConstructorInfo other = (RuntimeConstructorInfo) m;

            if (other._reflectedTypeCache == _reflectedTypeCache &&
                other._rawConstructor == _rawConstructor) {

                return true;
            }
        }
        return super.isEquivalentTo(m);
    }
}

final class RuntimeMethodInfo extends MethodInfo {
    private final MethodInfo _baseMethod;
    private final Method _rawMethod;
    private final Type<?> _declaringType;
    private final RuntimeTypeCache<?> _reflectedTypeCache;
    private final int _modifiers;
    private final Set<BindingFlags> _bindingFlags;
    private final ParameterList _parameters;
    private final SignatureType _signatureType;
    private final TypeList _thrownTypes;
    private final TypeBindings _typeBindings;

    RuntimeMethodInfo(
        final MethodInfo baseMethod,
        final Method rawMethod,
        final Type<?> declaringType,
        final RuntimeTypeCache<?> reflectedTypeCache,
        final int modifiers,
        final Set<BindingFlags> bindingFlags,
        final ParameterList parameters,
        final Type<?> returnType,
        final TypeList thrownTypes,
        final TypeBindings typeBindings) {

        _baseMethod = baseMethod;
        _rawMethod = VerifyArgument.notNull(rawMethod, "rawMethod");
        _declaringType = VerifyArgument.notNull(declaringType, "declaringType");
        _reflectedTypeCache = VerifyArgument.notNull(reflectedTypeCache, "reflectedTypeCache");
        _bindingFlags = VerifyArgument.notNull(bindingFlags, "bindingFlags");
        _modifiers = modifiers;
        _parameters = VerifyArgument.notNull(parameters, "parameters");

        final Type<?> actualReturnType;

        if (TypeBinder.GET_CLASS_METHOD.equals(rawMethod) && !(declaringType instanceof ErasedType<?>)) {
            actualReturnType = Types.Class.makeGenericType(
                Type.makeExtendsWildcard(reflectedTypeCache.getRuntimeType()/*.getErasedType()*/)
            );
        }
        else {
            actualReturnType = VerifyArgument.notNull(returnType, "returnType");
        }

        _signatureType = new SignatureType(actualReturnType, _parameters.getParameterTypes());
        _thrownTypes = VerifyArgument.notNull(thrownTypes, "thrownTypes");
        _typeBindings = VerifyArgument.notNull(typeBindings, "typeBindings");
    }

    Set<BindingFlags> getBindingFlags() {
        return _bindingFlags;
    }

    @Override
    public ParameterList getParameters() {
        return _parameters;
    }

    @Override
    public Type<?> getReturnType() {
        return _signatureType.getReturnType();
    }

    @Override
    public SignatureType getSignatureType() {
        return _signatureType;
    }

    @Override
    public Method getRawMethod() {
        return _rawMethod;
    }

    @Override
    public String getName() {
        return _rawMethod.getName();
    }

    @Override
    public Type getDeclaringType() {
        return _declaringType;
    }

    @Override
    public Type getReflectedType() {
        return _reflectedTypeCache.getRuntimeType();
    }

    @Override
    public TypeList getThrownTypes() {
        return _thrownTypes;
    }

    @Override
    protected TypeBindings getTypeBindings() {
        return _typeBindings;
    }

    @Override
    public int getModifiers() {
        return _modifiers;
    }

    @Override
    public boolean isAnnotationPresent(final Class<? extends Annotation> annotationClass) {
        return _rawMethod.isAnnotationPresent(annotationClass);
    }

    @NotNull
    @Override
    public Annotation[] getDeclaredAnnotations() {
        return _rawMethod.getDeclaredAnnotations();
    }

    @NotNull
    @Override
    public Annotation[] getAnnotations() {
        return _rawMethod.getAnnotations();
    }

    @Override
    public <T extends Annotation> T getAnnotation(final Class<T> annotationClass) {
        return _rawMethod.getAnnotation(annotationClass);
    }

    @Override
    public boolean isEquivalentTo(final MemberInfo m) {
        if (m == this) {
            return true;
        }
        if (m instanceof RuntimeMethodInfo) {
            final RuntimeMethodInfo other = (RuntimeMethodInfo) m;

            if (other._declaringType == _declaringType &&
                other._rawMethod == _rawMethod) {

                return true;
            }
        }
        return super.isEquivalentTo(m);
    }

    @Override
    public MethodInfo getErasedMethodDefinition() {
        if (_erasedMethodDefinition != null) {
            return _erasedMethodDefinition;
        }

        if (Fences.orderReads(this)._erasedMethodDefinition != null) {
            return _erasedMethodDefinition;
        }

        if (_baseMethod != null) {
            _erasedMethodDefinition = Fences.orderWrites(
                reflectedOn(
                    _baseMethod.getErasedMethodDefinition(),
                    getReflectedType()
                )
            );

            Fences.orderAccesses(this);
        }

        return super.getErasedMethodDefinition();
    }

    @Override
    public StringBuilder appendErasedDescription(final StringBuilder sb) {
        if (_baseMethod != null) {
            return _baseMethod.appendErasedDescription(sb);
        }
        return super.appendErasedDescription(sb);
    }

    @Override
    public StringBuilder appendErasedSignature(final StringBuilder sb) {
        if (_baseMethod != null) {
            return _baseMethod.appendErasedSignature(sb);
        }
        return super.appendErasedSignature(sb);
    }
}

final class ErasedMethod extends MethodInfo {
    private final MethodInfo _baseMethod;
    private final Type<?> _declaringType;
    private final ParameterList _parameters;
    private final SignatureType _signatureType;
    private final TypeList _thrownTypes;
    private final TypeBindings _typeBindings;

    ErasedMethod(
        final MethodInfo baseMethod,
        final Type<?> declaringType,
        final ParameterList parameters,
        final Type<?> returnType,
        final TypeList thrownTypes,
        final TypeBindings typeBindings) {

        _baseMethod = VerifyArgument.notNull(baseMethod, "baseMethod");
        _declaringType = VerifyArgument.notNull(declaringType, "declaringType");
        _parameters = VerifyArgument.notNull(parameters, "parameters");
        _signatureType = new SignatureType(VerifyArgument.notNull(returnType, "returnType"), _parameters.getParameterTypes());
        _thrownTypes = VerifyArgument.notNull(thrownTypes, "thrownTypes");
        _typeBindings = VerifyArgument.notNull(typeBindings, "typeBindings");
    }

    @Override
    public ParameterList getParameters() {
        return _parameters;
    }

    @Override
    public Type<?> getReturnType() {
        return _signatureType.getReturnType();
    }

    @Override
    public SignatureType getSignatureType() {
        return _signatureType;
    }

    @Override
    public Method getRawMethod() {
        return _baseMethod.getRawMethod();
    }

    @Override
    public String getName() {
        return _baseMethod.getName();
    }

    @Override
    public Type getDeclaringType() {
        return _declaringType;
    }

    @Override
    public Type getReflectedType() {
        return _baseMethod.getReflectedType();
    }

    @Override
    public TypeList getThrownTypes() {
        return _thrownTypes;
    }

    @Override
    protected TypeBindings getTypeBindings() {
        return _typeBindings;
    }

    @Override
    public int getModifiers() {
        return _baseMethod.getModifiers();
    }

    @Override
    public boolean isAnnotationPresent(final Class<? extends Annotation> annotationClass) {
        return _baseMethod.isAnnotationPresent(annotationClass);
    }

    @NotNull
    @Override
    public Annotation[] getDeclaredAnnotations() {
        return _baseMethod.getDeclaredAnnotations();
    }

    @NotNull
    @Override
    public Annotation[] getAnnotations() {
        return _baseMethod.getAnnotations();
    }

    @Override
    public <T extends Annotation> T getAnnotation(final Class<T> annotationClass) {
        return _baseMethod.getAnnotation(annotationClass);
    }

    @Override
    public boolean isEquivalentTo(final MemberInfo m) {
        if (m == this) {
            return true;
        }
        if ((m instanceof ErasedMethod)) {
            final ErasedMethod other = (ErasedMethod) m;

            if (other._declaringType == _declaringType &&
                other._baseMethod == _baseMethod) {

                return true;
            }
        }
        return super.isEquivalentTo(m);
    }

    @Override
    public StringBuilder appendErasedDescription(final StringBuilder sb) {
        return _baseMethod.appendErasedDescription(sb);
    }

    @Override
    public StringBuilder appendErasedSignature(final StringBuilder sb) {
        return _baseMethod.appendErasedSignature(sb);
    }
}

final class RuntimeFieldInfo extends FieldInfo {
    private final Field _rawField;
    private final Type<?> _declaringType;
    private final RuntimeTypeCache<?> _reflectedTypeCache;
    private final int _modifiers;
    private final Set<BindingFlags> _bindingFlags;
    private final Type<?> _fieldType;

    RuntimeFieldInfo(
        final Field rawField,
        final Type<?> declaringType,
        final RuntimeTypeCache<?> reflectedTypeCache,
        final int modifiers,
        final Set<BindingFlags> bindingFlags,
        final Type<?> fieldType) {

        _rawField = VerifyArgument.notNull(rawField, "rawConstructor");
        _declaringType = VerifyArgument.notNull(declaringType, "declaringType");
        _reflectedTypeCache = VerifyArgument.notNull(reflectedTypeCache, "reflectedTypeCache");
        _bindingFlags = VerifyArgument.notNull(bindingFlags, "bindingFlags");
        _modifiers = modifiers;
        _fieldType = VerifyArgument.notNull(fieldType, "fieldType");
    }

    Set<BindingFlags> getBindingFlags() {
        return _bindingFlags;
    }

    @Override
    public Type<?> getFieldType() {
        return _fieldType;
    }

    @Override
    public boolean isEnumConstant() {
        return false;
    }

    @Override
    public Field getRawField() {
        return _rawField;
    }

    @Override
    public String getName() {
        return _rawField.getName();
    }

    @Override
    public Type getDeclaringType() {
        return _declaringType;
    }

    @Override
    public Type getReflectedType() {
        return _reflectedTypeCache.getRuntimeType();
    }

    @Override
    public int getModifiers() {
        return _modifiers;
    }

    @Override
    public <T extends Annotation> T getAnnotation(final Class<T> annotationClass) {
        return _rawField.getAnnotation(annotationClass);
    }

    @NotNull
    @Override
    public Annotation[] getAnnotations() {
        return _rawField.getAnnotations();
    }

    @NotNull
    @Override
    public Annotation[] getDeclaredAnnotations() {
        return _rawField.getDeclaredAnnotations();
    }

    @Override
    public boolean isAnnotationPresent(final Class<? extends Annotation> annotationClass) {
        return _rawField.isAnnotationPresent(annotationClass);
    }

    @Override
    public boolean isEquivalentTo(final MemberInfo m) {
        if (m == this) {
            return true;
        }

        if (m instanceof RuntimeFieldInfo) {
            final RuntimeFieldInfo other = (RuntimeFieldInfo) m;

            if (other._declaringType == _declaringType &&
                other._rawField == _rawField) {

                return true;
            }
        }
        return super.isEquivalentTo(m);
    }
}

final class ErasedField extends FieldInfo {
    private final FieldInfo _baseField;
    private final Type<?> _declaringType;
    private final Type<?> _fieldType;

    ErasedField(
        final FieldInfo baseField,
        final Type<?> declaringType,
        final Type<?> fieldType) {

        _baseField = VerifyArgument.notNull(baseField, "baseField");
        _declaringType = VerifyArgument.notNull(declaringType, "declaringType");
        _fieldType = VerifyArgument.notNull(fieldType, "fieldType");
    }

    @Override
    public Type<?> getFieldType() {
        return _fieldType;
    }

    @Override
    public boolean isEnumConstant() {
        return false;
    }

    @Override
    public Field getRawField() {
        return _baseField.getRawField();
    }

    @Override
    public String getName() {
        return _baseField.getName();
    }

    @Override
    public Type getDeclaringType() {
        return _declaringType;
    }

    @Override
    public Type getReflectedType() {
        return _baseField.getReflectedType();
    }

    @Override
    public int getModifiers() {
        return _baseField.getModifiers();
    }

    @Override
    public <T extends Annotation> T getAnnotation(final Class<T> annotationClass) {
        return _baseField.getAnnotation(annotationClass);
    }

    @NotNull
    @Override
    public Annotation[] getAnnotations() {
        return _baseField.getAnnotations();
    }

    @NotNull
    @Override
    public Annotation[] getDeclaredAnnotations() {
        return _baseField.getDeclaredAnnotations();
    }

    @Override
    public boolean isAnnotationPresent(final Class<? extends Annotation> annotationClass) {
        return _baseField.isAnnotationPresent(annotationClass);
    }

    @Override
    public StringBuilder appendErasedDescription(final StringBuilder sb) {
        return _baseField.appendErasedDescription(sb);
    }

    @Override
    public StringBuilder appendErasedSignature(final StringBuilder sb) {
        return _baseField.appendErasedSignature(sb);
    }
}

final class RuntimeType<T> extends Type<T> {
    final static TypeBinder GenericBinder = new TypeBinder();

    private final Type<?> _reflectedType;
    private final Class<T> _erasedClass;
    private final Type<T> _basedOn;
    private final TypeBindings _typeBindings;
    private final TypeBindings _allBindings;

    private Type<? super T> _baseType;
    private TypeList _interfaces;
    private FieldList _fields;
    private ConstructorList _constructors;
    private MethodList _methods;
    private TypeList _nestedTypes;

    RuntimeType(final Type<?> reflectedType, final Type<T> basedOn, final TypeBindings allBindings) {
        _reflectedType = VerifyArgument.notNull(reflectedType, "reflectedType");
        _allBindings = VerifyArgument.notNull(allBindings, "allBindings");
        _erasedClass = basedOn.getErasedClass();
        _basedOn = VerifyArgument.notNull(basedOn, "basedOn");
        _typeBindings = basedOn.getTypeBindings();
    }

    @Override
    public Type getReflectedType() {
        return _reflectedType;
    }

    @SuppressWarnings("unchecked")
    private void ensureBaseType() {
        if (_baseType == null) {
            synchronized (CACHE_LOCK) {
                if (_baseType == null) {
                    final Type genericBaseType = _basedOn.getBaseType();
                    if (genericBaseType == null || genericBaseType == NullType) {
                        _baseType = (Type<? super T>) NullType;
                    }
                    else {
                        _baseType = (Type<? super T>) GenericBinder.visit(genericBaseType, _allBindings);
                    }
                }
            }
        }
    }

    private void ensureInterfaces() {
        if (_interfaces == null) {
            synchronized (CACHE_LOCK) {
                if (_interfaces == null) {
                    _interfaces = GenericBinder.visit(_basedOn.getExplicitInterfaces(), _allBindings);
                }
            }
        }
    }

    private void ensureFields() {
        if (_fields == null) {
            synchronized (CACHE_LOCK) {
                if (_fields == null) {
                    _fields = GenericBinder.visit(this, _basedOn.getDeclaredFields(), _allBindings);
                }
            }
        }
    }

    private void ensureConstructors() {
        if (_constructors == null) {
            synchronized (CACHE_LOCK) {
                if (_constructors == null) {
                    _constructors = GenericBinder.visit(this, _basedOn.getDeclaredConstructors(), _allBindings);
                }
            }
        }
    }

    private void ensureMethods() {
        if (_methods == null) {
            synchronized (CACHE_LOCK) {
                if (_methods == null) {
                    _methods = GenericBinder.visit(this, _basedOn.getDeclaredMethods(), _allBindings);
                }
            }
        }
    }

    private void ensureNestedTypes() {
        if (_nestedTypes == null) {
            synchronized (CACHE_LOCK) {
                if (_nestedTypes == null) {
                    _nestedTypes = Helper.map(
                        _basedOn.getDeclaredTypes(),
                        new TypeMapping() {
                            @Override
                            public Type<?> apply(final Type<?> type) {
                                return new RuntimeType<>(RuntimeType.this, type, _allBindings);
                            }
                        }
                    );
                }
            }
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public Class<T> getErasedClass() {
        return _erasedClass;
    }

    @Override
    public TypeList getExplicitInterfaces() {
        ensureInterfaces();
        return _interfaces;
    }

    @Override
    public Type<? super T> getBaseType() {
        ensureBaseType();
        final Type<? super T> baseType = _baseType;
        return baseType == NullType ? null : baseType;
    }

    @Override
    public Type getGenericTypeDefinition() {
        return _basedOn;
    }

    @Override
    public MemberType getMemberType() {
        return MemberType.TypeInfo;
    }

    @Override
    public Type getDeclaringType() {
        return _basedOn.getDeclaringType();
    }

    @Override
    public final boolean isGenericType() {
        return true;
    }

    @Override
    public TypeBindings getTypeBindings() {
        return _typeBindings;
    }

    @Override
    public int getModifiers() {
        return _basedOn.getModifiers();
    }

    @Override
    public boolean isAnnotationPresent(final Class<? extends Annotation> annotationClass) {
        return _basedOn.isAnnotationPresent(annotationClass);
    }

    @Override
    public <T extends Annotation> T getAnnotation(final Class<T> annotationClass) {
        return _basedOn.getAnnotation(annotationClass);
    }

    @NotNull
    @Override
    public Annotation[] getAnnotations() {
        return _basedOn.getAnnotations();
    }

    @NotNull
    @Override
    public Annotation[] getDeclaredAnnotations() {
        return _basedOn.getDeclaredAnnotations();
    }

    @Override
    public <P, R> R accept(final TypeVisitor<P, R> typeVisitor, final P parameter) {
        return typeVisitor.visitClassType(this, parameter);
    }

    @Override
    protected ConstructorList getDeclaredConstructors() {
        ensureConstructors();
        return _constructors;
    }

    @Override
    protected MethodList getDeclaredMethods() {
        ensureMethods();
        return _methods;
    }

    @Override
    protected FieldList getDeclaredFields() {
        ensureFields();
        return _fields;
    }

    @Override
    protected TypeList getDeclaredTypes() {
        ensureNestedTypes();
        return _nestedTypes;
    }

    @Override
    public boolean isEquivalentTo(final Type other) {
        if (other == this) {
            return true;
        }
        if (other instanceof RuntimeType<?>) {
            return isEquivalentTo(((RuntimeType<?>) other)._basedOn);
        }
        return _basedOn.isEquivalentTo(other);
    }
}

redpajama_set_name: RedPajamaGithub


text:
#region Copyright (c) 2004 Ian Davis and James Carlyle

#endregion

namespace SemPlan.Spiral.Tests.Core {
  using SemPlan.Spiral.Core;
  using System;
  using System.Collections;
	/// <summary>
	/// An instrumented version of Node that counts calls to methods
	/// </summary>
  /// <remarks>
  /// $Id: NodeCounter.cs,v 1.4 2006/02/13 23:44:11 ian Exp $
  ///</remarks>
  public class NodeCounter : Node {

    public int GetLabelCalled = 0;
    public string GetLabel() {
      ++GetLabelCalled;
      return "";
    }

    public int WriteCalled = 0;
    public void Write(RdfWriter writer) {
      ++WriteCalled;
    }

    public int MatchesCalled = 0;
    public bool Matches(ResourceSpecifier specifier) {
      ++MatchesCalled;
      return false;
    }

    public int EquivalentToCalled = 0;
    public bool EquivalentTo(Node other) {
      ++EquivalentToCalled;
      return false;
    }

    public int IsSelfDenotingCalled = 0;
    public bool IsSelfDenoting() {
      ++IsSelfDenotingCalled;
      return false;
    }

    public Bindings Unify(Atom other, Bindings bindings, ResourceMap map) {
      if ( null == bindings) {
        return null;
      }
      else if (Equals(other) ) {
        return bindings;
      }
      else if (other is Variable) {
        return (( Variable)other).Unify( this, bindings, map);
      }
      else {
        return null;
      }

    }

  }
}


text:
package com.royalrangers.service;

import com.dropbox.core.DbxException;
import com.royalrangers.dto.user.UserRegistrationDto;
import com.royalrangers.dto.user.UserUpdateDto;
import com.royalrangers.enums.AuthorityName;
import com.royalrangers.enums.ImageType;
import com.royalrangers.enums.UserAgeGroup;
import com.royalrangers.exception.UserRepositoryException;
import com.royalrangers.model.Authority;
import com.royalrangers.model.TempUser;
import com.royalrangers.model.User;
import com.royalrangers.model.VerificationToken;
import com.royalrangers.repository.*;
import com.royalrangers.utils.security.JwtUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.net.UnknownHostException;
import java.util.*;
import java.util.stream.Collectors;

import static com.royalrangers.enums.AuthorityName.*;

@Slf4j
@Service
public class UserService {

    private final String CONFIRM_EMAIL_STRING = "/#/registration/confirm?token=";
    private final String CHANGE_PASSWORD_STRING = "/#/changePassword?token=";

    @Value("${application.host}")
    private String host;

    @Autowired
    private EmailService emailService;

    @Autowired
    private DropboxService dropboxService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private CountryRepository countryRepository;

    @Autowired
    private RegionRepository regionRepository;

    @Autowired
    private CityRepository cityRepository;

    @Autowired
    private PlatoonRepository platoonRepository;

    @Autowired
    private SectionRepository sectionRepository;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthorityRepository authorityRepository;

    @Autowired
    private TempUserRepository tempUserRepository;

    private void grantAuthority(User user, AuthorityName authorityName) {
        Set<Authority> authoritySet = new HashSet<>();

        switch (authorityName) {
            case ROLE_SUPER_ADMIN:
                authoritySet.add(authorityRepository.findByName(ROLE_SUPER_ADMIN));
            case ROLE_ADMIN:
                authoritySet.add(authorityRepository.findByName(ROLE_ADMIN));
            case ROLE_USER:
                authoritySet.add(authorityRepository.findByName(ROLE_USER));
        }

        user.setAuthorities(authoritySet);
    }

    public User createUser(UserRegistrationDto userDto) {
        User user = new User();
        user.setCreateDate(new Date());
        user.setUpdateDate(new Date());
        user.setEmail(userDto.getEmail());
        user.setFirstName(userDto.getFirstName());
        user.setLastName(userDto.getLastName());
        user.setPassword(passwordEncoder.encode(userDto.getPassword()));
        user.setEmail(userDto.getEmail());
        user.setEnabled(false);
        user.setConfirmed(false);
        user.setApproved(false);
        user.setRejected(false);
        user.setUserAgeGroup(determineUserAgeGroup(calculateUserAge(userDto.getBirthDate())));
        user.setLastPasswordResetDate(new Date(System.currentTimeMillis()));
        user.setGender(userDto.getGender());
        user.setTelephoneNumber(userDto.getTelephoneNumber());
        user.setBirthDate(userDto.getBirthDate());
        user.setUserRank(userDto.getUserRank());
        user.setCountry(countryRepository.findOne(userDto.getCountryId()));
        user.setRegion(regionRepository.findOne(userDto.getRegionId()));
        user.setCity(cityRepository.findOne(userDto.getCityId()));
        user.setPlatoon(platoonRepository.findOne(userDto.getPlatoonId()));

        if (userDto.getSectionId() != null) {
            user.setSection(sectionRepository.findOne(userDto.getSectionId()));
        }

        grantAuthority(user, userDto.getAuthorityName());

        return user;
    }

    public void registerUser(UserRegistrationDto userInfo) {
        if (isEmailExist(userInfo.getEmail()))
            throw new UserRepositoryException("User with email " + userInfo.getEmail() + " already exists");

        User user = createUser(userInfo);
        userRepository.save(user);

        try {
            emailService.sendEmail(user, "RegistrationConfirm",
                    "submit.email.inline.html", generateConfirmationLink(user, CONFIRM_EMAIL_STRING));
        } catch (UnknownHostException e) {
            log.error("Error in confirmation URL for " + userInfo.getEmail());
        }
    }

    public Boolean isEmailExist(String email) {
        return (userRepository.findByEmail(email) != null);
    }

    public Boolean isTempUserExist() {
        return (tempUserRepository.findByUserId(getAuthenticatedUserId()) != null);
    }

    private String generateConfirmationLink(User user, String link) throws UnknownHostException {
        return "http://" + host + link + tokenService.generateVerificationToken(user);
    }

    private int calculateUserAge(Long birthdate) {
        Calendar cal = Calendar.getInstance();
        double userAge = (cal.getTime().getTime() - birthdate) * 3.170979E-11;
        return (int) userAge;
    }

    private UserAgeGroup determineUserAgeGroup(int userAge) {
        UserAgeGroup rank = UserAgeGroup.BEGINNER;
        if (userAge >= 5 && userAge <= 7)
            return UserAgeGroup.BEGINNER;
        if (userAge >= 8 && userAge <= 10)
            return UserAgeGroup.PIONEER;
        if (userAge >= 11 && userAge <= 13)
            return UserAgeGroup.PATHFINDER;
        if (userAge >= 14 && userAge <= 16)
            return UserAgeGroup.RANGER;
        if (userAge >= 17)
            return UserAgeGroup.ADULT;
        return rank;
    }

    public List<User> getUsersForApprove() {
        User user = userRepository.findOne(getAuthenticatedUserId());
        if (user.hasRole(ROLE_SUPER_ADMIN))
            return userRepository.findAllByConfirmedTrueAndApprovedFalse();
        else if (user.hasRole(ROLE_ADMIN)) {
            Long platoonId = user.getPlatoon().getId();
            return userRepository.findAllByConfirmedTrueAndApprovedFalseAndPlatoonId(platoonId);
        } else
            return Collections.emptyList();
    }

    public Long getAuthenticatedUserId() {
        JwtUser user = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return user.getId();
    }

    public User getAuthenticatedUser() {
        return userRepository.findByEmail(getAuthenticatedUserEmail());
    }

    public String getAuthenticatedUserEmail() {
        return SecurityContextHolder.getContext().getAuthentication().getName();
    }

    public void approveUser(Long id) {
        User user = userRepository.findOne(id);
        user.setApproved(true);
        user.setEnabled(true);
        user.setRejected(false);
        userRepository.save(user);
        emailService.sendEmail(user, "Registration accepted", "approved.inline.html", "");
        log.info("User " + user.getEmail() + " approved.");
    }

    public void rejectUser(Long id) {
        User user = userRepository.findOne(id);
        user.setEnabled(false);
        user.setConfirmed(false);
        user.setRejected(true);
        userRepository.save(user);
        emailService.sendEmail(user, "Registration rejected", "rejected.inline.html", "");
        log.info("User " + user.getEmail() + " rejected.");
    }

    public void rejectTempUser(Long id) {
        TempUser tempUser = tempUserRepository.findOne(id);
        tempUserRepository.delete(tempUser);
        log.info("TempUser " + tempUser.getEmail() + " rejected.");
    }

    public User getUserByEmail(String email) {
        return userRepository.findByEmail(email);
    }

    public User getUserById(Long id) throws DataAccessException {
        if (!userRepository.exists(id)) {
            throw new UserRepositoryException("Not found user with id " + id);
        }
        return userRepository.findOne(id);
    }

    public List<TempUser> getTempUsersForUpdate() {
        User user = userRepository.findOne(getAuthenticatedUserId());
        if (user.hasRole(ROLE_SUPER_ADMIN))
            return tempUserRepository.findAll();
        else if (user.hasRole(ROLE_ADMIN)) {
            Long platoonId = user.getPlatoon().getId();
            return tempUserRepository.findByPlatoonId(platoonId);
        } else
            return Collections.emptyList();
    }

    public TempUser getTempUser() {
        TempUser tempUser = tempUserRepository.findByUserId(getAuthenticatedUserId());
        return tempUserRepository.findOne(tempUser.getId());
    }

    private void createTempUser() {
        User user = getAuthenticatedUser();
        TempUser tempUser = new TempUser();

        tempUser.setUser(user);
        tempUser.setCreateDate(user.getCreateDate());
        tempUser.setUpdateDate(user.getUpdateDate());
        tempUser.setFirstName(user.getFirstName());
        tempUser.setLastName(user.getLastName());
        tempUser.setGender(user.getGender());
        tempUser.setTelephoneNumber(user.getTelephoneNumber());
        tempUser.setBirthDate(user.getBirthDate());
        tempUser.setUserAgeGroup(user.getUserAgeGroup());
        tempUser.setUserRank(user.getUserRank());
        tempUser.setCountry(user.getCountry());
        tempUser.setRegion(user.getRegion());
        tempUser.setCity(user.getCity());
        tempUser.setPlatoon(user.getPlatoon());
        tempUser.setSection(user.getSection());

        tempUserRepository.save(tempUser);
    }

    /**
     Compares temp_user to user - if they are the same we should delete temp_user
     */
    public boolean isTempUserEqualsUser(TempUser tempUser) {
        User user = getAuthenticatedUser();

        return  tempUser.getBirthDate().equals(user.getBirthDate()) && tempUser.getCity().equals(user.getCity()) && tempUser.getCountry().equals(user.getCountry()) &&
                tempUser.getPlatoon().equals(user.getPlatoon()) && tempUser.getRegion().equals(user.getRegion()) && tempUser.getSection().equals(user.getSection()) &&
                tempUser.getFirstName().equals(user.getFirstName()) && tempUser.getLastName().equals(user.getLastName()) && tempUser.getGender().equals(user.getGender()) &&
                tempUser.getTelephoneNumber().equals(user.getTelephoneNumber()) && tempUser.getUserAgeGroup().equals(user.getUserAgeGroup()) &&
                tempUser.getUserRank().equals(user.getUserRank());
    }

    public void removeTempUserByAuthenticatedUserId(){
        tempUserRepository.delete(tempUserRepository.findByUserId(getAuthenticatedUserId()));
    }

    public TempUser getTempUserById(Long id) {
        return tempUserRepository.findOne(id);
    }

    public void updateTempUser(UserUpdateDto update){
        if (!isTempUserExist()) {
            createTempUser();
            updateTempUsr(update);
        } else {
            updateTempUsr(update);
        }
    }

    private void updateTempUsr(UserUpdateDto update) {
        TempUser user = tempUserRepository.findByUserId(getAuthenticatedUserId());

            user.setUpdateDate(new Date());
            user.setFirstName(update.getFirstName());
            user.setLastName(update.getLastName());
            user.setGender(update.getGender());
            user.setBirthDate(update.getBirthDate());
            user.setTelephoneNumber(update.getTelephoneNumber());
            user.setUserAgeGroup(update.getUserAgeGroup());
            user.setUserRank(update.getUserRank());
            user.setCountry(countryRepository.findOne(update.getCountryId()));
            user.setRegion(regionRepository.findOne(update.getRegionId()));
            user.setCity(cityRepository.findOne(update.getCityId()));
            user.setPlatoon(platoonRepository.findOne(update.getPlatoonId()));
            user.setSection(sectionRepository.findOne(update.getSectionId()));

            tempUserRepository.save(user);

    }

    public void updateUser(Long id, UserUpdateDto update) {
        TempUser tempUser = getTempUserById(id);
        User user = tempUser.getUser();

        user.setUpdateDate(new Date());
        user.setFirstName(update.getFirstName());
        user.setLastName(update.getLastName());
        user.setGender(update.getGender());
        user.setBirthDate(update.getBirthDate());
        user.setTelephoneNumber(update.getTelephoneNumber());
        user.setUserAgeGroup(update.getUserAgeGroup());
        user.setUserRank(update.getUserRank());
        user.setCountry(countryRepository.findOne(update.getCountryId()));
        user.setRegion(regionRepository.findOne(update.getRegionId()));
        user.setCity(cityRepository.findOne(update.getCityId()));
        user.setPlatoon(platoonRepository.findOne(update.getPlatoonId()));
        user.setSection(sectionRepository.findOne(update.getSectionId()));

        userRepository.save(user);
        tempUserRepository.delete(tempUser);
    }

    public void updateUserById(Long id, UserUpdateDto update) {
        if (!userRepository.exists(id)) {
            throw new UserRepositoryException("Not found user with id " + id);
        }

        User user = userRepository.findOne(id);

        user.setUpdateDate(new Date());
        user.setFirstName(update.getFirstName());
        user.setLastName(update.getLastName());
        user.setGender(update.getGender());
        user.setTelephoneNumber(update.getTelephoneNumber());
        user.setBirthDate(update.getBirthDate());
        user.setUserAgeGroup(update.getUserAgeGroup());
        user.setUserRank(update.getUserRank());
        user.setCountry(countryRepository.findOne(update.getCountryId()));
        user.setRegion(regionRepository.findOne(update.getRegionId()));
        user.setCity(cityRepository.findOne(update.getCityId()));
        user.setPlatoon(platoonRepository.findOne(update.getPlatoonId()));
        user.setSection(sectionRepository.findOne(update.getSectionId()));

        userRepository.save(user);
    }

    public List<User> getUsersByPlatoon() {
        return userRepository.findUsersByApprovedTrueAndPlatoon_Id(getAuthenticatedUser().getPlatoon().getId());
    }

    public void setUserAvatarUrl(String avatarUrl) throws DbxException {
        User user = getAuthenticatedUser();
        if (user.getAvatarUrl() != null) {
            dropboxService.deleteImage(user.getAvatarUrl(), ImageType.USER_AVATAR);
        }

        user.setAvatarUrl(avatarUrl);
        userRepository.save(user);
    }

    public void confirmUser(VerificationToken verificationToken) {
        User user = verificationToken.getUser();
        user.setConfirmed(true);
        getPlatoonAdminsList(user).forEach(admin -> emailService.sendEmail(admin,"New user needs approve", "newuserforapprove.inline.html", ""));
        userRepository.save(user);
    }

    private List<User> getPlatoonAdminsList(User user) {
        Long platoonId = user.getPlatoon().getId();
        List<User> usersByPlatoon = userRepository.findAllByPlatoonId(platoonId);
        List<User> adminList = usersByPlatoon.stream().filter(element -> user.hasRole(ROLE_ADMIN))
                .collect(Collectors.toList());
        if (adminList.isEmpty())
            throw new UserRepositoryException("Admin not found in platoon " + platoonId);
        return adminList;
    }

    public void resendConfirmation(String email) throws UserRepositoryException, UnknownHostException {
        User user = userRepository.findByEmail(email);

        if (!isEmailExist(email)) {
            throw new UserRepositoryException("User with this email is not exist.");
        }
        if (user.getConfirmed()) {
            throw new UserRepositoryException("User with this email already confirmed.");
        }
        if (user.getRejected()) {
            throw new UserRepositoryException("User with this email has been rejected.");
        }

        emailService.sendEmail(user, "RegistrationConfirm",
                "submit.email.inline.html", generateConfirmationLink(user, CONFIRM_EMAIL_STRING));
    }

    public void sendResetPasswordEmail(String email) throws UserRepositoryException, UnknownHostException {
        User user = userRepository.findByEmail(email);

        if (!isEmailExist(email)) {
            throw new UserRepositoryException("User with this email " + email + " is not exist.");
        }
        if (!user.getConfirmed()) {
            throw new UserRepositoryException("User with this email " + email + " already confirmed.");
        }
        if (user.getRejected()) {
            throw new UserRepositoryException("User with this email " + email + " has been rejected.");
        }

        emailService.sendEmail(user, "ResetPassword",
                "reset.password.inline.html", generateConfirmationLink(user, CHANGE_PASSWORD_STRING));
        log.info("Send reset password email for user:  " + email);

    }

    public void changeUserPassword(String token, String newPassword) {
        VerificationToken verificationToken = tokenService.getVerificationToken(token);
        User user = verificationToken.getUser();
        user.setPassword(passwordEncoder.encode(newPassword));
        userRepository.save(user);
        log.info("Change password for user: " + user.getEmail());
    }
}


text:
from collections import OrderedDict
from inspect import isclass

def pretty_name(name):
    """Converts 'first_name' to 'First name'"""

    if not name:
        return u''

    return name.replace('_', ' ').capitalize()

class WTFormToJSONSchema(object):
    DEFAULT_CONVERSIONS = {
        'URLField': {
            'type': 'string',
            'format': 'uri'
        },
        'URIField': {
            'type': 'string',
            'format': 'uri'
        },
        'URIFileField': {
            'type': 'string',
            'format': 'uri',
            'ux-widget': 'file-select' #not part of spec but flags behavior
        },
        'FileField': {
            'type': 'string',
            'format': 'uri',
            'ux-widget': 'file-select' #not part of spec but flags behavior
        },
        'DateField': {
            'type': 'string',
            'format': 'date'
        },
        'DateTimeField': {
            'type': 'string',
            'format': 'datetime'
        },
        'DecimalField': {
            'type': 'number'
        },
        'IntegerField': {
            'type': 'integer'
        },
        'BooleanField': {
            'type': 'boolean'
        },
        'StringField': {
            'type': 'string'
        },
        'SearchField': {
            'type': 'string'
        },
        'TelField': {
            'type': 'string',
            'format': 'phone'
        },
        'EmailField': {
            'type': 'string',
            'format': 'email'
        },
        'DateTimeLocalField': {
            'type': 'string',
            'format': 'datetime'
        },
        'ColorField': {
            'type': 'string',
            'format': 'color'
        },
        #TODO min/max
        'DecimalRangeField': {
            'type': 'number'
        },
        'IntegerRangeField': {
            'type': 'integer'
        },
    }

    INPUT_TYPE_MAP = {
        'text': 'StringField',
        'checkbox': 'BooleanField',
        'color': 'ColorField',
        'tel': 'TelField'
    }

    def __init__(
        self,
        form,
        conversions=None,
        include_array_item_titles=True,
        include_array_title=True,
        forms_seen=None,
        json_schema=None,
        path=None,
        *args, **kwargs
    ):
        super(WTFormToJSONSchema, self).__init__(*args, **kwargs)

        self.conversions = conversions or self.DEFAULT_CONVERSIONS
        self.include_array_item_titles = include_array_item_titles
        self.include_array_title = include_array_title

        self.form = form
        self.forms_seen = {}
        self.json_schema = {
            'type': 'object',
            'properties': OrderedDict()
        }
        self.path = []

        if forms_seen is not None:
            self.forms_seen = forms_seen

        if json_schema is not None:
            self.json_schema = json_schema

        if path is not None:
            self.path = path

        key = id(self.form)

        if key in self.forms_seen:
            self.json_schema['$ref'] = '#{0}'.format(
                '/'.join(self.forms_seen[key])
            )
            self.json_schema.pop('properties', None)

        else:
            self.forms_seen[key] = self.path

        if isclass(self.form):
            self.form = self.form()
            fields = [
                name
                for name, ufield in self.form._unbound_fields
            ]

        else:
            fields = self.form._fields.keys()

        for name in fields:
            if name not in self.form._fields:
                continue

            field = self.form._fields[name]
            self.json_schema['properties'][name] = self._convert_formfield(
                name=name,
                field=field
            )

    def __call__(self):
        return self.json_schema

    def _convert_formfield(self, name=None, field=None):
        widget = field.widget
        target_def = {
            'title': field.label.text,
            'description': field.description
        }

        self.path.append(name)

        if field.flags.required:
            target_def['required'] = True
            self.json_schema.setdefault('required', list())
            self.json_schema['required'].append(name)

        ftype = type(field).__name__
        methodname = '_convert_{0}'.format(ftype)
        method = getattr(self, methodname, None)

        if callable(method):
            return method(
                name=name,
                field=field
            )

        params = self.conversions.get(ftype)

        if params is not None:
            target_def.update(params)

        elif ftype == 'FormField':
            key = id(field.form_class)

            if key in self.forms_seen:
                return {'$ref': '#{0}'.format('/'.join(self.forms_seen[key]))}

            self.forms_seen[key] = self.path
            schemagen = WTFormToJSONSchema(
                field.form_class(obj=getattr(field, '_obj', None))
            )

            target_def.update(schemagen())

        elif ftype == 'FieldList':
            if not self.include_array_title:
                target_def.pop('title')
                target_def.pop('description')

            target_def['type'] = 'array'

            subfield = field.unbound_field.bind(
                getattr(field, '_obj', None),
                name
            )

            target_def['items'] = self.convert_formfield(
                name=name,
                field=subfield
            )

            if not self.include_array_item_titles:
                target_def['items'].pop('title', None)
                target_def['items'].pop('description', None)

        else:
            try:
                input_type = widget.input_type

            except AttributeError:
                target_def['type'] = 'string'

            else:
                it = self.INPUT_TYPE_MAP.get(input_type, 'StringField')

                methodname = '_convert_{0}'.format(it)
                method = getattr(self, methodname, None)

                if callable(method):
                    return method(
                        name=name,
                        field=field
                    )

                target_def.update(self.conversions[it])

        return target_def

    def _convert_SelectField(self, field=None, **_):
        values = list()

        for val, label in field.choices:
            if isinstance(label, (list, tuple)):  # wonky option groups
                values.extend([x for x, y in label])

            else:
                values.append(val)

        target_def = {
            'title': field.label.text,
            'description': field.description,
            'enum': values,
            'ux-widget-choices': list(field.choices)
        }

        if field.flags.required:
            target_def['required'] = True

        return target_def

    def _convert_RadioField(self, field=None, **_):
        target_def = {
            'title': field.label.text,
            'description': field.description,
            'enum': [x for x, y in field.choices],
            'ux-widget': 'radio',
            'ux-widget-choices': list(field.choices)
        }

        if field.flags.required:
            target_def['required'] = True

        return target_def

def form_to_jsonschema(*args, **kwargs):
    generator = WTFormToJSONSchema(*args, **kwargs)
    return generator()


text:
using System;
using Chiro.Cdf.Mailer;
using Chiro.Gap.Test;
using NUnit.Framework;

// Unit tests zonder veel structuur.  Achteraf op te kuisen.
// Makkelijkste is om de loginservice te runnen vanuit 1 Visual Studio instance, en deze tests vanuit
// een andere.

namespace Chiro.Ad.Test
{
    [TestFixture]
    public class MailTest: ChiroTest
    {
        [Test]
        public void MailNaarGmail()
        {
            IMailer mailer = Factory.Maak<IMailer>();

            mailer.Verzenden("johan.vervloet@gmail.com", "unit test " + DateTime.Now, "unit test");

            Assert.IsTrue(true);
        }

        [Test]
        public void MailNaarChiro()
        {
            IMailer mailer = Factory.Maak<IMailer>();

            mailer.Verzenden("johan.vervloet@chiro.be", "unit test " + DateTime.Now, "unit test");

            Assert.IsTrue(true);
        }

    }
}


text:
class CreateWearables < ActiveRecord::Migration[5.1]
  def change
    create_table :wearables do |t|
      t.string :name
      t.boolean :is_worn, default: false
      t.boolean :is_magical, default: false
      t.integer :owner_id
      t.integer :room_id
      t.timestamps null: false
    end
  end
end


text:
namespace Sarene
{
	class OrthographicCamera
	{
	public:
		OrthographicCamera(float left, float right, float bottom, float top);

		const glm::vec3& GetPosition() const { return m_Position; }
		void SetPosition(const glm::vec3& position)
		{
			m_Position = position;
			RecalculateViewMatrix();
		}

		float GetRotation() const { return m_Rotation; }
		void SetRotation(float rotation)
		{
			m_Rotation = rotation;
			RecalculateViewMatrix();
		}

		const glm::mat4& GetProjectionMatrix() const { return m_ProjectionMatrix; }
		const glm::mat4& GetViewMatrix() const { return m_ViewMatrix; }
		const glm::mat4& GetViewProjectionMatrix() const { return m_ViewProjectionMatrix; }
	private:
		glm::mat4 m_ProjectionMatrix;
		glm::mat4 m_ViewMatrix;
		glm::mat4 m_ViewProjectionMatrix;

		glm::vec3 m_Position = { 0.0f, 0.0f, 0.0f };
		float m_Rotation = 0.0f;

		void RecalculateViewMatrix();
	};
}


text:
/*general body - used by main portal document */
body{
	width: 100%;
	padding: 0;
	font-family: arial, Verdana, sans-serif;
	font-size:62.5%;
	margin: auto;
	background: #fff;
}

/*PART 1 - MAIN LAYOUT BLOCKS*/
/*outer wrapper for portal content (decorative - child is #portalContainer )*/
#portalOuterContainer{
	background: #fff;
	display: block;
	margin-left: auto;
	margin-right: auto;
   	height:100%;
}

/*inner wrapper for portal content (decorative - children are #header #container and #footer )*/
#portalContainer{
	background: #264C83 url(../images/banner_inst.gif) no-repeat 253px top;
}

/*wrapper masthead  and site navigation
 two possible states - logged in headerMax, not logged in - headerMin*/
#headerMax,#headerMin{
	width: 100%;
	margin: 0;
	padding: 0;
	overflow: hidden;
}

/*accessibility links wrapper */
#skipNav{
}

/*site hierarchy breadcrumb*/
#siteHierarchy{
        clear:both;
        float:none;
        margin:0;
        list-style: none;
        padding:.5em 0;
}
/*style the standard breadcrumbseparator
can set display:none if needed because the list-style is taking care of it*/
.breadSeparator{
}
#siteHierarchy li{
        display:inline;
}
#siteHierarchy li a, #siteHierarchy li a:visited{
        color:#09c;
}

/*wrapper for site content (includes as children #toolMenuWrap,#content and #footer)*/
#container{
	position: relative;
	clear:both;
	padding: 0;
	margin: 0;
	background-color: #fff;
	border-top:1px solid white;
}

/*wrapper for #toolMenu - children are #worsiteLogo,#toolMenu*/
#toolMenuWrap{
	position:relative;
	top: 0;
	left:0;
	float:left;
	width: 189px;
	color: #000;
	text-align: left;
	padding: 0;
	margin: 0;
	padding-top: 2em;
}

#toolMenuWrap:hover{
	/*border-right:2px solid #09c;*/
	}
/*depending on site type - different hover effects for the tool menu parent block
site types are a local setting - adjust */
.workspace #toolMenuWrap:hover{
	/*border-right:2px solid #aaa;*/
}
.course #toolMenuWrap:hover{
	/*border-right:2px solid #FC6;*/
}
.project #toolMenuWrap:hover{
	/*border-right:2px solid #9CF;*/
}

/*wrapper for site content (portlets) -  children can be #col1 or #col1of2 and #col2of2 depending in the number of columns*/
#content{
	margin-left: 190px;
	padding-top: 2em;
	height:100%;
}

/*margin tweak for IE to avoid float drop*/
* html #content{margin-left:11.3em}
/*wrapper for footer blocks*/
#footer{
	color: #000;
	background-color: #FFF;
	font-size: x-small;
	margin: 0px;
	padding: 0.4em 0 1.7em;
	width: auto;
	clear: both;
	top: 0;
	text-align: center;
}

/*PART 2 - HEADER IFRAME SETTINGS*/
/*iframe sizes for different states*/
/*gone for 2.3
.sitenav-log{
	user not logged in
	height: 90px;
	width: 0%;
	border-bottom:1px solid #09c
}

.sitenav-max{
	user logged in
	height: 90px;
	max-height:90px;
	min-height:90px;
	width: 100%;

* html .sitenav-max{
	user logged in - iframe height tweak for IE
	height: 8em;
	}
.sitenav-min{
	no logos or banners
	height: 2em;
	width: 100%;
}*/

/*PART 3 - HEADER BLOCKS (BRANDING,LOGIN)*/
/*depending on site type - different border-bottoms for the site menu parent block
site types are a local setting - adjust */
.workspace .siteNavWrap{
	height:100%;

}
.course .siteNavWrap{

}
.project .siteNavWrap{

}
#siteNavWrapper{
	margin: 0;
}

/*wrapper for mast head elements - children are 3 blocks - #mastLogo,#mastBanner,#mastLogin*/
#mastHead{
	clear: both;
}

/*container wrapping branding images - portal outputs one /library/skin/<skin name>/images/logo_inst.gif
that can be used or hidden,can also use a background:url(../images/<image name>.<ext>) in this block,or both superimposing them*/
#mastLogo{
	float: left;
	width: auto;
	height:90px;
}

/*the portal outputs an image that can be treated here or hidden with display:none*/
#mastLogo img{
	margin: 0em 0em;
	height:89px;
}

#mastLogo img a link{
	margin: 0em 0em;
	height:89px;
}

/*another container wrapping branding images - portal outputs one /library/skin/<skin name>/images/banner_inst.gif
that can be used or hidden,can also use a background:url(../images/<image name>.<ext>) in this block,or both superimposing them*/
#mastBanner{
	display: none;
	width: auto;
	vertical-align: top;
	float: left;
	height:90px;
}

/*the portal outputs an image that can be treated here or hidden with display:none*/
#mastBanner img{
	margin: 0em 0em;
    display: block;
	height:90px;
}

/*container wrapping,depending on Sakai settings:1) a login form,2) a login link for CAS,3) a logout link*/
#mastLogin{
	float: left;
	text-align: right;
	vertical-align: top;
	width: 100%;
	height:100%;
	overflow: hidden;

}

/*the anchor for the login link for CAS above can be an image - treated here*/
#mastLogin img{
	margin-top: 0;

}

/*login form elements - in order,form,userid field,password field,login button - first 2 have labels associated with them,gettable as #loginForm label{
}

#loginForm is the form for login - contains children #eid #pw #submit*/
#loginForm{
	margin: 0em 10em 0 0em;
	background: #f5db73;
	width:100%;
	text-align: left;
	padding: .4em .75em .4em 20px;
}

#eid, #pw{
	border: 1px solid #aaa;
	padding: 1px;
	margin-left: .5em;
	width: 7em;
}

#loginForm label{
	color: #000;
	padding: 0 .5em;
	text-transform: capitalize;
	font-size: 1.1em;
}

#submit{
}

#submit:hover{
	color: #fc7317;
}

/*block for login/logout links */
#loginLinks{
	position:absolute;
	display:block;
	width: 73px;
	height: 18px;
	left:680px;
	top:0px;
}

#loginLinks a, #loginLinks a:visited, #loginLinks a:active{
	margin: 0;
	padding: 1px 0 0;
	display: block;
	font-size: 1.1em;
	font-family: arial, san-serif;
	font-weight: bold;
	background: url(../images/logout.gif) top right no-repeat;
	color: #264c83;
	width: 73px;
	height: 18px;
	text-decoration:none;
	text-align: center;

}

#loginLinks a:hover{
	font-weight: bold;
	height: 18px;
	background: url(../images/logout_h.gif) top right no-repeat;
	color: #fb741a;
}

/*main CAS link*/
#loginLink1{
}

/*secondary CAS link*/
#loginLink2{
}

/*PART 4 - SITE NAVIGATION - children of #siteNavBlock*/
/*outer wrapper for the site navigation blocks - it is a class,not an id because it can be overloaded with other values having to do with site type
so for example
 so that different site types can be treated differently via inheritance - children are #siteNavWrap and #navBottom*/
.siteNavWrap{
	position:relative;
 	width: 100%;
	background: url(../images/navback.gif) bottom repeat-x;
	float:left;
	clear:both;
	font-size: 1.2em;
	font-weight: bold;
	line-height: normal;
	z-index: 2000;
}

/*wrapper for the site links and site <select> blocks - children are #siteNav and #tabNav */
#siteNav{

}

/*wrapper for the site link list   - the #siteLinkList child)*/
#linkNav{
	position: relative;
	display: block;
	float:left;
}

/*wrapper for the site <select> that is displayed when more than x sites are in the link list*/
#selectNav{
	padding: 0;
	text-align: left;
	vertical-align: middle;
	float: left;
}

/*the <select> contextually defined*/
#selectNav select{
	display:inline;
	font-size: .8em;
	margin: 0px;
	padding: 0px;
	border:double 2px #f4d472;

}

#selectNav select option{
	background: #fff;
}

/*a ul - the li below are outer wrappers for the links to sites */
#siteLinkList{
/*	white-space: nowrap;*/
	line-height: normal;
	margin: 0;
	list-style:none;
	padding: 3px 5px 0;
}

/*list elements - children are  and */
#siteLinkList li {
	display: block;
	float: left;
    background: url("../images/norm_right.gif") no-repeat right top;
    margin: 2px 0 0 3px;
	padding: 0;
}

#siteLinkList a {
      float:left;
      background:url("../images/norm_left.gif") no-repeat left top;
      margin:0;
      padding: 5px 15px 4px;
      text-decoration:none;
      display: block;
}

/*span shim for fine grained manipulation of link display (decorative)*/
#siteLinkList li span {
}

#siteLinkList .selectedTab, #siteLinkList .more-active {
background-image:url(../images/norm_right_on.gif);
	cursor: text;
	text-decoration: none;
	margin-top: 0px;
}

/*the current sites' link*/
#siteLinkList .selectedTab a,
	#siteLinkList .selectedTab a:link,
	#siteLinkList .selectedTab a:visited,
	#siteLinkList .selectedTab a:hover,
	#siteLinkList li.more-active a {
		background-image:url(../images/norm_left_on.gif);
		padding-top: 7px;
		padding-bottom: 6px;
		color: #072e5b;
}

/*links to other sites*/
#siteLinkList a,#siteLinkList a:link,#siteLinkList a:visited{
	text-decoration: none;
	color: #264c83;
}

/*hover state for links to other sites*/
#siteLinkList a:hover{
	color: #Fb741a;
	text-decoration: none;
}

#siteLinkList .tab-dim {
	background:transparent url(../images/norm_right_on_dim.gif) no-repeat scroll right top;
}

#siteLinkList .tab-dim a,
	#siteLinkList .tab-dim a:link,
	#siteLinkList .tab-dim a:visited,
	#siteLinkList .tab-dim a:hover {
	background: transparent url(../images/norm_left_on_dim.gif) no-repeat scroll left top;
	padding-bottom: 4px;
	color: #264C83;
}

/* more tab */
#siteLinkList .more-tab a .inner {
	background-image:  url(../images/tab-arrow-down.gif);
	background-repeat: no-repeat;
	background-position: 100% 36%;
	padding: 0 20px 0 0;
	margin: 0;
	outline: 0;
}

#siteLinkList .more-tab a:hover .inner {
	background-image:  url(../images/tab-arrow-down-over.gif);
	color: #FB741A
}

#siteLinkList li.more-active a span {
	background:transparent url(../images/tab-right-selected.gif) no-repeat scroll right top;
}

#siteLinkList li.more-active a span.inner {
	background-image: url(../images/tab-arrow-down.gif);
}

.fixTabsIE{
	visibility: hidden;
	display: none;
	border-width: 0;
}

/*wrapper for the site <select> that is displayed when more than x sites are in the link list*/
.dhtml_more_tabs {
	position: absolute;
	top: 2.5em;
	right: 4px;
	line-height: 1.5em;
	background-color: #FFFFFF;
	border: 2px solid #FC7317;
	border-top-width: 0;
	width: 75%;
	z-index: 9999;
}

html>body .dhtml_more_tabs {
	right: 5px;
}

.dhtml_more_tabs div.termContainer {
	float: left;
	padding: 0.8em;
	text-align: left;
	width: 28%;
}

.dhtml_more_tabs h4 {
	font-size: 1.09em;
	margin: 0 0 0.3em;
	padding: 0;
	font-weight: bold;
}

.dhtml_more_tabs  ul {
	list-style: none;
	margin: 0;
	padding: 0;
}

.dhtml_more_tabs  li {
	margin-bottom: 0.4em;
	line-height: 1.1em;
}

.dhtml_more_tabs div:first-child {
	border-left: none;
}

.dhtml_more_tabs a:link, .dhtml_more_tabs a:visited, .dhtml_more_tabs active{
	color: #274B82;
	text-decoration: none;
	font-weight: normal;
}

.dhtml_more_tabs a:hover {
	color: #FB741A;
	text-decoration: underline !important;
}

#more_tabs_instr  {
	color: #444;
	font-size: 1em;
	margin: 0.4em 0.8em 0.7em;
	padding-top: 0.6em;
	clear: both;
	border-top: 1px solid #CCC;
	text-align: left;
	line-height: 1.26em;
	font-weight: normal;
}

#portalMask {
	background-color: #6781A8;
	position: absolute;
	z-index: 9000;
	top:-1px;
	left:0;
	filter:alpha(opacity=30);
	opacity: 0.30;
	-moz-opacity: 0.30;
}

/*block in case need to display any decorative element above or below the .tabHolder block*/
#navBottom{
	display: none;
}

/*PART 5 - SITE TOOL LINKS  - children of #toolMenuWrap	*/
/*wrapper for ul that lists the links to tools*/
#toolMenu{
	background: url(../images/mytoolsfooter.gif) no-repeat bottom left;
	padding: 0px 0px 13px 0px;
	width: 150px;
	margin-left: 24px;
}

#container #toolMenu ul {
	background: url(../images/tools-header.gif) no-repeat top left;
}

#container.workspace #toolMenu ul {
	background: url(../images/tools-workspace-header.gif) no-repeat top left;
}

#container.project #toolMenu ul {
	background: url(../images/tools-project-header.gif) no-repeat top left;
}

#container.course #toolMenu ul {
	background: url(../images/tools-course-header.gif) no-repeat top left;
}

#toolMenu ul {
	margin: 0 -10px auto 0px;
	padding: 24px 10px 0 0px;
	width: 150px;
	list-style: none;
	font-size: 1.2em;
	line-height: 1.2em;
}

#toolMenu li{
	margin: 0;
	width: auto;
	border-bottom: #ACBACF solid 1px;
	text-align: left;
	background: #f9E7AF;
	color: #264C83;
}

/*span shim for fine grained manipulation of link display (decorative)
also hide if are going to be using icon links (as background of  nad

*/

#toolMenu li span{
	display:block;
	padding: 0.4em 1.4em 0.4em 13px;
/*comment this line for a return to sanity
display:none*/
}

#toolMenu li a:link,#toolMenu li a{
	display: block;
	text-decoration: none;
	color: #264c83;
}
#toolMenu li a:hover{
	text-decoration: none;
	color: #fb741a;
background:url(../images/pointer_tools.gif) no-repeat right;
	background-color: #fff;

}

/* The class selector's entitled *selected* seems no longer to appear in the html. My theory is that it has been renamed to "selectedTool" which is more semantically accurate but does not exist as of yet in the css. This is why I am commenting out the next 4 clases and repeating them with selectedTool instead of selected.*/

#toolMenu li a.selected{
	text-decoration: none;
	color: #6781a8;
	cursor: text;
	background:url(../images/pointer_tools.gif) no-repeat right;
	background-color:#fff;
	font-style: normal;
}

#toolMenu li a.selected:hover{
	text-decoration: none;
	color: #6781a8;
	cursor: text;
	font-weight: bold;
}

/*

#toolMenu li a.selected span{
	font-weight: bolder;
}

#toolMenu li .selectedTool {
	font-weight: bolder;
	background:url(../images/pointer_tools.gif) no-repeat right;
	background-color:#fff;
	cursor: text;
}

*/

#toolMenu li a.selected span{
	font-weight: bolder;
}

#toolMenu li.selectedTool {
	font-weight: bolder;
	background:url(../images/pointer_tools.gif) no-repeat right;
	background-color:#fff;
	cursor: text;
}

/*PART 6 - SITE AFFILIATION,SITE TYPE/STATUS AND PRESENCE - children of #toolMenuWrap	*/
/*site logo wrapper*/
#worksiteLogo{
	display: block;
	width: 0;
	height: 0;
	overflow: visible;
}

/*site logo image - Sakai may output,depending on installation,an image here based in site affiliation. Site owner may also point to a url - overriding the Sakai provided image*/
#worksiteLogo img{
	display: block;
	margin: .5em auto;
}

/*wrapper for the string that Sakai will output based on site type (ie. project,course) this is open ended and institution specific*/
#siteType{
	display: none;
}

/*wrapper for the string that Sakai will output based on site status when status is "Unpublished"*/
#siteStatus{
	position: absolute;
	top: -1px;
	left: 0;
	min-width: 150px;
	z-index: 1;
	height: 1.35em;
	text-transform: capitalize;
	text-align: center;
	color: white;
	background: #6F070D url(../images/err_btm_curve.gif) no-repeat 100% 100%;
	font-size: 1.1em;
	font-weight: bold;
	margin: 0;
	padding: 3px 12px 1px;
	white-space: nowrap;
}

/*wrapper for all elements of presence display */
#presenceWrapper{
	width: 9.65em;
	margin-top: .5em;
}

/*wrapper for title of iframe ("Users present")*/
#presenceTitle{
	font-size: .7em;
	text-align: right;
	margin-right: .5em;
}

/*of presence iframe*/
#presenceIframe{
	height: 100px;
	/*margin: .3em;*/
	width: 8.8em;
}

/*PART 7 - PORTLETS - children of #content*/
/*a page may display portlets in one column or two columns - the next three id selectors address the three possiblities - sole child of column is the .portlet */
#col1{
	padding-right: 1em;
}

#col1of2{
	width: 50%;
	float: left;
	margin: 0;
}

#col2of2{
	width: 49%;
	float: right;
}

/*wrapper class for portlets - decorative -  contains two wrapper block children:.portletTitleWrap and  .portletMainWrap*/
.portlet{
}

/*.portletTitleWrap are wrappers for the tool title documents,
below they are contextually defined depending on the column as an example,as you may want to adjust the widths accordingly*/
#col1 .portletTitleWrap{
	width: 99%;
	/*border-bottom: 2px solid #09c;*/
}

#col1 .portletMainWrap{
	width: 99%;
}

#col1of2 .portletTitleWrap,#col2of2 .portletTitleWrap{
	width: 98.5%;
	/*border-bottom: 2px solid #09c;*/
}

#col1of2 .portletMainWrap,#col2of2 .portletMainWrap{
	width: 98.5%;
	margin-bottom: 5em;
	/*margin-bottom: .5em;*/
}

.portletTitle{
	width: 100%;
	background: url(../images/top_left.gif) top left no-repeat;
	background-color: #264c83;
	height:24px;
	overflow:hidden;

}

.portletTitle .title img{

	width: 16px;
	height: 16px;
	border:none;
	line-height: 24px;
	vertical-align: middle;
}

.portletTitle .title{
	background: url(../images/top_right.gif) right top no-repeat;
	color: #000;
	height:24px;
	padding-left: .3em;
}

.portletTitle .title h2{

	padding: 1px;
	display: inline;
	color: #fff;
	font-weight: bold;
	font-size: 1.3em;
	vertical-align: middle;
	margin-left: .8em;
	line-height:24px;
}

.portletTitle .title a{

	padding: 2px;
	margin-left:1em;
	background: url(../images/reload.gif) center center no-repeat;
	vertical-align: middle;
	line-height: 24px;
}

.portletTitle .title a:hover{

	padding: 2px;
	margin-left:1em;
	background: url(../images/reload_h.gif) center center no-repeat;
	vertical-align: middle;
	line-height: 24px;

}

.portletTitle .action{

	text-align: right;
	width: 98.7%;
	margin-top:-24px;
	height:24px;
	padding-left: .4em;
}

.portletTitle .action img{

	margin-bottom: 6px;

	padding: 2px;
	width: 16px;
	height: 16px !important;
	border:none;
	vertical-align: middle;

}

.portletTitle .action a{
	margin-top: 6px;
	background: url(../images/help.gif) center center no-repeat;
	vertical-align: middle;
	line-height: 24px;
	padding: 2px;
	margin-left:1em;
}

.portletTitle .action a:hover{
	background: url(../images/help_h.gif) center center no-repeat;
	line-height: 24px;

}

.portletTitle .action a#jsr-edit{
        padding:2px;
        background: url(../images/page_edit.gif) center right no-repeat;
}

.portletTitle .action a#jsr-edit:hover{
        background: url(../images/page_edit.gif) center right no-repeat;
}

/*iframes for portlet title and portlet content*/
/*gone for 2.3
.portletTitleIframe{
	margin: 0;
	height: 1.8em;
	width: 100%;
}
*/
.portletMainIframe{
	text-align: left;
	margin-bottom: .5em;
	/*margin-top: 10em;*/
	height: auto;
	border: none;
}

/*PART 8 - FOOTER BLOCKS - descendants of #footer TODO - unpack the 3 descendants and make them all children*/
/*wrapper for links going to external sites - links are output as a series  separated via pipes (TODO:make a list already)*/
.footerExtNav{
	color: #eee;
	padding-top: .5em;
	padding-bottom: .5em;
	background: #274B82
}

/*the links displayed inside the wrapper above*/
.footerExtNav a,.footerExtNav A:link,.footerExtNav A:visited{
	color: #eee;
	text-decoration: none;
	margin: 1em;
}

.footerExtNav a:hover{
	color: #F2CE5E;
	text-decoration: underline;
	margin: 1em;
}

/*a second wrapper - server info,build,etc*/
#footerInfo{
	font-size: xx-small;
	text-align: center;
	clear: both;
	padding-bottom: 0;
}

#footerInfo img{
	margin-top: .4em;
	margin-bottom: .4em;
}

/*a third wrapper - reserved for copyright blurbs*/
.sakaiCopyrightInfo{
	color: #274B82;
}

/*PART 8 - CONVENIENCE*/
/*used to hide various blocks from sighted users that are in the source to help with accessibility*/
.skip{
	display: inline;
	position: absolute;
	top: -999px;
	left: -999px;
	height: 0;

}