text:
package sun.rmi.rmic;

import java.util.Vector;
import java.util.Hashtable;
import java.util.Enumeration;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.security.MessageDigest;
import java.security.DigestOutputStream;
import java.security.NoSuchAlgorithmException;
import sun.tools.java.Type;
import sun.tools.java.ClassDefinition;
import sun.tools.java.ClassDeclaration;
import sun.tools.java.MemberDefinition;
import sun.tools.java.Identifier;
import sun.tools.java.ClassNotFound;

/**
 * A RemoteClass object encapsulates RMI-specific information about
 * a remote implementation class, i.e. a class that implements
 * one or more remote interfaces.
 *
 * WARNING: The contents of this source file are not part of any
 * supported API.  Code that depends on them does so at its own risk:
 * they are subject to change or removal without notice.
 *
 * @author      Peter Jones
 */
public class RemoteClass implements sun.rmi.rmic.RMIConstants {

    /**
     * Create a RemoteClass object representing the remote meta-information
     * of the given class.
     *
     * Returns true if successful.  If the class is not a properly formed
     * remote implementation class or if some other error occurs, the
     * return value will be null, and errors will have been reported to
     * the supplied BatchEnvironment.
     */
    public static RemoteClass forClass(BatchEnvironment env,
                                       ClassDefinition implClassDef)
    {
        RemoteClass rc = new RemoteClass(env, implClassDef);
        if (rc.initialize()) {
            return rc;
        } else {
            return null;
        }
    }

    /**
     * Return the ClassDefinition for this class.
     */
    public ClassDefinition getClassDefinition() {
        return implClassDef;
    }

    /**
     * Return the name of the class represented by this object.
     */
    public Identifier getName() {
        return implClassDef.getName();
    }

    /**
     * Return an array of ClassDefinitions representing all of the remote
     * interfaces implemented by this class.
     *
     * A remote interface is any interface that extends Remote,
     * directly or indirectly.  The remote interfaces of a class
     * are the interfaces directly listed in either the class's
     * "implements" clause, or the "implements" clause of any
     * of its superclasses, that are remote interfaces.
     *
     * The order of the array returned is arbitrary, and some elements
     * may be superfluous (i.e., superinterfaces of other interfaces
     * in the array).
     */
    public ClassDefinition[] getRemoteInterfaces() {
        return remoteInterfaces.clone();
    }

    /**
     * Return an array of RemoteClass.Method objects representing all of
     * the remote methods implemented by this class, i.e. all of the
     * methods in the class's remote interfaces.
     *
     * The methods in the array are ordered according to the comparision
     * of the strings consisting of their method name followed by their
     * type signature, so each method's index in the array corresponds
     * to its "operation number" in the JDK 1.1 version of the
     * stub/skeleton protocol.
     */
    public Method[] getRemoteMethods() {
        return remoteMethods.clone();
    }

    /**
     * Return the "interface hash" used to match a stub/skeleton pair for
     * this class in the JDK 1.1 version of the stub/skeleton protocol.
     */
    public long getInterfaceHash() {
        return interfaceHash;
    }

    /**
     * Return string representation of this object, consisting of
     * the string "remote class " followed by the class name.
     */
    public String toString() {
        return "remote class " + implClassDef.getName().toString();
    }

    /** rmic environment for this object */
    private BatchEnvironment env;

    /** the remote implementation class this object corresponds to */
    private ClassDefinition implClassDef;

    /** remote interfaces implemented by this class */
    private ClassDefinition[] remoteInterfaces;

    /** all the remote methods of this class */
    private Method[] remoteMethods;

    /** stub/skeleton "interface hash" for this class */
    private long interfaceHash;

    /** cached definition for certain classes used in this environment */
    private ClassDefinition defRemote;
    private ClassDefinition defException;
    private ClassDefinition defRemoteException;

    /**
     * Create a RemoteClass instance for the given class.  The resulting
     * object is not yet initialized.
     */
    private RemoteClass(BatchEnvironment env, ClassDefinition implClassDef) {
        this.env = env;
        this.implClassDef = implClassDef;
    }

    /**
     * Validate that the remote implementation class is properly formed
     * and fill in the data structures required by the public interface.
     */
    private boolean initialize() {
        /*
         * Verify that the "impl" is really a class, not an interface.
         */
        if (implClassDef.isInterface()) {
            env.error(0, "rmic.cant.make.stubs.for.interface",
                      implClassDef.getName());
            return false;
        }

        /*
         * Initialize cached definitions for the Remote interface and
         * the RemoteException class.
         */
        try {
            defRemote =
                env.getClassDeclaration(idRemote).getClassDefinition(env);
            defException =
                env.getClassDeclaration(idJavaLangException).
                getClassDefinition(env);
            defRemoteException =
                env.getClassDeclaration(idRemoteException).
                getClassDefinition(env);
        } catch (ClassNotFound e) {
            env.error(0, "rmic.class.not.found", e.name);
            return false;
        }

        /*
         * Here we find all of the remote interfaces of our remote
         * implementation class.  For each class up the superclass
         * chain, add each directly-implemented interface that
         * somehow extends Remote to a list.
         */
        Vector<ClassDefinition> remotesImplemented = // list of remote interfaces found
            new Vector<ClassDefinition>();
        for (ClassDefinition classDef = implClassDef;
             classDef != null;)
            {
                try {
                    ClassDeclaration[] interfaces = classDef.getInterfaces();
                    for (int i = 0; i < interfaces.length; i++) {
                        ClassDefinition interfaceDef =
                            interfaces[i].getClassDefinition(env);
                        /*
                         * Add interface to the list if it extends Remote and
                         * it is not already there.
                         */
                        if (!remotesImplemented.contains(interfaceDef) &&
                            defRemote.implementedBy(env, interfaces[i]))
                            {
                                remotesImplemented.addElement(interfaceDef);
                                /***** <DEBUG> */
                                if (env.verbose()) {
                                    System.out.println("[found remote interface: " +
                                                       interfaceDef.getName() + "]");
                                    /***** </DEBUG> */
                                }
                            }
                    }

                    /*
                     * Verify that the candidate remote implementation class
                     * implements at least one remote interface directly.
                     */
                    if (classDef == implClassDef && remotesImplemented.isEmpty()) {
                        if (defRemote.implementedBy(env,
                                                    implClassDef.getClassDeclaration()))
                            {
                                /*
                                 * This error message is used if the class does
                                 * implement a remote interface through one of
                                 * its superclasses, but not directly.
                                 */
                                env.error(0, "rmic.must.implement.remote.directly",
                                          implClassDef.getName());
                            } else {
                                /*
                                 * This error message is used if the class never
                                 * implements a remote interface.
                                 */
                                env.error(0, "rmic.must.implement.remote",
                                          implClassDef.getName());
                            }
                        return false;
                    }

                    /*
                     * Get definition for next superclass.
                     */
                    classDef = (classDef.getSuperClass() != null ?
                                classDef.getSuperClass().getClassDefinition(env) :
                                null);

                } catch (ClassNotFound e) {
                    env.error(0, "class.not.found", e.name, classDef.getName());
                    return false;
                }
            }

        /*
         * The "remotesImplemented" vector now contains all of the remote
         * interfaces directly implemented by the remote class or by any
         * of its superclasses.
         *
         * At this point, we could optimize the list by removing superfluous
         * entries, i.e. any interfaces that are implemented by some other
         * interface in the list anyway.
         *
         * This should be correct; would it be worthwhile?
         *
         *      for (int i = 0; i < remotesImplemented.size();) {
         *          ClassDefinition interfaceDef =
         *              (ClassDefinition) remotesImplemented.elementAt(i);
         *          boolean isOtherwiseImplemented = false;
         *          for (int j = 0; j < remotesImplemented.size; j++) {
         *              if (j != i &&
         *                  interfaceDef.implementedBy(env, (ClassDefinition)
         *                  remotesImplemented.elementAt(j).
         *                      getClassDeclaration()))
         *              {
         *                  isOtherwiseImplemented = true;
         *                  break;
         *              }
         *          }
         *          if (isOtherwiseImplemented) {
         *              remotesImplemented.removeElementAt(i);
         *          } else {
         *              ++i;
         *          }
         *      }
         */

        /*
         * Now we collect the methods from all of the remote interfaces
         * into a hashtable.
         */
        Hashtable<String, Method> methods = new Hashtable<String, Method>();
        boolean errors = false;
        for (Enumeration<ClassDefinition> enumeration
                 = remotesImplemented.elements();
             enumeration.hasMoreElements();)
            {
                ClassDefinition interfaceDef = enumeration.nextElement();
                if (!collectRemoteMethods(interfaceDef, methods))
                    errors = true;
            }
        if (errors)
            return false;

        /*
         * Convert vector of remote interfaces to an array
         * (order is not important for this array).
         */
        remoteInterfaces = new ClassDefinition[remotesImplemented.size()];
        remotesImplemented.copyInto(remoteInterfaces);

        /*
         * Sort table of remote methods into an array.  The elements are
         * sorted in ascending order of the string of the method's name
         * and type signature, so that each elements index is equal to
         * its operation number of the JDK 1.1 version of the stub/skeleton
         * protocol.
         */
        String[] orderedKeys = new String[methods.size()];
        int count = 0;
        for (Enumeration<Method> enumeration = methods.elements();
             enumeration.hasMoreElements();)
            {
                Method m = enumeration.nextElement();
                String key = m.getNameAndDescriptor();
                int i;
                for (i = count; i > 0; --i) {
                    if (key.compareTo(orderedKeys[i - 1]) >= 0) {
                        break;
                    }
                    orderedKeys[i] = orderedKeys[i - 1];
                }
                orderedKeys[i] = key;
                ++count;
            }
        remoteMethods = new Method[methods.size()];
        for (int i = 0; i < remoteMethods.length; i++) {
            remoteMethods[i] = methods.get(orderedKeys[i]);
            /***** <DEBUG> */
            if (env.verbose()) {
                System.out.print("[found remote method <" + i + ">: " +
                                 remoteMethods[i].getOperationString());
                ClassDeclaration[] exceptions =
                    remoteMethods[i].getExceptions();
                if (exceptions.length > 0)
                    System.out.print(" throws ");
                for (int j = 0; j < exceptions.length; j++) {
                    if (j > 0)
                        System.out.print(", ");
                    System.out.print(exceptions[j].getName());
                }
                System.out.println("]");
            }
            /***** </DEBUG> */
        }

        /**
         * Finally, pre-compute the interface hash to be used by
         * stubs/skeletons for this remote class.
         */
        interfaceHash = computeInterfaceHash();

        return true;
    }

    /**
     * Collect and validate all methods from given interface and all of
     * its superinterfaces as remote methods.  Remote methods are added
     * to the supplied hashtable.  Returns true if successful,
     * or false if an error occurred.
     */
    private boolean collectRemoteMethods(ClassDefinition interfaceDef,
                                         Hashtable<String, Method> table)
    {
        if (!interfaceDef.isInterface()) {
            throw new Error(
                            "expected interface, not class: " + interfaceDef.getName());
        }

        /*
         * rmic used to enforce that a remote interface could not extend
         * a non-remote interface, i.e. an interface that did not itself
         * extend from Remote.  The current version of rmic does not have
         * this restriction, so the following code is now commented out.
         *
         * Verify that this interface extends Remote, since all interfaces
         * extended by a remote interface must implement Remote.
         *
         *      try {
         *          if (!defRemote.implementedBy(env,
         *              interfaceDef.getClassDeclaration()))
         *          {
         *              env.error(0, "rmic.can.mix.remote.nonremote",
         *                  interfaceDef.getName());
         *              return false;
         *          }
         *      } catch (ClassNotFound e) {
         *          env.error(0, "class.not.found", e.name,
         *              interfaceDef.getName());
         *          return false;
         *      }
         */

        boolean errors = false;

        /*
         * Search interface's members for methods.
         */
    nextMember:
        for (MemberDefinition member = interfaceDef.getFirstMember();
             member != null;
             member = member.getNextMember())
            {
                if (member.isMethod() &&
                    !member.isConstructor() && !member.isInitializer())
                    {
                        /*
                         * Verify that each method throws RemoteException.
                         */
                        ClassDeclaration[] exceptions = member.getExceptions(env);
                        boolean hasRemoteException = false;
                        for (int i = 0; i < exceptions.length; i++) {
                            /*
                             * rmic used to enforce that a remote method had to
                             * explicitly list RemoteException in its "throws"
                             * clause; i.e., just throwing Exception was not
                             * acceptable.  The current version of rmic does not
                             * have this restriction, so the following code is
                             * now commented out.  Instead, the method is
                             * considered valid if RemoteException is a subclass
                             * of any of the methods declared exceptions.
                             *
                             *  if (exceptions[i].getName().equals(
                             *      idRemoteException))
                             *  {
                             *      hasRemoteException = true;
                             *      break;
                             *  }
                             */
                            try {
                                if (defRemoteException.subClassOf(
                                                                  env, exceptions[i]))
                                    {
                                        hasRemoteException = true;
                                        break;
                                    }
                            } catch (ClassNotFound e) {
                                env.error(0, "class.not.found", e.name,
                                          interfaceDef.getName());
                                continue nextMember;
                            }
                        }
                        /*
                         * If this method did not throw RemoteException as required,
                         * generate the error but continue, so that multiple such
                         * errors can be reported.
                         */
                        if (!hasRemoteException) {
                            env.error(0, "rmic.must.throw.remoteexception",
                                      interfaceDef.getName(), member.toString());
                            errors = true;
                            continue nextMember;
                        }

                        /*
                         * Verify that the implementation of this method throws only
                         * java.lang.Exception or its subclasses (fix bugid 4092486).
                         * JRMP does not support remote methods throwing
                         * java.lang.Throwable or other subclasses.
                         */
                        try {
                            MemberDefinition implMethod = implClassDef.findMethod(
                                                                                env, member.getName(), member.getType());
                            if (implMethod != null) {           // should not be null
                                exceptions = implMethod.getExceptions(env);
                                for (int i = 0; i < exceptions.length; i++) {
                                    if (!defException.superClassOf(
                                                                   env, exceptions[i]))
                                        {
                                            env.error(0, "rmic.must.only.throw.exception",
                                                      implMethod.toString(),
                                                      exceptions[i].getName());
                                            errors = true;
                                            continue nextMember;
                                        }
                                }
                            }
                        } catch (ClassNotFound e) {
                            env.error(0, "class.not.found", e.name,
                                      implClassDef.getName());
                            continue nextMember;
                        }

                        /*
                         * Create RemoteClass.Method object to represent this method
                         * found in a remote interface.
                         */
                        Method newMethod = new Method(member);
                        /*
                         * Store remote method's representation in the table of
                         * remote methods found, keyed by its name and parameter
                         * signature.
                         *
                         * If the table already contains an entry with the same
                         * method name and parameter signature, then we must
                         * replace the old entry with a Method object that
                         * represents a legal combination of the old and the new
                         * methods; specifically, the combined method must have
                         * a throws list that contains (only) all of the checked
                         * exceptions that can be thrown by both the old or
                         * the new method (see bugid 4070653).
                         */
                        String key = newMethod.getNameAndDescriptor();
                        Method oldMethod = table.get(key);
                        if (oldMethod != null) {
                            newMethod = newMethod.mergeWith(oldMethod);
                            if (newMethod == null) {
                                errors = true;
                                continue nextMember;
                            }
                        }
                        table.put(key, newMethod);
                    }
            }

        /*
         * Recursively collect methods for all superinterfaces.
         */
        try {
            ClassDeclaration[] superDefs = interfaceDef.getInterfaces();
            for (int i = 0; i < superDefs.length; i++) {
                ClassDefinition superDef =
                    superDefs[i].getClassDefinition(env);
                if (!collectRemoteMethods(superDef, table))
                    errors = true;
            }
        } catch (ClassNotFound e) {
            env.error(0, "class.not.found", e.name, interfaceDef.getName());
            return false;
        }

        return !errors;
    }

    /**
     * Compute the "interface hash" of the stub/skeleton pair for this
     * remote implementation class.  This is the 64-bit value used to
     * enforce compatibility between a stub and a skeleton using the
     * JDK 1.1 version of the stub/skeleton protocol.
     *
     * It is calculated using the first 64 bits of a SHA digest.  The
     * digest is from a stream consisting of the following data:
     *     (int) stub version number, always 1
     *     for each remote method, in order of operation number:
     *         (UTF) method name
     *         (UTF) method type signature
     *         for each declared exception, in alphabetical name order:
     *             (UTF) name of exception class
     *
     */
    private long computeInterfaceHash() {
        long hash = 0;
        ByteArrayOutputStream sink = new ByteArrayOutputStream(512);
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            DataOutputStream out = new DataOutputStream(
                                                        new DigestOutputStream(sink, md));

            out.writeInt(INTERFACE_HASH_STUB_VERSION);
            for (int i = 0; i < remoteMethods.length; i++) {
                MemberDefinition m = remoteMethods[i].getMemberDefinition();
                Identifier name = m.getName();
                Type type = m.getType();

                out.writeUTF(name.toString());
                // type signatures already use mangled class names
                out.writeUTF(type.getTypeSignature());

                ClassDeclaration exceptions[] = m.getExceptions(env);
                sortClassDeclarations(exceptions);
                for (int j = 0; j < exceptions.length; j++) {
                    out.writeUTF(Names.mangleClass(
                                                   exceptions[j].getName()).toString());
                }
            }
            out.flush();

            // use only the first 64 bits of the digest for the hash
            byte hashArray[] = md.digest();
            for (int i = 0; i < Math.min(8, hashArray.length); i++) {
                hash += ((long) (hashArray[i] & 0xFF)) << (i * 8);
            }
        } catch (IOException e) {
            throw new Error(
                            "unexpected exception computing intetrface hash: " + e);
        } catch (NoSuchAlgorithmException e) {
            throw new Error(
                            "unexpected exception computing intetrface hash: " + e);
        }

        return hash;
    }

    /**
     * Sort array of class declarations alphabetically by their mangled
     * fully-qualified class name.  This is used to feed a method's exceptions
     * in a canonical order into the digest stream for the interface hash
     * computation.
     */
    private void sortClassDeclarations(ClassDeclaration[] decl) {
        for (int i = 1; i < decl.length; i++) {
            ClassDeclaration curr = decl[i];
            String name = Names.mangleClass(curr.getName()).toString();
            int j;
            for (j = i; j > 0; j--) {
                if (name.compareTo(
                                   Names.mangleClass(decl[j - 1].getName()).toString()) >= 0)
                    {
                        break;
                    }
                decl[j] = decl[j - 1];
            }
            decl[j] = curr;
        }
    }

    /**
     * A RemoteClass.Method object encapsulates RMI-specific information
     * about a particular remote method in the remote implementation class
     * represented by the outer instance.
     */
    public class Method implements Cloneable {

        /**
         * Return the definition of the actual class member corresponing
         * to this method of a remote interface.
         *
         * REMIND: Can this method be removed?
         */
        public MemberDefinition getMemberDefinition() {
            return memberDef;
        }

        /**
         * Return the name of this method.
         */
        public Identifier getName() {
            return memberDef.getName();
        }

        /**
         * Return the type of this method.
         */
        public Type getType() {
            return memberDef.getType();
        }

        /**
         * Return an array of the exception classes declared to be
         * thrown by this remote method.
         *
         * For methods with the same name and type signature inherited
         * from multiple remote interfaces, the array will contain
         * the set of exceptions declared in all of the interfaces'
         * methods that can be legally thrown in each of them.
         */
        public ClassDeclaration[] getExceptions() {
            return exceptions.clone();
        }

        /**
         * Return the "method hash" used to identify this remote method
         * in the JDK 1.2 version of the stub protocol.
         */
        public long getMethodHash() {
            return methodHash;
        }

        /**
         * Return the string representation of this method.
         */
        public String toString() {
            return memberDef.toString();
        }

        /**
         * Return the string representation of this method appropriate
         * for the construction of a java.rmi.server.Operation object.
         */
        public String getOperationString() {
            return memberDef.toString();
        }

        /**
         * Return a string consisting of this method's name followed by
         * its method descriptor, using the Java VM's notation for
         * method descriptors (see section 4.3.3 of The Java Virtual
         * Machine Specification).
         */
        public String getNameAndDescriptor() {
            return memberDef.getName().toString() +
                memberDef.getType().getTypeSignature();
        }

        /**
         * Member definition for this method, from one of the remote
         * interfaces that this method was found in.
         *
         * Note that this member definition may be only one of several
         * member defintions that correspond to this remote method object,
         * if several of this class's remote interfaces contain methods
         * with the same name and type signature.  Therefore, this member
         * definition may declare more exceptions thrown that this remote
         * method does.
         */
        private MemberDefinition memberDef;

        /** stub "method hash" to identify this method */
        private long methodHash;

        /**
         * Exceptions declared to be thrown by this remote method.
         *
         * This list can include superfluous entries, such as
         * unchecked exceptions and subclasses of other entries.
         */
        private ClassDeclaration[] exceptions;

        /**
         * Create a new Method object corresponding to the given
         * method definition.
         */
        /*
         * Temporarily comment out the private modifier until
         * the VM allows outer class to access inner class's
         * private constructor
         */
        /* private */ Method(MemberDefinition memberDef) {
            this.memberDef = memberDef;
            exceptions = memberDef.getExceptions(env);
            methodHash = computeMethodHash();
        }

        /**
         * Cloning is supported by returning a shallow copy of this object.
         */
        protected Object clone() {
            try {
                return super.clone();
            } catch (CloneNotSupportedException e) {
                throw new Error("clone failed");
            }
        }

        /**
         * Return a new Method object that is a legal combination of
         * this method object and another one.
         *
         * This requires determining the exceptions declared by the
         * combined method, which must be (only) all of the exceptions
         * declared in both old Methods that may thrown in either of
         * them.
         */
        private Method mergeWith(Method other) {
            if (!getName().equals(other.getName()) ||
                !getType().equals(other.getType()))
                {
                    throw new Error("attempt to merge method \"" +
                                    other.getNameAndDescriptor() + "\" with \"" +
                                    getNameAndDescriptor());
                }

            Vector<ClassDeclaration> legalExceptions
                = new Vector<ClassDeclaration>();
            try {
                collectCompatibleExceptions(
                                            other.exceptions, exceptions, legalExceptions);
                collectCompatibleExceptions(
                                            exceptions, other.exceptions, legalExceptions);
            } catch (ClassNotFound e) {
                env.error(0, "class.not.found", e.name,
                          getClassDefinition().getName());
                return null;
            }

            Method merged = (Method) clone();
            merged.exceptions = new ClassDeclaration[legalExceptions.size()];
            legalExceptions.copyInto(merged.exceptions);

            return merged;
        }

        /**
         * Add to the supplied list all exceptions in the "from" array
         * that are subclasses of an exception in the "with" array.
         */
        private void collectCompatibleExceptions(ClassDeclaration[] from,
                                                 ClassDeclaration[] with,
                                                 Vector<ClassDeclaration> list)
            throws ClassNotFound
        {
            for (int i = 0; i < from.length; i++) {
                ClassDefinition exceptionDef = from[i].getClassDefinition(env);
                if (!list.contains(from[i])) {
                    for (int j = 0; j < with.length; j++) {
                        if (exceptionDef.subClassOf(env, with[j])) {
                            list.addElement(from[i]);
                            break;
                        }
                    }
                }
            }
        }

        /**
         * Compute the "method hash" of this remote method.  The method
         * hash is a long containing the first 64 bits of the SHA digest
         * from the UTF encoded string of the method name and descriptor.
         *
         * REMIND: Should this method share implementation code with
         * the outer class's computeInterfaceHash() method?
         */
        private long computeMethodHash() {
            long hash = 0;
            ByteArrayOutputStream sink = new ByteArrayOutputStream(512);
            try {
                MessageDigest md = MessageDigest.getInstance("SHA");
                DataOutputStream out = new DataOutputStream(
                                                            new DigestOutputStream(sink, md));

                String methodString = getNameAndDescriptor();
                /***** <DEBUG> */
                if (env.verbose()) {
                    System.out.println("[string used for method hash: \"" +
                                       methodString + "\"]");
                }
                /***** </DEBUG> */
                out.writeUTF(methodString);

                // use only the first 64 bits of the digest for the hash
                out.flush();
                byte hashArray[] = md.digest();
                for (int i = 0; i < Math.min(8, hashArray.length); i++) {
                    hash += ((long) (hashArray[i] & 0xFF)) << (i * 8);
                }
            } catch (IOException e) {
                throw new Error(
                                "unexpected exception computing intetrface hash: " + e);
            } catch (NoSuchAlgorithmException e) {
                throw new Error(
                                "unexpected exception computing intetrface hash: " + e);
            }

            return hash;
        }
    }
}


text:
import "./heightSettingsPanel.component.scss"

import { Component, Inject } from "@angular/core"
import { Store } from "../../../state/angular-redux/store"
import { amountOfTopLabelsSelector } from "../../../state/store/appSettings/amountOfTopLabels/amountOfTopLabels.selector"
import { isLabelsSliderDisabledSelector } from "./selectors/isLabelsSliderDisabled.selector"
import { debounce } from "lodash"
import { setAmountOfTopLabels } from "../../../state/store/appSettings/amountOfTopLabels/amountOfTopLabels.actions"
import { showMetricLabelNodeNameSelector } from "../../../state/store/appSettings/showMetricLabelNodeName/showMetricLabelNodeName.selector"
import { showMetricLabelNodeValueSelector } from "../../../state/store/appSettings/showMetricLabelNameValue/showMetricLabelNameValue.selector"
import { MatCheckboxChange } from "@angular/material/checkbox"
import { setShowMetricLabelNodeName } from "../../../state/store/appSettings/showMetricLabelNodeName/showMetricLabelNodeName.actions"
import { setShowMetricLabelNameValue } from "../../../state/store/appSettings/showMetricLabelNameValue/showMetricLabelNameValue.actions"
import { scalingSelector } from "../../../state/store/appSettings/scaling/scaling.selector"
import { setScaling } from "../../../state/store/appSettings/scaling/scaling.actions"
import { invertHeightSelector } from "../../../state/store/appSettings/invertHeight/invertHeight.selector"
import { setInvertHeight } from "../../../state/store/appSettings/invertHeight/invertHeight.actions"
import { isDeltaStateSelector } from "../../../state/selectors/isDeltaState.selector"

@Component({
	selector: "cc-height-settings-panel",
	template: require("./heightSettingsPanel.component.html")
})
export class HeightSettingsPanelComponent {
	static DEBOUNCE_TIME = 400

	amountOfTopLabels$ = this.store.select(amountOfTopLabelsSelector)
	isLabelsSliderDisabled$ = this.store.select(isLabelsSliderDisabledSelector)
	showMetricLabelNodeName$ = this.store.select(showMetricLabelNodeNameSelector)
	showMetricLabelNodeValue$ = this.store.select(showMetricLabelNodeValueSelector)
	scaling$ = this.store.select(scalingSelector)
	invertHeight$ = this.store.select(invertHeightSelector)
	isDeltaState$ = this.store.select(isDeltaStateSelector)

	constructor(@Inject(Store) private store: Store) {}

	applyDebouncedTopLabels = debounce((amountOfTopLabels: number) => {
		this.store.dispatch(setAmountOfTopLabels(amountOfTopLabels))
	}, HeightSettingsPanelComponent.DEBOUNCE_TIME)

	applyDebouncedScalingY = debounce((y: number) => {
		this.store.dispatch(setScaling({ y }))
	}, HeightSettingsPanelComponent.DEBOUNCE_TIME)

	setShowMetricLabelNodeName(event: MatCheckboxChange) {
		this.store.dispatch(setShowMetricLabelNodeName(event.checked))
	}

	setShowMetricLabelNameValue(event: MatCheckboxChange) {
		this.store.dispatch(setShowMetricLabelNameValue(event.checked))
	}

	setInvertHeight(event: MatCheckboxChange) {
		this.store.dispatch(setInvertHeight(event.checked))
	}
}

redpajama_set_name: RedPajamaGithub


text:
package castalia.matcher

import akka.actor._
import akka.http.scaladsl.model.HttpRequest
import castalia.matcher.MatcherActor.TryMatch
import castalia.matcher.RequestMatcherActor.{AddMatcher, FindMatch}
import castalia.matcher.types._

object RequestMatcherActor {

  case class FindMatch(httpRequest: HttpRequest, origin: ActorRef)

  case class AddMatcher(segments: Segments, handler: ActorRef)

  def props(): Props = Props(new RequestMatcherActor with RequestMatcherActorCreatorImplementation)
}

class RequestMatcherActor extends Actor with ActorLogging {
  this: RequestMatcherActorCreator =>

  def receive: Receive = normal(Map.empty[Segments, ActorRef])

  def normal(matchers: Map[Segments, ActorRef]): Receive = {
    // Add matcher. If there is already a matcher with the same segments, stop that and replace with new one
    case AddMatcher(segments, handler) =>
      val matcher = createRequestMatcherActor(context, segments, handler)
      log.debug(s"Added matcher $matcher to RequestMatcherActor ${self.toString()}")
      val matcherOnSameSegments = matchers.get(segments)
      matcherOnSameSegments.foreach { matcherRef => context.stop(matcherRef) }
      val newSetOfMatchers = matchers.updated(segments, matcher)
      context.become(normal(newSetOfMatchers))

    // Foward match request to all registered matchers. Create result gatherer to gather and handle results
    case FindMatch(httpRequest, origin) =>
      val parsedUri = new ParsedUri(httpRequest.uri.toString().replace(';', '&'), httpRequest.uri.path, httpRequest.uri.query().toList)
      log.debug(s"RequestMatcherActor received http request $parsedUri from $sender")
      val gatherer = context.actorOf(MatchResultGatherer.props(matchers.size, origin))
      matchers.foreach{case (segments, matcher) => {
        log.debug(s"sending to ${matcher} ${TryMatch(parsedUri, httpRequest, gatherer)}")
        matcher ! TryMatch(parsedUri, httpRequest, gatherer)
      }}

    // unexpected messages
    case x =>
      log.info("RequestMatcherActor received unexpected message: " + x.toString)
  }
}

/**
  * This trait allows us to inject test probes
  */
trait RequestMatcherActorCreator {
  def createRequestMatcherActor(context: ActorContext, segments: Segments, handler: ActorRef): ActorRef
}

trait RequestMatcherActorCreatorImplementation extends RequestMatcherActorCreator {
  def createRequestMatcherActor(context: ActorContext, segments: Segments, handler: ActorRef): ActorRef = {
    context.actorOf(MatcherActor.props(segments, handler))
  }
}


text:
@protocol IO2GOrderResponseReader <IAddRef>
    - (NSString*) getOrderID;
    - (BOOL) isUnderDealerIntervention;
@end


text:
require_relative "library"
require "yaml"

module Franklin
  class Config
    DEFAULT_CONFIG_FILE = File.join(Dir.home, ".franklin").freeze
    attr_reader :libraries, :default_type

    def initialize(data)
      @libraries = data.fetch("libraries").map { |library|
        Library.new(library.fetch("name"), library.fetch("url"))
      }
      @default_type = data["default_type"]
    end

    class << self
      def from_yaml(yaml)
        new(YAML.safe_load(yaml))
      end

      def load_from_file(file_path = nil)
        from_yaml(File.read(file_path || DEFAULT_CONFIG_FILE))
      end
    end
  end
end


text:
ACCEPTED

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

#### Published in
in C. F. P. Martius

#### Original name
null

### Remarks
null


text:
package org.nuxeo.common.utils;

import java.io.Serializable;
import java.util.Arrays;

import javax.transaction.xa.Xid;

/**
 * A Serializable {@link Xid} independent of the transaction manager
 * implementation.
 */
public class XidImpl implements Xid, Serializable {

    private static final long serialVersionUID = 1L;

    public final int fid;

    public final byte[] gtrid;

    public final byte[] bqual;

    /**
     * Copy constructor.
     *
     * @param xid the xid to copy
     */
    public XidImpl(Xid xid) {
        fid = xid.getFormatId();
        gtrid = xid.getGlobalTransactionId().clone();
        bqual = xid.getBranchQualifier().clone();
    }

    /**
     * Constructor mostly used in unit tests.
     *
     * @param id the global transaction id
     */
    public XidImpl(String id) {
        fid = 0;
        gtrid = id.getBytes();
        // MySQL JDBC driver needs a non 0-length branch qualifier
        bqual = new byte[] { 0 };
    }

    public int getFormatId() {
        return fid;
    }

    public byte[] getGlobalTransactionId() {
        return gtrid.clone();
    }

    public byte[] getBranchQualifier() {
        return bqual.clone();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hash = 1;
        hash = prime * hash + fid;
        hash = prime * hash + Arrays.hashCode(gtrid);
        hash = prime * hash + Arrays.hashCode(bqual);
        return hash;
    }

    @Override
    public boolean equals(Object other) {
        if (!(other instanceof XidImpl)) {
            return false;
        }
        return equals((XidImpl) other);
    }

    private boolean equals(XidImpl other) {
        if (other == this) {
            return true;
        }
        return fid == other.fid && Arrays.equals(gtrid, other.gtrid)
                && Arrays.equals(bqual, other.bqual);
    }

}


text:
<?php

declare(strict_types = 1);

use PHPUnit\Framework\TestCase;
use Sop\JWX\JWA\JWA;
use Sop\JWX\JWS\Algorithm\HMACAlgorithm;
use Sop\JWX\JWS\Algorithm\HS512Algorithm;
use Sop\JWX\JWS\SignatureAlgorithm;
use Sop\JWX\JWT\Parameter\AlgorithmParameterValue;

/**
 * @group jws
 * @group hmac
 *
 * @internal
 */
class HS512Test extends TestCase
{
    public const KEY = '12345678';

    public const DATA = 'CONTENT';

    public function testCreate()
    {
        $algo = new HS512Algorithm(self::KEY);
        $this->assertInstanceOf(HMACAlgorithm::class, $algo);
        return $algo;
    }

    /**
     * @depends testCreate
     */
    public function testAlgoParamValue(AlgorithmParameterValue $algo)
    {
        $this->assertEquals(JWA::ALGO_HS512, $algo->algorithmParamValue());
    }

    /**
     * @depends testCreate
     */
    public function testSign(SignatureAlgorithm $algo)
    {
        $sig = $algo->computeSignature(self::DATA);
        $this->assertEquals(64, strlen($sig));
        return $sig;
    }

    /**
     * @depends testCreate
     * @depends testSign
     *
     * @param string $signature
     */
    public function testValidate(SignatureAlgorithm $algo, $signature)
    {
        $this->assertTrue($algo->validateSignature(self::DATA, $signature));
    }
}


text:
module WorkDecoratorCommon
  extend ActiveSupport::Concern

  included do
    def to_values
      model.class::DIFF_FIELDS.inject({}) do |hash, field|
        hash[field] = case field
        when :season_id
          if send(:season_id).present?
            Season.find(send(:season_id)).decorate.yearly_season_ja
          end
        when :sc_tid
          sc_tid = send(:sc_tid)
          if sc_tid.present?
            url = "http://cal.syoboi.jp/tid/#{sc_tid}"
            h.link_to(sc_tid, url, target: "_blank")
          end
        when :media
          Work.media.find_value(send(:media)).text
        when :official_site_url, :wikipedia_url
          url = send(field)
          if url.present?
            h.link_to(URI.decode(url), url, target: "_blank") rescue url
          end
        when :twitter_username
          username = send(:twitter_username)
          if username.present?
            url = "https://twitter.com/#{username}"
            h.link_to("@#{username}", url, target: "_blank")
          end
        when :twitter_hashtag
          hashtag = send(:twitter_hashtag)
          if hashtag.present?
            url = "https://twitter.com/search?q=%23#{hashtag}"
            h.link_to("##{hashtag}", url, target: "_blank")
          end
        when :number_format_id
          send(:number_format).name if send(:number_format_id).present?
        else
          send(field)
        end

        hash
      end
    end
  end
end


text:
import { forwardRef } from "react";

import { FontIcon, FontIconProps } from "@react-md/icon";

export const HdrOffFontIcon = forwardRef<HTMLElement, FontIconProps>(
  function HdrOffFontIcon(props, ref) {
    return (
      <FontIcon {...props} ref={ref}>
        hdr_off
      </FontIcon>
    );
  }
);


text:
(function() {
  'use strict';

  var PIXI = require('pixi.js'),
      Rock = require('./rock');

  function Main() {
    PIXI.DisplayObjectContainer.call(this);
    this.width = FP.getWidth();
    this.height = FP.getHeight();
    this.addRocks();
  }

  Main.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
  Main.prototype.constructor = Main;

  Main.prototype.update = function() {
    if(FP.GAME_OVER) return;
    this.children.forEach(function(child) { child.update(); });
  };

  Main.prototype.addRocks = function() {
    var texture, yPlacement, posX, rock, height_delta;
    var availableRocks = ['', 'Snow', 'Grass'];
    var randomRock = availableRocks[Math.floor(Math.random() * 3)];
    var textureUp = PIXI.Texture.fromFrame(FP.LANDSCAPE_PATH + 'rock' + randomRock + '.png');
    var textureDown = PIXI.Texture.fromFrame(FP.LANDSCAPE_PATH + 'rock' + randomRock + 'Down.png');
    for(var i = 0; i < FP.NUMBER_OF_ROCKS; i += 1) {
      if(i === 0 || i === 2) {
        height_delta = 30;
        texture = textureUp;
        yPlacement = 'bottom';
      }
      if (i === 1 || i === 3) {
        height_delta = 60;
        texture = textureDown;
        yPlacement = 'top';
      }
      posX = FP.getWidth() + (FP.NUMBER_OF_ROCKS - i) * (FP.ROCK_DISTANCE + texture.width);
      rock = new Rock(texture, posX, yPlacement, height_delta);
      FP.PLANE_OBSTICLES.push(rock);
      this.addChild(rock);
    }
  };

  module.exports = Main;

})();


text:
const int = score => parseInt(score, 10) || 0;

const stats = ["str", "dex", "con", "wis", "int", "cha"];
const skillslist = ["acrobatics", "animalhandling", "athletics", "culture", "deception", "engineering", "history", "insight", "intimidation", "investigation", "medicine", "nature", "perception", "performance", "persuasion", "pilot", "science", "sleight", "stealth", "survival"];
const statmods = ["str_mod", "dex_mod", "con_mod", "wis_mod", "int_mod", "cha_mod", "prof"];

// tabs

const buttonlist = ["character","background","settings"];
buttonlist.forEach(button => {
    on(`clicked:${button}`, function() {
        setAttrs({
            sheetTab: button
        });
    });
});

// Calculate Stat modifier

stats.forEach(stat => {
    on(`change:${stat}`, () => {
        getAttrs([stat], values => {
            const stat_base = int(values[stat]);
            console.log("stat changed");
            console.log(stat_base);
            let stat_mod = 0;
            if (stat_base >= 30) stat_mod = "+10";
            else if (stat_base >= 28) stat_mod = "+9";
            else if (stat_base >= 26) stat_mod = "+8";
            else if (stat_base >= 24) stat_mod = "+7";
            else if (stat_base >= 22) stat_mod = "+6";
            else if (stat_base >= 20) stat_mod = "+5";
            else if (stat_base >= 18) stat_mod = "+4";
            else if (stat_base >= 16) stat_mod = "+3";
            else if (stat_base >= 14) stat_mod = "+2";
            else if (stat_base >= 12) stat_mod = "+1";
            else if (stat_base >= 10) stat_mod = "+0";
            else if (stat_base >= 8) stat_mod = "-1";
            else if (stat_base >= 6) stat_mod = "-2";
            else if (stat_base >= 4) stat_mod = "-3";
            else if (stat_base >= 2) stat_mod = "-4";
            else if (stat_base <= 1) stat_mod = "-5";
            else stat_mod = "+0";

            setAttrs({
                [`${stat}_mod`]: stat_mod
            });
        });
    });
});

// skill prof check/uncheck

skillslist.forEach(skillcheckbox => {
    on(`change:${skillcheckbox}_c`, (eventInfo) => {
        console.log("skill prof toggle");
        console.log(skillcheckbox);
        let xbox = skillcheckbox + "_c";

        console.log("xbox defined");
        console.log("xbox is " + xbox);

        let getlist = [ xbox, "acrobatics", "animalhandling", "athletics", "culture", "deception", "engineering", "history", "insight", "intimidation", "investigation", "medicine", "nature", "perception", "performance", "persuasion", "pilot", "science", "sleight", "stealth", "survival", "acrobatics_c", "animalhandling_c", "athletics_c", "culture_c", "deception_c", "engineering_c", "history_c", "insight_c", "intimidation_c", "investigation_c", "medicine_c", "nature_c", "perception_c", "performance_c", "persuasion_c", "pilot_c", "science_c", "sleight_c", "stealth_c", "survival_c", "prof"];
        console.log("def getlist");

        getAttrs(getlist, values => {
            console.log("getatt done");
            let checkbox = int(values[xbox]);
            let skillnow = int(values[skillcheckbox]);
            let profval = int(values["prof"]);
            let skillnew = 0;
            console.log("checkbox " + checkbox + "skillnow " + skillnow);

            if (checkbox === 1){
                skillnew = skillnow + profval;
            }
            else{
               skillnew = skillnow - profval;
            }
            console.log("skillew " + skillnew);

            setAttrs({
                [`${skillcheckbox}`]: skillnew
            });
            console.log("setAttr done");
        });
    });
});

// save prof check/uncheck

stats.forEach(savecheckbox => {
    on(`change:${savecheckbox}_save_c`, (eventInfo) => {
        console.log("save prof toggle");
        console.log(savecheckbox);
        let xbox = savecheckbox + "_save_c";

        console.log("xbox defined");
        console.log("xbox is " + xbox);

        let getlist = [ xbox, "str_save", "dex_save", "con_save", "wis_save", "int_save", "cha_save","str_save_c", "dex_save_c", "con_save_c", "wis_save_c", "int_save_c", "cha_save_c", "prof"];
        console.log("def getlist");

        getAttrs(getlist, values => {
            console.log("getatt done");
            let checkbox = int(values[xbox]);
            let savenow = int(values[`${savecheckbox}_save`]);
            let profval = int(values["prof"]);
            let savenew = 0;
            console.log("checkbox " + checkbox + "savenow " + savenow);

            if (checkbox === 1){
                savenew = savenow + profval;
            }
            else{
               savenew = savenow - profval;
            }
            console.log("skillew " + savenew);

            setAttrs({
                [`${savecheckbox}_save`]: savenew
            });
            console.log("setAttr done");
        });
    });
});

// proficiency changed, updates skills/saves

on(`change:prof`, eventInfo => {
    console.log("prof change");
    let profold = int(eventInfo.previousValue);
    console.log("eventinfo: " + eventInfo.previousValue);
    let getlist = ["acrobatics", "animalhandling", "athletics", "culture", "deception", "engineering", "history", "insight", "intimidation", "investigation", "medicine", "nature", "perception", "performance", "persuasion", "pilot", "science", "sleight", "stealth", "survival", "acrobatics_c", "animalhandling_c", "athletics_c", "culture_c", "deception_c", "engineering_c", "history_c", "insight_c", "intimidation_c", "investigation_c", "medicine_c", "nature_c", "perception_c", "performance_c", "persuasion_c", "pilot_c", "science_c", "sleight_c", "stealth_c", "survival_c", "str_save", "dex_save", "con_save", "wis_save", "int_save", "cha_save","str_save_c", "dex_save_c", "con_save_c", "wis_save_c", "int_save_c", "cha_save_c", "prof", "determination", "determination_max"];

    getAttrs(getlist, values => {

        var update = {};
        let profnew = int(values["prof"]);
        let profdiff = profnew - profold;
        let determination = int(values["determination"]) + profdiff;
        let determination_max = int(values["determination_max"]) + profdiff;

        //manual fix for when you change proficiency for first time
        if (profnew === 3 && profold ===3)( profdiff = 1);

        determination = int(values["determination"]) + profdiff;
        determination_max = int(values["determination_max"]) + profdiff;
        update["determination"] = determination;
        console.log("det worked");
        update["determination_max"] = determination_max;
        console.log("det max worked");

        console.log("profold:" + profold + " profnew:" + profnew + " proffdiff: " + profdiff);

        let xboxlist = ["acrobatics", "animalhandling", "athletics", "culture", "deception", "engineering", "history", "insight", "intimidation", "investigation", "medicine", "nature", "perception", "performance", "persuasion", "pilot", "science", "sleight", "stealth", "survival","str_save", "dex_save", "con_save", "wis_save", "int_save", "cha_save"];

        xboxlist.forEach(number => {

            let checkbox = int(values[`${number}_c`]);

            if (checkbox === 1) {
                let oldval = int(values[`${number}`]);
                let newval = oldval + profdiff;

                update[number] = newval;
            }

        });

        console.log(update);

        setAttrs(update);

    });
});

// update skills & saves when attr mod changes

statmods.forEach(statmod => {
    on(`change:${statmod}`, eventInfo => {
        console.log("attr mod change");
        console.log("old mod: " + eventInfo.previousValue);
        let temp = eventInfo.previousValue;
        if (temp === undefined){
            temp = 0;
        }else{
            temp = temp.replace('+', '');
        }

        let oldstatmod = int(temp);

        console.log("old mod: " + oldstatmod);

        let getlist = ["str_mod", "dex_mod", "con_mod", "wis_mod", "int_mod", "cha_mod", "acrobatics", "animalhandling", "athletics", "culture", "deception", "engineering", "history", "insight", "intimidation", "investigation", "medicine", "nature", "perception", "performance", "persuasion", "pilot", "science", "sleight", "stealth", "survival", "str_save", "dex_save", "con_save", "wis_save", "int_save", "cha_save", "prof", "init", "moxie", "ac", "ac_extra", "determination","determination_max"];

        getAttrs(getlist, values => {

            var update = {};

            let modnew = int(values[`${statmod}`]);
            let moddiff = modnew - oldstatmod;

            switch (`${statmod}`) {
                case "str_mod":
                    console.log("oldstatmod: " + oldstatmod + " modnew:" + modnew + " moddiff: " + moddiff);
                    update["athletics"] = int(values["athletics"]) + moddiff;
                    update["str_save"] = int(values["str_save"]) + moddiff;
                    update["bulk"] = 8 + modnew;

                    setAttrs(update);
                    break;
                case "con_mod":
                    //let modnew = int(values[`${statmod}`]);
                    //let moddiff = modnew - oldstatmod;
                    update["con_save"] = int(values["con_save"]) + moddiff;

                    setAttrs(update);
                    break;
                case "dex_mod":
                    update["acrobatics"] = int(values["acrobatics"]) + moddiff;
                    update["pilot"] = int(values["pilot"]) + moddiff;
                    update["sleight"] = int(values["sleight"]) + moddiff;
                    update["stealth"] = int(values["stealth"]) + moddiff;
                    update["ac"] = int(values["ac"]) + moddiff;
                    update["ac_extra"] = int(values["ac_extra"]) + moddiff;
                    update["init"] = int(values["init"]) + moddiff;
                    update["dex_save"] = int(values["dex_save"]) + moddiff;

                    setAttrs(update);
                    break;
                case "int_mod":
                    update["engineering"] = int(values["engineering"]) + moddiff;
                    update["history"] = int(values["history"]) + moddiff;
                    update["investigation"] = int(values["investigation"]) + moddiff;
                    update["nature"] = int(values["nature"]) + moddiff;
                    update["science"] = int(values["science"]) + moddiff;
                    update["int_save"] = int(values["int_save"]) + moddiff;

                    setAttrs(update);
                    break;
                case "wis_mod":
                    update["animalhandling"] = int(values["animalhandling"]) + moddiff;
                    update["culture"] = int(values["culture"]) + moddiff;
                    update["insight"] = int(values["insight"]) + moddiff;
                    update["medicine"] = int(values["medicine"]) + moddiff;
                    update["perception"] = int(values["perception"]) + moddiff;
                    update["survival"] = int(values["survival"]) + moddiff;
                    update["wis_save"] = int(values["wis_save"]) + moddiff;

                    setAttrs(update);
                    break;
                case "cha_mod":
                    update["deception"] = int(values["deception"]) + moddiff;
                    update["intimidation"] = int(values["intimidation"]) + moddiff;
                    update["performance"] = int(values["performance"]) + moddiff;
                    update["persuasion"] = int(values["persuasion"]) + moddiff;
                    update["moxie"] = int(values["moxie"]) + moddiff;
                    update["cha_save"] = int(values["cha_save"]) + moddiff;

                    setAttrs(update);
                    break;
                default:
                    false;
            }
            console.log(update);

        });
    });
});


text:
package com.google.common.collect;

import com.google.common.annotations.GwtCompatible;

import java.util.Collection;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;

import javax.annotation.Nullable;

/**
 * A {@code SetMultimap} whose set of values for a given key are kept sorted;
 * that is, they comprise a {@link SortedSet}. It cannot hold duplicate
 * key-value pairs; adding a key-value pair that's already in the multimap has
 * no effect. This interface does not specify the ordering of the multimap's
 * keys.
 *
 *
The {@link #get}, {@link #removeAll}, and {@link #replaceValues} methods
 * each return a {@link SortedSet} of values, while {@link Multimap#entries()}
 * returns a {@link Set} of map entries. Though the method signature doesn't say
 * so explicitly, the map returned by {@link #asMap} has {@code SortedSet}
 * values.
 *
 * @author Jared Levy
 * @since 2010.01.04 stable (imported from Google Collections Library)
 */
@GwtCompatible
public interface SortedSetMultimap<K, V> extends SetMultimap<K, V> {
  /**
   * Returns a collection view of all values associated with a key. If no
   * mappings in the multimap have the provided key, an empty collection is
   * returned.
   *
   *
Changes to the returned collection will update the underlying multimap,
   * and vice versa.
   *
   *
Because a {@code SortedSetMultimap} has unique sorted values for a given
   * key, this method returns a {@link SortedSet}, instead of the
   * {@link java.util.Collection} specified in the {@link Multimap} interface.
   */
  SortedSet<V> get(@Nullable K key);

  /**
   * Removes all values associated with a given key.
   *
   *
Because a {@code SortedSetMultimap} has unique sorted values for a given
   * key, this method returns a {@link SortedSet}, instead of the
   * {@link java.util.Collection} specified in the {@link Multimap} interface.
   */
  SortedSet<V> removeAll(@Nullable Object key);

  /**
   * Stores a collection of values with the same key, replacing any existing
   * values for that key.
   *
   *
Because a {@code SortedSetMultimap} has unique sorted values for a given
   * key, this method returns a {@link SortedSet}, instead of the
   * {@link java.util.Collection} specified in the {@link Multimap} interface.
   *
   *
Any duplicates in {@code values} will be stored in the multimap once.
   */
  SortedSet<V> replaceValues(K key, Iterable<? extends V> values);

  /**
   * Returns a map view that associates each key with the corresponding values
   * in the multimap. Changes to the returned map, such as element removal,
   * will update the underlying multimap. The map never supports
   * {@code setValue()} on the map entries, {@code put}, or {@code putAll}.
   *
   *
The collections returned by {@code asMap().get(Object)} have the same
   * behavior as those returned by {@link #get}.
   *
   *
Though the method signature doesn't say so explicitly, the returned map
   * has {@link SortedSet} values.
   */
  Map<K, Collection<V>> asMap();

  /**
   * Returns the comparator that orders the multimap values, with a {@code null}
   * indicating that natural ordering is used.
   */
  Comparator<? super V> valueComparator();
}


text:
import React from 'react';
import { connect } from 'react-redux';
import Cookies from 'js-cookie';
import Snackbar from 'material-ui/Snackbar';
import Navbar from '../Navbar';
import Signup from '../Signup';
import Login from '../Login';
import Welcome from '../Welcome';
import AddEvent from '../AddEvent';
import AddPhoto from '../AddPhoto';

import { toggleActive } from './actions';
import { AUTH_REQUEST, CLOSE_SNACKBAR } from './constants';

class App extends React.Component {
  static propTypes = {
    children: React.PropTypes.node.isRequired,
    signupActive: React.PropTypes.bool,
    loginActive: React.PropTypes.bool,
    welcomeActive: React.PropTypes.bool,
    addEventActive: React.PropTypes.bool,
    addPhotoActive: React.PropTypes.bool,
    snackbar: React.PropTypes.shape({
      open: React.PropTypes.bool,
      message: React.PropTypes.string,
    }),
    requestAuth: React.PropTypes.func,
    closeSnackbar: React.PropTypes.func,
    toggleActive: React.PropTypes.func,
  };

  constructor(props) {
    super(props);
    props.requestAuth();
    if (Cookies.get('welcomeRead') !== '1.0') {
      props.toggleActive('welcome');
    }
  }

  render = () => (
    <div>
      <Navbar />
      {this.props.children}
      {this.props.signupActive ? <Signup /> : null}
      {this.props.loginActive ? <Login /> : null}
      {this.props.welcomeActive ? <Welcome /> : null}
      {this.props.addEventActive ? <AddEvent /> : null}
      {this.props.addPhotoActive ? <AddPhoto /> : null}
      <Snackbar
        open={this.props.snackbar.open}
        message={this.props.snackbar.message}
        autoHideDuration={4000}
        onRequestClose={this.props.closeSnackbar}
        bodyStyle={{ backgroundColor: '#A5D6A7' }}
      />
    </div>
  )
}

const mapStateToProps = state => ({
  signupActive: state.app.signup,
  loginActive: state.app.login,
  welcomeActive: state.app.welcome,
  addEventActive: state.app.addEvent,
  addPhotoActive: state.app.addPhoto,
  snackbar: state.app.snackbar,
});

const mapDispatchToProps = dispatch => ({
  requestAuth: () => dispatch({ type: AUTH_REQUEST }),
  closeSnackbar: () => dispatch({ type: CLOSE_SNACKBAR }),
  toggleActive: target => dispatch(toggleActive(target)),
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App);


text:
/*! \file AshikhminShirleyReflection.h
 *  \author Jared Hoberock
 *  \brief Defines the interface to a ScatteringDistributionFunction
 *         which implements the anisotropic Ashikhmin-Shirley glossy
 *         reflection model.
 */

#ifndef ASHIKHMIN_SHIRLEY_REFLECTION_H
#define ASHIKHMIN_SHIRLEY_REFLECTION_H

#include "ScatteringDistributionFunction.h"
#include "functions/AshikhminShirleyReflectionBase.h"
#include "Fresnel.h"

class AshikhminShirleyReflection
  : public ScatteringDistributionFunction,
    public AshikhminShirleyReflectionBase<Vector,Spectrum>
{
  public:
    /*! \typedef Parent0
     *  \brief Shorthand.
     */
    typedef ScatteringDistributionFunction Parent0;

    /*! \typedef Parent1
     *  \brief Shorthand.
     */
    typedef AshikhminShirleyReflectionBase<Vector,Spectrum> Parent1;

    /*! Constructor accepts a reflectance, index of refraction,
     *  and two Ashikhmin-Shirley exponents to create an anisotropic
     *  glossy Fresnel conductor.
     *  \param r The reflectance of this AshikhminShirleyReflection.
     *  \param eta Sets the index of refraction of the Fresnel conductor.
     *  \param uExponent The Ashikhmin-Shirley exponent in the u direction.
     *  \param vExponent The Ashikhmin-Shriley exponent in the v direction.
     */
    AshikhminShirleyReflection(const Spectrum &r,
                               const float eta,
                               const float uExponent,
                               const float vExponent);

    /*! Constructor accepts a reflectance, two indices of refraction,
     *  and two Ashikhmin-Shirley exponents to create an anisotropic
     *  glossy Fresnel dielectric.
     *  \param r The reflectance of this AshikhminShirleyReflection.
     *  \param etai Sets the index of refraction of the medium surrounding this Fresnel dielectric.
     *  \param etat Sets the index of refraction of the Fresnel dielectric.
     *  \param uExponent The Ashikhmin-Shirley exponent in the u direction.
     *  \param vExponent The Ashikhmin-Shriley exponent in the v direction.
     */
    AshikhminShirleyReflection(const Spectrum &r,
                               const float etai,
                               const float etat,
                               const float uExponent,
                               const float vExponent);

    /*! This method evaluates this AshikhminShirleyReflection function.
     *  \param wi A vector pointing towards the direction of incoming radiance.
     *  \param dg The DifferentialGeometry at the surface point of interest.
     *  \param wo A vector pointing towards the viewing direction.
     *  \return The scattering in direction wo.
     */
    using Parent0::evaluate;
    virtual Spectrum evaluate(const Vector &wo,
                              const DifferentialGeometry &dg,
                              const Vector &wi) const;

    /*! This method evaluates the value of this AshikhminShirleyReflection and its pdf given a
     *  wo, DifferentialGeometry, and wi.
     *  This method is included to allow bidirectional path tracing's computation of
     *  MIS weights to work with composite scattering functions.
     *  \param wo A Vector pointing towards the direction of scattering.
     *  \param dg The DifferentialGeometry at the scattering Point of interest.
     *  \param wi A Vector pointing towards the direction of incidence.
     *  \param delta Ignored.  AshikhminShirleyReflection is not a delta function.
     *  \param component Ignored.  AshikhminShirleyReflection is a single component.
     *  \param pdf The value of this AshikhminShirleyReflection's pdf is returned here.
     *  \return The value of this AshikhminShirleyReflection.
     */
    virtual Spectrum evaluate(const Vector &wo,
                              const DifferentialGeometry &dg,
                              const Vector &wi,
                              const bool delta,
                              const ComponentIndex component,
                              float &pdf) const;

    /*! This method samples this AshikhminShirleyReflection function given a wo,
     *  DifferentialGeometry, and three numbers in the unit interval.
     *  \param wo The direction of scattering.
     *  \param dg The DifferentialGeometry at the point of interest.
     *  \param u0 A real number in [0,1).
     *  \param u1 A second real number in [0,1).
     *  \param u2 A third real number in [0,1).
     *  \param wi The direction of scattering is returned here.
     *  \param pdf The value of the pdf at (u0,u1,u2) is returned here.
     *  \param delta This is set to false.
     *  \param component This is set to 0.
     *  \return The bidirectional scattering from wi to wo is returned here.
     */
    using Parent0::sample;
    virtual Spectrum sample(const Vector &wo,
                            const DifferentialGeometry &dg,
                            const float u0,
                            const float u1,
                            const float u2,
                            Vector &wi,
                            float &pdf,
                            bool &delta,
                            ComponentIndex &component) const;

    /*! This method returns the value of
     *  this AshikhminShirleyReflection's pdf given a wo, DifferentialGeometry, and wi.
     *  \param wo A Vector pointing towards the direction of scattering.
     *  \param dg The DifferentialGeometry at the scattering Point of interest.
     *  \param wi A Vector pointing towards the direction of incidence.
     *  \return The value of the pdf at (wi,dg,wo).
     */
    using Parent0::evaluatePdf;
    virtual float evaluatePdf(const Vector &wo,
                              const DifferentialGeometry &dg,
                              const Vector &wi) const;
}; // end AshikhminShirleyReflection

#endif // ASHIKHMIN_SHIRLEY_REFLECTION_H