text:
package org.apache.catalina.loader;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilePermission;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLDecoder;
import java.net.URLStreamHandlerFactory;
import java.util.ArrayList;
import java.util.jar.JarFile;

import javax.management.ObjectName;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.servlet.ServletContext;

import org.apache.catalina.Container;
import org.apache.catalina.Context;
import org.apache.catalina.Globals;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleState;
import org.apache.catalina.Loader;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.mbeans.MBeanUtils;
import org.apache.catalina.util.LifecycleMBeanBase;
import org.apache.naming.resources.DirContextURLStreamHandler;
import org.apache.naming.resources.DirContextURLStreamHandlerFactory;
import org.apache.naming.resources.Resource;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.modeler.Registry;
import org.apache.tomcat.util.res.StringManager;

/**
 * Classloader implementation which is specialized for handling web
 * applications in the most efficient way, while being Catalina aware (all
 * accesses to resources are made through the DirContext interface).
 * This class loader supports detection of modified
 * Java classes, which can be used to implement auto-reload support.
 *

 * This class loader is configured by adding the pathnames of directories,
 * JAR files, and ZIP files with the addRepository() method,
 * prior to calling start().  When a new class is required,
 * these repositories will be consulted first to locate the class.  If it
 * is not present, the system class loader will be used instead.
 *
 * @author Craig R. McClanahan
 * @author Remy Maucherat
 */

public class WebappLoader extends LifecycleMBeanBase
    implements Loader, PropertyChangeListener {

    // ----------------------------------------------------------- Constructors

    /**
     * Construct a new WebappLoader with no defined parent class loader
     * (so that the actual parent will be the system class loader).
     */
    public WebappLoader() {

        this(null);

    }

    /**
     * Construct a new WebappLoader with the specified class loader
     * to be defined as the parent of the ClassLoader we ultimately create.
     *
     * @param parent The parent class loader
     */
    public WebappLoader(ClassLoader parent) {
        super();
        this.parentClassLoader = parent;
    }

    // ----------------------------------------------------- Instance Variables

    /**
     * First load of the class.
     */
    private static boolean first = true;

    /**
     * The class loader being managed by this Loader component.
     */
    private WebappClassLoaderBase classLoader = null;

    /**
     * The Container with which this Loader has been associated.
     */
    private Container container = null;

    /**
     * The "follow standard delegation model" flag that will be used to
     * configure our ClassLoader.
     */
    private boolean delegate = false;

    /**
     * The descriptive information about this Loader implementation.
     */
    private static final String info =
        "org.apache.catalina.loader.WebappLoader/1.0";

    /**
     * The Java class name of the ClassLoader implementation to be used.
     * This class should extend WebappClassLoaderBase, otherwise, a different
     * loader implementation must be used.
     */
    private String loaderClass =
        "org.apache.catalina.loader.WebappClassLoader";

    /**
     * The parent class loader of the class loader we will create.
     */
    private ClassLoader parentClassLoader = null;

    /**
     * The reloadable flag for this Loader.
     *
     * tomcat 的自动加载的属性
     */
    private boolean reloadable = false;

    /**
     * The set of repositories associated with this class loader.
     */
    private String repositories[] = new String[0];

    /**
     * The string manager for this package.
     */
    protected static final StringManager sm =
        StringManager.getManager(Constants.Package);

    /**
     * The property change support for this component.
     */
    protected PropertyChangeSupport support = new PropertyChangeSupport(this);

    /**
     * Classpath set in the loader.
     */
    private String classpath = null;

    /**
     * Repositories that are set in the loader, for JMX.
     */
    private ArrayList<String> loaderRepositories = null;

    /**
     * Whether we should search the external repositories first
     */
    private boolean searchExternalFirst = false;

    // ------------------------------------------------------------- Properties

    /**
     * Return the Java class loader to be used by this Container.
     */
    @Override
    public ClassLoader getClassLoader() {

        return classLoader;

    }

    /**
     * Return the Container with which this Logger has been associated.
     */
    @Override
    public Container getContainer() {

        return (container);

    }

    /**
     * Set the Container with which this Logger has been associated.
     *
     * @param container The associated Container
     */
    @Override
    public void setContainer(Container container) {

        // Deregister from the old Container (if any)
        if ((this.container != null) && (this.container instanceof Context))
            ((Context) this.container).removePropertyChangeListener(this);

        // Process this property change
        Container oldContainer = this.container;
        this.container = container;
        support.firePropertyChange("container", oldContainer, this.container);

        // Register with the new Container (if any)
        if ((this.container != null) && (this.container instanceof Context)) {
            setReloadable( ((Context) this.container).getReloadable() );
            ((Context) this.container).addPropertyChangeListener(this);
        }

    }

    /**
     * Return the "follow standard delegation model" flag used to configure
     * our ClassLoader.
     */
    @Override
    public boolean getDelegate() {

        return (this.delegate);

    }

    /**
     * Set the "follow standard delegation model" flag used to configure
     * our ClassLoader.
     *
     * @param delegate The new flag
     */
    @Override
    public void setDelegate(boolean delegate) {

        boolean oldDelegate = this.delegate;
        this.delegate = delegate;
        support.firePropertyChange("delegate", Boolean.valueOf(oldDelegate),
                                   Boolean.valueOf(this.delegate));

    }

    /**
     * Return descriptive information about this Loader implementation and
     * the corresponding version number, in the format
     * <description>/<version>.
     */
    @Override
    public String getInfo() {

        return (info);

    }

    /**
     * Return the ClassLoader class name.
     */
    public String getLoaderClass() {

        return (this.loaderClass);

    }

    /**
     * Set the ClassLoader class name.
     *
     * @param loaderClass The new ClassLoader class name
     */
    public void setLoaderClass(String loaderClass) {

        this.loaderClass = loaderClass;

    }

    /**
     * Return the reloadable flag for this Loader.
     */
    @Override
    public boolean getReloadable() {

        return (this.reloadable);

    }

    /**
     * Set the reloadable flag for this Loader.
     *
     * @param reloadable The new reloadable flag
     */
    @Override
    public void setReloadable(boolean reloadable) {

        // Process this property change
        boolean oldReloadable = this.reloadable;
        this.reloadable = reloadable;
        support.firePropertyChange("reloadable",
                                   Boolean.valueOf(oldReloadable),
                                   Boolean.valueOf(this.reloadable));

    }

    /**
     * @return Returns searchExternalFirst.
     */
    public boolean getSearchExternalFirst() {
        return searchExternalFirst;
    }

    /**
     * @param searchExternalFirst Whether external repositories should be searched first
     */
    public void setSearchExternalFirst(boolean searchExternalFirst) {
        this.searchExternalFirst = searchExternalFirst;
        if (classLoader != null) {
            classLoader.setSearchExternalFirst(searchExternalFirst);
        }
    }

    // --------------------------------------------------------- Public Methods

    /**
     * Add a property change listener to this component.
     *
     * @param listener The listener to add
     */
    @Override
    public void addPropertyChangeListener(PropertyChangeListener listener) {

        support.addPropertyChangeListener(listener);

    }

    /**
     * Add a new repository to the set of repositories for this class loader.
     *
     * @param repository Repository to be added
     */
    @Override
    public void addRepository(String repository) {

        if (log.isDebugEnabled())
            log.debug(sm.getString("webappLoader.addRepository", repository));

        for (int i = 0; i < repositories.length; i++) {
            if (repository.equals(repositories[i]))
                return;
        }
        String results[] = new String[repositories.length + 1];
        for (int i = 0; i < repositories.length; i++)
            results[i] = repositories[i];
        results[repositories.length] = repository;
        repositories = results;

        if (getState().isAvailable() && (classLoader != null)) {
            classLoader.addRepository(repository);
            if( loaderRepositories != null ) loaderRepositories.add(repository);
            setClassPath();
        }

    }

    /**
     * Execute a periodic task, such as reloading, etc. This method will be
     * invoked inside the classloading context of this container. Unexpected
     * throwables will be caught and logged.
     */
    @Override
    public void backgroundProcess() {
        if (reloadable && modified()) {
            try {
                Thread.currentThread().setContextClassLoader
                    (WebappLoader.class.getClassLoader());
                if (container instanceof StandardContext) {

                    // todo 其中reloadable变量的值就是本文开始提到的配置文件的Context节点的reloadable属性的值,
                    // 当它为true并且modified()方法返回也是true时就会执行StandardContext的reload方法:
                    ((StandardContext) container).reload();
                }
            } finally {
                if (container.getLoader() != null) {
                    Thread.currentThread().setContextClassLoader
                        (container.getLoader().getClassLoader());
                }
            }
        } else {
            closeJARs(false);
        }
    }

    /**
     * Return the set of repositories defined for this class loader.
     * If none are defined, a zero-length array is returned.
     * For security reason, returns a clone of the Array (since
     * String are immutable).
     */
    @Override
    public String[] findRepositories() {

        return repositories.clone();

    }

    public String[] getRepositories() {
        return repositories.clone();
    }

    /** Extra repositories for this loader
     */
    public String getRepositoriesString() {
        StringBuilder sb=new StringBuilder();
        for( int i=0; i<repositories.length ; i++ ) {
            sb.append( repositories[i]).append(":");
        }
        return sb.toString();
    }

    public String[] getLoaderRepositories() {
        if( loaderRepositories==null ) return  null;
        String res[]=new String[ loaderRepositories.size()];
        loaderRepositories.toArray(res);
        return res;
    }

    public String getLoaderRepositoriesString() {
        String repositories[]=getLoaderRepositories();
        StringBuilder sb=new StringBuilder();
        for( int i=0; i<repositories.length ; i++ ) {
            sb.append( repositories[i]).append(":");
        }
        return sb.toString();
    }

    /**
     * Classpath, as set in org.apache.catalina.jsp_classpath context
     * property
     *
     * @return The classpath
     */
    public String getClasspath() {
        return classpath;
    }

    /**
     * Has the internal repository associated with this Loader been modified,
     * such that the loaded classes should be reloaded?
     */
    @Override
    public boolean modified() {
        return classLoader != null ? classLoader.modified() : false ;
    }

    /**
     * Used to periodically signal to the classloader to release JAR resources.
     */
    public void closeJARs(boolean force) {
        if (classLoader !=null) {
            classLoader.closeJARs(force);
        }
    }

    /**
     * Remove a property change listener from this component.
     *
     * @param listener The listener to remove
     */
    @Override
    public void removePropertyChangeListener(PropertyChangeListener listener) {

        support.removePropertyChangeListener(listener);

    }

    /**
     * Return a String representation of this component.
     */
    @Override
    public String toString() {

        StringBuilder sb = new StringBuilder("WebappLoader[");
        if (container != null)
            sb.append(container.getName());
        sb.append("]");
        return (sb.toString());

    }

    /**
     * Start associated {@link ClassLoader} and implement the requirements
     * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
     *
     * @exception LifecycleException if this component detects a fatal error
     *  that prevents this component from being used
     */
    @Override
    protected void startInternal() throws LifecycleException {

        if (log.isDebugEnabled())
            log.debug(sm.getString("webappLoader.starting"));

        if (container.getResources() == null) {
            log.info("No resources for " + container);
            setState(LifecycleState.STARTING);
            return;
        }

        // Register a stream handler factory for the JNDI protocol
        URLStreamHandlerFactory streamHandlerFactory =
                DirContextURLStreamHandlerFactory.getInstance();
        if (first) {
            first = false;
            try {
                URL.setURLStreamHandlerFactory(streamHandlerFactory);
            } catch (Exception e) {
                // Log and continue anyway, this is not critical
                log.error("Error registering jndi stream handler", e);
            } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
                // This is likely a dual registration
                log.info("Dual registration of jndi stream handler: "
                         + t.getMessage());
            }
        }

        // Construct a class loader based on our current repositories list
        try {

            classLoader = createClassLoader();
            classLoader.setResources(container.getResources());
            classLoader.setDelegate(this.delegate);
            classLoader.setSearchExternalFirst(searchExternalFirst);
            if (container instanceof StandardContext) {
                classLoader.setAntiJARLocking(
                        ((StandardContext) container).getAntiJARLocking());
                classLoader.setClearReferencesRmiTargets(
                        ((StandardContext) container).getClearReferencesRmiTargets());
                classLoader.setClearReferencesStatic(
                        ((StandardContext) container).getClearReferencesStatic());
                classLoader.setClearReferencesStopThreads(
                        ((StandardContext) container).getClearReferencesStopThreads());
                classLoader.setClearReferencesStopTimerThreads(
                        ((StandardContext) container).getClearReferencesStopTimerThreads());
                classLoader.setClearReferencesHttpClientKeepAliveThread(
                        ((StandardContext) container).getClearReferencesHttpClientKeepAliveThread());
            }

            for (int i = 0; i < repositories.length; i++) {
                classLoader.addRepository(repositories[i]);
            }

            // Configure our repositories
            setRepositories();
            setClassPath();

            setPermissions();

            ((Lifecycle) classLoader).start();

            // Binding the Webapp class loader to the directory context
            DirContextURLStreamHandler.bind(classLoader,
                    this.container.getResources());

            StandardContext ctx=(StandardContext)container;
            String contextName = ctx.getName();
            if (!contextName.startsWith("/")) {
                contextName = "/" + contextName;
            }
            ObjectName cloname = new ObjectName
                (MBeanUtils.getDomain(ctx) + ":type=WebappClassLoader,context="
                 + contextName + ",host=" + ctx.getParent().getName());
            Registry.getRegistry(null, null)
                .registerComponent(classLoader, cloname, null);

        } catch (Throwable t) {
            t = ExceptionUtils.unwrapInvocationTargetException(t);
            ExceptionUtils.handleThrowable(t);
            log.error( "LifecycleException ", t );
            throw new LifecycleException("start: ", t);
        }

        setState(LifecycleState.STARTING);
    }

    /**
     * Stop associated {@link ClassLoader} and implement the requirements
     * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
     *
     * @exception LifecycleException if this component detects a fatal error
     *  that prevents this component from being used
     */
    @Override
    protected void stopInternal() throws LifecycleException {

        if (log.isDebugEnabled())
            log.debug(sm.getString("webappLoader.stopping"));

        setState(LifecycleState.STOPPING);

        // Remove context attributes as appropriate
        if (container instanceof Context) {
            ServletContext servletContext =
                ((Context) container).getServletContext();
            servletContext.removeAttribute(Globals.CLASS_PATH_ATTR);
        }

        // Throw away our current class loader
        if (classLoader != null) {
            ((Lifecycle) classLoader).stop();
            DirContextURLStreamHandler.unbind(classLoader);
        }

        try {
            StandardContext ctx=(StandardContext)container;
            String contextName = ctx.getName();
            if (!contextName.startsWith("/")) {
                contextName = "/" + contextName;
            }
            ObjectName cloname = new ObjectName
                (MBeanUtils.getDomain(ctx) + ":type=WebappClassLoader,context="
                 + contextName + ",host=" + ctx.getParent().getName());
            Registry.getRegistry(null, null).unregisterComponent(cloname);
        } catch (Exception e) {
            log.error("LifecycleException ", e);
        }

        classLoader = null;
    }

    // ----------------------------------------- PropertyChangeListener Methods

    /**
     * Process property change events from our associated Context.
     *
     * @param event The property change event that has occurred
     */
    @Override
    public void propertyChange(PropertyChangeEvent event) {

        // Validate the source of this event
        if (!(event.getSource() instanceof Context))
            return;

        // Process a relevant property change
        if (event.getPropertyName().equals("reloadable")) {
            try {
                setReloadable
                    ( ((Boolean) event.getNewValue()).booleanValue() );
            } catch (NumberFormatException e) {
                log.error(sm.getString("webappLoader.reloadable",
                                 event.getNewValue().toString()));
            }
        }

    }

    // ------------------------------------------------------- Private Methods

    /**
     * Create associated classLoader.
     */
    private WebappClassLoaderBase createClassLoader()
        throws Exception {

        Class<?> clazz = Class.forName(loaderClass);
        WebappClassLoaderBase classLoader = null;

        if (parentClassLoader == null) {
            parentClassLoader = container.getParentClassLoader();
        }
        Class<?>[] argTypes = { ClassLoader.class };
        Object[] args = { parentClassLoader };
        Constructor<?> constr = clazz.getConstructor(argTypes);
        classLoader = (WebappClassLoaderBase) constr.newInstance(args);

        return classLoader;

    }

    /**
     * Configure associated class loader permissions.
     */
    private void setPermissions() {

        if (!Globals.IS_SECURITY_ENABLED)
            return;
        if (!(container instanceof Context))
            return;

        // Tell the class loader the root of the context
        ServletContext servletContext =
            ((Context) container).getServletContext();

        // Assigning permissions for the work directory
        File workDir =
            (File) servletContext.getAttribute(ServletContext.TEMPDIR);
        if (workDir != null) {
            try {
                String workDirPath = workDir.getCanonicalPath();
                classLoader.addPermission
                    (new FilePermission(workDirPath, "read,write"));
                classLoader.addPermission
                    (new FilePermission(workDirPath + File.separator + "-",
                                        "read,write,delete"));
            } catch (IOException e) {
                // Ignore
            }
        }

        try {

            URL rootURL = servletContext.getResource("/");
            classLoader.addPermission(rootURL);

            String contextRoot = servletContext.getRealPath("/");
            if (contextRoot != null) {
                try {
                    contextRoot = (new File(contextRoot)).getCanonicalPath();
                    classLoader.addPermission(contextRoot);
                } catch (IOException e) {
                    // Ignore
                }
            }

            URL classesURL = servletContext.getResource("/WEB-INF/classes/");
            classLoader.addPermission(classesURL);
            URL libURL = servletContext.getResource("/WEB-INF/lib/");
            classLoader.addPermission(libURL);

            if (contextRoot != null) {

                if (libURL != null) {
                    File rootDir = new File(contextRoot);
                    File libDir = new File(rootDir, "WEB-INF/lib/");
                    try {
                        String path = libDir.getCanonicalPath();
                        classLoader.addPermission(path);
                    } catch (IOException e) {
                        // Ignore
                    }
                }

            } else {

                if (workDir != null) {
                    if (libURL != null) {
                        File libDir = new File(workDir, "WEB-INF/lib/");
                        try {
                            String path = libDir.getCanonicalPath();
                            classLoader.addPermission(path);
                        } catch (IOException e) {
                            // Ignore
                        }
                    }
                    if (classesURL != null) {
                        File classesDir = new File(workDir, "WEB-INF/classes/");
                        try {
                            String path = classesDir.getCanonicalPath();
                            classLoader.addPermission(path);
                        } catch (IOException e) {
                            // Ignore
                        }
                    }
                }

            }

        } catch (MalformedURLException e) {
            // Ignore
        }

    }

    /**
     * Configure the repositories for our class loader, based on the
     * associated Context.
     * @throws IOException
     */
    private void setRepositories() throws IOException {

        if (!(container instanceof Context))
            return;
        ServletContext servletContext =
            ((Context) container).getServletContext();
        if (servletContext == null)
            return;

        loaderRepositories=new ArrayList<String>();
        // Loading the work directory
        File workDir =
            (File) servletContext.getAttribute(ServletContext.TEMPDIR);
        if (workDir == null) {
            log.info("No work dir for " + servletContext);
        }

        if( log.isDebugEnabled() && workDir != null)
            log.debug(sm.getString("webappLoader.deploy", workDir.getAbsolutePath()));

        classLoader.setWorkDir(workDir);

        DirContext resources = container.getResources();

        // Setting up the class repository (/WEB-INF/classes), if it exists

        String classesPath = "/WEB-INF/classes";
        DirContext classes = null;

        try {
            Object object = resources.lookup(classesPath);
            if (object instanceof DirContext) {
                classes = (DirContext) object;
            }
        } catch(NamingException e) {
            // Silent catch: it's valid that no /WEB-INF/classes collection
            // exists
        }

        if (classes != null) {

            File classRepository = null;

            String absoluteClassesPath =
                servletContext.getRealPath(classesPath);

            if (absoluteClassesPath != null) {

                classRepository = new File(absoluteClassesPath);

            } else {

                classRepository = new File(workDir, classesPath);
                if (!classRepository.mkdirs() &&
                        !classRepository.isDirectory()) {
                    throw new IOException(
                            sm.getString("webappLoader.mkdirFailure"));
                }
                if (!copyDir(classes, classRepository)) {
                    throw new IOException(
                            sm.getString("webappLoader.copyFailure"));
                }

            }

            if(log.isDebugEnabled())
                log.debug(sm.getString("webappLoader.classDeploy", classesPath,
                             classRepository.getAbsolutePath()));

            // Adding the repository to the class loader
            classLoader.addRepository(classesPath + "/", classRepository);
            loaderRepositories.add(classesPath + "/" );

        }

        // Setting up the JAR repository (/WEB-INF/lib), if it exists

        String libPath = "/WEB-INF/lib";

        classLoader.setJarPath(libPath);

        DirContext libDir = null;
        // Looking up directory /WEB-INF/lib in the context
        try {
            Object object = resources.lookup(libPath);
            if (object instanceof DirContext)
                libDir = (DirContext) object;
        } catch(NamingException e) {
            // Silent catch: it's valid that no /WEB-INF/lib collection
            // exists
        }

        if (libDir != null) {

            boolean copyJars = false;
            String absoluteLibPath = servletContext.getRealPath(libPath);

            File destDir = null;

            if (absoluteLibPath != null) {
                destDir = new File(absoluteLibPath);
            } else {
                copyJars = true;
                destDir = new File(workDir, libPath);
                if (!destDir.mkdirs() && !destDir.isDirectory()) {
                    throw new IOException(
                            sm.getString("webappLoader.mkdirFailure"));
                }
            }

            // Looking up directory /WEB-INF/lib in the context
            NamingEnumeration<NameClassPair> enumeration = null;
            try {
                enumeration = libDir.list("");
            } catch (NamingException e) {
                IOException ioe = new IOException(sm.getString(
                        "webappLoader.namingFailure", libPath));
                ioe.initCause(e);
                throw ioe;
            }
            while (enumeration.hasMoreElements()) {
                NameClassPair ncPair = enumeration.nextElement();
                String filename = libPath + "/" + ncPair.getName();
                if (!filename.endsWith(".jar"))
                    continue;

                // Copy JAR in the work directory, always (the JAR file
                // would get locked otherwise, which would make it
                // impossible to update it or remove it at runtime)
                File destFile = new File(destDir, ncPair.getName());

                if( log.isDebugEnabled())
                log.debug(sm.getString("webappLoader.jarDeploy", filename,
                                 destFile.getAbsolutePath()));

                // Bug 45403 - Explicitly call lookup() on the name to check
                // that the resource is readable. We cannot use resources
                // returned by listBindings(), because that lists all of them,
                // but does not perform the necessary checks on each.
                Object obj = null;
                try {
                    obj = libDir.lookup(ncPair.getName());
                } catch (NamingException e) {
                    IOException ioe = new IOException(sm.getString(
                            "webappLoader.namingFailure", filename));
                    ioe.initCause(e);
                    throw ioe;
                }

                if (!(obj instanceof Resource))
                    continue;

                Resource jarResource = (Resource) obj;

                if (copyJars) {
                    if (!copy(jarResource.streamContent(),
                              new FileOutputStream(destFile))) {
                        throw new IOException(
                                sm.getString("webappLoader.copyFailure"));
                    }
                }

                try {
                    JarFile jarFile = new JarFile(destFile);
                    classLoader.addJar(filename, jarFile, destFile);
                } catch (Exception ex) {
                    // Catch the exception if there is an empty jar file
                    // Should ignore and continue loading other jar files
                    // in the dir
                }

                loaderRepositories.add( filename );
            }
        }
    }

    /**
     * Set the appropriate context attribute for our class path.  This
     * is required only because Jasper depends on it.
     */
    private void setClassPath() {

        // Validate our current state information
        if (!(container instanceof Context))
            return;
        ServletContext servletContext =
            ((Context) container).getServletContext();
        if (servletContext == null)
            return;

        if (container instanceof StandardContext) {
            String baseClasspath =
                ((StandardContext) container).getCompilerClasspath();
            if (baseClasspath != null) {
                servletContext.setAttribute(Globals.CLASS_PATH_ATTR,
                                            baseClasspath);
                return;
            }
        }

        StringBuilder classpath = new StringBuilder();

        // Assemble the class path information from our class loader chain
        ClassLoader loader = getClassLoader();

        if (delegate && loader != null) {
            // Skip the webapp loader for now as delegation is enabled
            loader = loader.getParent();
        }

        while (loader != null) {
            if (!buildClassPath(servletContext, classpath, loader)) {
                break;
            }
            loader = loader.getParent();
        }

        if (delegate) {
            // Delegation was enabled, go back and add the webapp paths
            loader = getClassLoader();
            if (loader != null) {
                buildClassPath(servletContext, classpath, loader);
            }
        }

        this.classpath=classpath.toString();

        // Store the assembled class path as a servlet context attribute
        servletContext.setAttribute(Globals.CLASS_PATH_ATTR,
                                    classpath.toString());

    }

    private boolean buildClassPath(ServletContext servletContext,
            StringBuilder classpath, ClassLoader loader) {
        if (loader instanceof URLClassLoader) {
            URL repositories[] =
                    ((URLClassLoader) loader).getURLs();
                for (int i = 0; i < repositories.length; i++) {
                    String repository = repositories[i].toString();
                    if (repository.startsWith("file://"))
                        repository = utf8Decode(repository.substring(7));
                    else if (repository.startsWith("file:"))
                        repository = utf8Decode(repository.substring(5));
                    else if (repository.startsWith("jndi:"))
                        repository =
                            servletContext.getRealPath(repository.substring(5));
                    else
                        continue;
                    if (repository == null)
                        continue;
                    if (classpath.length() > 0)
                        classpath.append(File.pathSeparator);
                    classpath.append(repository);
                }
        } else {
            String cp = getClasspath(loader);
            if (cp == null) {
                log.info( "Unknown loader " + loader + " " + loader.getClass());
            } else {
                if (classpath.length() > 0)
                    classpath.append(File.pathSeparator);
                classpath.append(cp);
            }
            return false;
        }
        return true;
    }

    private String utf8Decode(String input) {
        String result = null;
        try {
            result = URLDecoder.decode(input, "UTF-8");
        } catch (UnsupportedEncodingException uee) {
            // Impossible. All JVMs are required to support UTF-8.
        }
        return result;
    }

    // try to extract the classpath from a loader that is not URLClassLoader
    private String getClasspath( ClassLoader loader ) {
        try {
            Method m=loader.getClass().getMethod("getClasspath", new Class[] {});
            if( log.isTraceEnabled())
                log.trace("getClasspath " + m );
            Object o=m.invoke( loader, new Object[] {} );
            if( log.isDebugEnabled() )
                log.debug("gotClasspath " + o);
            if( o instanceof String )
                return (String)o;
            return null;
        } catch( Exception ex ) {
            Throwable t = ExceptionUtils.unwrapInvocationTargetException(ex);
            ExceptionUtils.handleThrowable(t);
            if (log.isDebugEnabled())
                log.debug("getClasspath ", ex);
        }
        return null;
    }

    /**
     * Copy directory.
     */
    private boolean copyDir(DirContext srcDir, File destDir) {

        try {

            NamingEnumeration<NameClassPair> enumeration = srcDir.list("");
            while (enumeration.hasMoreElements()) {
                NameClassPair ncPair = enumeration.nextElement();
                String name = ncPair.getName();
                Object object = srcDir.lookup(name);
                File currentFile = new File(destDir, name);
                if (object instanceof Resource) {
                    InputStream is = ((Resource) object).streamContent();
                    OutputStream os = new FileOutputStream(currentFile);
                    if (!copy(is, os))
                        return false;
                } else if (object instanceof InputStream) {
                    OutputStream os = new FileOutputStream(currentFile);
                    if (!copy((InputStream) object, os))
                        return false;
                } else if (object instanceof DirContext) {
                    if (!currentFile.isDirectory() && !currentFile.mkdir())
                        return false;
                    if (!copyDir((DirContext) object, currentFile))
                        return false;
                }
            }

        } catch (NamingException e) {
            return false;
        } catch (IOException e) {
            return false;
        }

        return true;

    }

    /**
     * Copy a file to the specified temp directory. This is required only
     * because Jasper depends on it.
     */
    private boolean copy(InputStream is, OutputStream os) {

        try {
            byte[] buf = new byte[4096];
            while (true) {
                int len = is.read(buf);
                if (len < 0)
                    break;
                os.write(buf, 0, len);
            }
            is.close();
            os.close();
        } catch (IOException e) {
            return false;
        }

        return true;

    }

    private static final org.apache.juli.logging.Log log=
        org.apache.juli.logging.LogFactory.getLog( WebappLoader.class );

    @Override
    protected String getDomainInternal() {
        return MBeanUtils.getDomain(container);
    }

    @Override
    protected String getObjectNameKeyProperties() {

        StringBuilder name = new StringBuilder("type=Loader");

        if (container instanceof Context) {
            name.append(",context=");
            Context context = (Context) container;

            String contextName = context.getName();
            if (!contextName.startsWith("/")) {
                name.append("/");
            }
            name.append(contextName);

            name.append(",host=");
            name.append(context.getParent().getName());
        } else {
            // Unlikely / impossible? Handle it to be safe
            name.append(",container=");
            name.append(container.getName());
        }

        return name.toString();
    }

}


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W20523_extracted</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans2.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">HALLIBURTDN

    <p class="styleSans35.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Job Recommendation Surface Casing

Fluid Instructions
Fluid 1: Water Based Spacer
Water Spacer Fluid Density: 8.34 lbm/gal Fluid Volume: 20 bbl
Fluid 2: Lead Cement VARICEM (TM) CEMENT Fluid Weight 11.50 lbm/gal 0.125 lbm/sk Poly-E-Flake (Lost Circulation Additive) Slurry Yield: 2.97 fIJ/sk Total Mixing Fluid: 18.17 Gal/5k Top of Fluid: 0 ft Calculated Fill: 1700 ft Volume: 251.57 bbl
Calculated Sacks: 476.22 sks  - A null,
Proposed Sacks: 480 sks

    <p class="styleSans4.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Fluid 3: Tail Cement VARICEM (TM) CEMENT Fluid Weight 0.125 lbm/sk Poly-E-F lake (Lost Circulation Additive) Slurry Yield: Total Mixing Fluid: Top of Fluid: Calculated Fill: Volume: Calculated Sacks: Proposed Sacks:

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Fluid 4: Water Spacer Water Displacement

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">6/16

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans43.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">l3 lbm/gal 2.01 fi3/sk 11.05 Gal/3k 1700 ft
350 ft
54.89 bbl 153.01 sks 155 sks
47 L r .95 waif

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Fluid Density: Fluid Volume:

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Proposal Federal 16-30—2H - #260015 v.1

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">8.34 lbm/gal 155.39 bbl

redpajama_set_name: RedPajamaGithub


text:
This documentation embeds [Code Pen](https://codepen.io/) pens to illustrate how the code works. This folder contains the raw source for these pens.

## Code Pen configuration

Code Pen was configured to use `Babel` as a JavaScript preprocessor, and rely on the following external files:

https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.min.js
https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.min.js
https://cdnjs.cloudflare.com/ajax/libs/redux/3.6.0/redux.min.js
https://cdnjs.cloudflare.com/ajax/libs/react-redux/5.0.2/react-redux.min.js

## HTML

The following `HTML` should suffice for all the pens.

```html
<div id="base">
<div>
```

## CSS

The following `css` should suffice for all the pens.

```css
#base {
  padding: 20px;
}

.controls {
  display: inline-block;
}

.up::before {
  content: '↑'
}

.down::before {
  content: '↓'
}

.remove::before {
  content: '×'
}

.debug {
  margin-top: 20px;
  padding-top: 20px;
  border-top: solid #ccc 1px;
  color: red;
  font-family: monospace;
}
```

## Code

- [react-redux/component.md](./code-editor-component.js)

TODO keep up to date


text:
/** PURE_IMPORTS_START .._operators_publishLast PURE_IMPORTS_END */
import { publishLast as higherOrder } from '../operators/publishLast';
/**
 * @return {ConnectableObservable<T>}
 * @method publishLast
 * @owner Observable
 */
export function publishLast() {
    //TODO(benlesh): correct type-flow through here.
    return higherOrder()(this);
}
//# sourceMappingURL=publishLast.js.map


text:
import graphene

from app import db
from app.graphql.object import SkillInput, User as User, Profile as Profile
from app.model import User as UserModel, Profile as ProfileModel, Skill as SkillModel

class UserMutation(graphene.Mutation):
    class Arguments:
        username = graphene.String(required=True)
        name = graphene.String(required=True)
        last_name = graphene.String(required=True)

    user = graphene.Field(lambda: User)

    def mutate(self, info, username, name, last_name):
        user = UserModel(username=username, name=name, last_name=last_name)

        db.session.add(user)
        db.session.commit()

        return UserMutation(user=user)

class ProfileMutation(graphene.Mutation):
    class Arguments:
        role = graphene.String(required=True)
        description = graphene.String(required=True)
        user_id = graphene.Int(required=True)
        skills = graphene.List(SkillInput)
        id = graphene.Int()

    profile = graphene.Field(lambda: Profile)

    def mutate(self, info, role, description, user_id, skills):
        user = UserModel.query.get(user_id)

        profile = ProfileModel(role=role, description=description)
        # Create skills
        skill_list = [SkillModel(name=input_skill.name, score=input_skill.score) for input_skill in skills]
        profile.skills.extend(skill_list)

        db.session.add(profile)

        # Update user
        user.profile = profile

        db.session.commit()

        return ProfileMutation(profile=profile)

class Mutation(graphene.ObjectType):
    mutate_user = UserMutation.Field()
    mutate_profile = ProfileMutation.Field()


text:
require 'rubygems'
require 'midilib'                                   # => false

class TimedTrack < MIDI::Track
  PITCH_G2 = 43
  @@channel_counter=0

  def initialize(number, song)
    super(number)
    @sequence = song
    @time = 0
    @channel = @@channel_counter
    @@channel_counter += 1
  end

  # Tell this track's channel to use the given instrument, and
  # also set the track's instrument display name.
  def instrument=(instrument)
    @events << MIDI::ProgramChange.new(@channel, instrument)
    super(MIDI::GM_PATCH_NAMES[instrument])
  end

  # Add one or more notes to sound simultaneously. Increments the per-track
  # timer so that subsequent notes will sound after this one finishes.
  def add_notes(offsets, velocity=127, duration='quarter')
    offsets = [offsets] unless offsets.respond_to? :each
    offsets.each do |offset|
      event(MIDI::NoteOnEvent.new(@channel, PITCH_G2 + offset, velocity))
    end
    @time += @sequence.note_to_delta(duration)
    offsets.each do |offset|
      event(MIDI::NoteOffEvent.new(@channel, PITCH_G2 + offset, velocity))
    end
    recalc_delta_from_times
  end

  private
  def event(event)
    @events << event
   event.time_from_start = @time
  end
end
#=========================
module HarmonyMidi
TRACK_0 = 0
GM_PATCH_NAME_ACOUSTIC_GRAND_PIANO = 0
#-----------------------------
  class Play
    def Play.set_up
      @song = MIDI::Sequence.new
      @harmony = TimedTrack.new( TRACK_0, @song)
      @song.tracks << ( @harmony)
      @harmony.instrument = GM_PATCH_NAME_ACOUSTIC_GRAND_PIANO
      beats_per_minute = 100
      correcting_factor = # By observation in RealPlayer.
      ((35 * 60) + 37.0) / ((42 * 60) + 42.0)
      seconds_per_beat = (60.0/beats_per_minute) * correcting_factor
      @harmony.events << MIDI::Tempo.new(MIDI::Tempo.bpm_to_mpq(beats_per_minute))
      @harmony.events << MIDI::MetaEvent.new(MIDI::META_SEQ_NAME, 'Thirdschords')
      @clock = 0.0
      @clock_half = 2.0 * seconds_per_beat
      @clock_eighth = seconds_per_beat / 2.0
      @harmony.add_notes([0], velocity = 63, 'half') # Ate the first one.
      @harmony.add_notes([], velocity = 63, 'eighth')
      @clock += 1.0 # By observation in RealPlayer.
    end

    def Play.handle_necklace( necklace, necklace_number)
print "necklace #{necklace_number} "; p necklace.word.to_s( 2)
#      @harmony.events << MIDI::MetaEvent.new( MIDI::META_SEQ_NAME,
#                                    'A-random-Ruby-composition')
#                                    'necklace ' +
#                                     '')
# necklace.word.to_s( Bit::BINARY))
      @harmony.add_notes([], velocity = 63, 'eighth')
      @clock += @clock_eighth
    end

    def Play.handle_chord( absolutes, root_number)
print "#{Play.clock_string()} root #{root_number} chord "; p absolutes
      @harmony.add_notes(absolutes, velocity = 63, 'half')
      @clock += @clock_half
    end

    def Play.tear_down
      open('thirdsout.mid', 'w') { |f| @song.write( f) }
    end

    def Play.clock_string
      minutes = (@clock / 60.0).floor
      seconds = (@clock - (minutes * 60.0)).floor
      [minutes, seconds].collect {|e| (e >= 10 ? '' : '0') + e.to_s}.join( ':')
    end
  end #class Play
end #module HarmonyMidi


text:
require "okcomputer-newrelic-ignore/version"

require 'okcomputer'
require File.join OKComputer::Engine.paths["app/controllers"].expanded.first, "ok_computer_controller.rb"
require 'new_relic/agent/instrumentation/controller_instrumentation'
class OkComputerController
  include NewRelic::Agent::Instrumentation::ControllerInstrumentation
  newrelic_ignore
end


text:
import * as assert from "assert";
import {IntentSchema} from "../../lib/alexa/intent-schema";
import {InteractionModel} from "../../lib/alexa/interaction-model";
import {SampleUtterances} from "../../lib/alexa/sample-utterances";
import {Alexa} from "../../lib/alexa/alexa";
import {RequestCallback} from "request";

describe("Alexa", function() {
    // The intentName schema we will use in these tests
    let intentSchemaJSON = {
        "intents": [
            {"intent": "NearestLocation"},
            {"intent": "AnotherIntent"},
            {"intent": "TakeMeToWalmart", "slots": [
                {"name": "SlotName", "type": "SLOT_TYPE"}
            ]}
        ]
    };

    let sampleUtterancesJSON = {
        "NearestLocation": ["Nearest Location", "Location"],
        "TakeMeToWalmart": ["Take Me To Walmart {SlotName}"],
        "NoMatchingIntent": ["No Matching"]
    };

    let model = new InteractionModel(
        new IntentSchema(intentSchemaJSON),
        SampleUtterances.fromJSON(sampleUtterancesJSON));

    let alexa: Alexa = null;
    beforeEach(function () {
        alexa = new Alexa();
    });

    describe("#spoken()", function() {
        it("Returns payload", function(done) {
            let skillURL = "https://alexa.xappmedia.com/xapp?tag=JPKUnitTest&apiKey=XappMediaApiKey&appKey=DefaultApp";

            (<any> alexa).post = function(options: any, responseHandler: RequestCallback) {
                responseHandler(null, null, {
                    response: {
                        shouldEndSession: true,
                        outputSpeech: {
                            ssml: "<speak><audio src=\"https://audio.com/audio.mp3\" /></speak>"
                        }
                    }
                });
            };

            alexa.startSession(skillURL, model, false).spoken("Nearest Location", function (error: any, response: any, request: any) {
                assert(request);
                assert(response.response.outputSpeech.ssml !== null);
                assert.equal(response.response.outputSpeech.ssml, "<speak><audio src=\"https://audio.com/audio.mp3\" /></speak>");
                done();
            });
        });

        it("Handle With Slot", function(done) {
            let skillURL = "https://alexa.xappmedia.com/xapp?tag=JPKUnitTest&apiKey=XappMediaApiKey&appKey=DefaultApp";
            (<any> alexa).post = function(options: any, responseHandler: RequestCallback) {
                responseHandler(null, null, {
                    response: {
                        shouldEndSession: true,
                    }
                });
            };

            alexa.startSession(skillURL, model, false).spoken("Take Me To Walmart {A}", function (error: any, response: any) {
                assert(response.response.shouldEndSession);
                done();
            });
        });

        it("Handles error on bad URL", function(done) {
            this.timeout(5000);
            let skillURL = "https://alexa.xappmedia.xyz/xapp?tag=JPKUnitTest&apiKey=XappMediaApiKey&appKey=DefaultApp";
            alexa.startSession(skillURL, model, false).spoken("Nearest Location", function (error: any){
                assert(error);
                assert.equal(error.message, "getaddrinfo ENOTFOUND alexa.xappmedia.xyz alexa.xappmedia.xyz:443");
                done();
            });
        });

        it("Handles error on bad Intent", function(done) {
            this.timeout(10000);
            let skillURL = "https://alexa.xappmedia.com/xapp?tag=JPKUnitTest&apiKey=XappMediaApiKey&appKey=DefaultApp";
            alexa.startSession(skillURL, model, false).spoken("No Matching", function (error: any) {
                assert(error);
                assert.equal(error.message, "Interaction model has no intentName named: NoMatchingIntent");
                done();
            });
        });

        it("Handles default on bad Phrase", function(done) {
            this.timeout(10000);
            let skillURL = "https://alexa.xappmedia.com/xapp?tag=JPKUnitTest&apiKey=XappMediaApiKey&appKey=DefaultApp";
            alexa.startSession(skillURL, model, false).spoken("NotMatching", function (error: any, response: any, request: any) {
                assert.equal(request.request.intent.name, "NearestLocation");
                done();
            });
        });

        it("Handles end session", function(done) {
            let skillURL = "https://alexa.xappmedia.com/xapp?tag=JPKUnitTest&apiKey=XappMediaApiKey&appKey=DefaultApp";
            (<any> alexa).post = function(options: any, responseHandler: RequestCallback) {
                responseHandler(null, null, {
                    response: {
                        shouldEndSession: true
                    }
                });
            };
            alexa.startSession(skillURL, model, false);
            alexa.spoken("Nearest Location", function () {
                assert(!alexa.context().activeSession());
                done();
            });
        });

        it("Handles session attributes", function(done) {
            let skillURL = "https://alexa.xappmedia.com/xapp?tag=JPKUnitTest&apiKey=XappMediaApiKey&appKey=DefaultApp";

            let count = 0;
            (<any> alexa).post = function(options: any, responseHandler: RequestCallback) {
                count++;
                let shouldEndSession = false;
                if (count === 2) {
                    shouldEndSession = true;
                }
                responseHandler(null, null, {
                    response: {
                        shouldEndSession: shouldEndSession
                    },
                    sessionAttributes: {
                        attribute1: "Test"
                    }
                });

                // On the second call, the session attributes should be in the request that came through on the previous response
                if (count === 2) {
                    assert.equal(options.json.session.attributes.attribute1, "Test");
                }

                if (count === 3) {
                    assert(!options.json.session.attributes.attribute1);
                }
            };
            alexa.startSession(skillURL, model, false);
            alexa.spoken("Nearest Location");
            alexa.spoken("Nearest Location");
            alexa.spoken("Nearest Location", function () {
                done();
            });

        });
    });

    describe("#intended()", function () {
        it("Handles error on bad URL", function(done) {
            let skillURL = "https://alexa.xappmedia.xyz/xapp?tag=JPKUnitTest&apiKey=XappMediaApiKey&appKey=DefaultApp";
            alexa.startSession(skillURL, model, false).intended("NearestLocation", null, function (error: any) {
                assert(error);
                assert.equal(error.message, "getaddrinfo ENOTFOUND alexa.xappmedia.xyz alexa.xappmedia.xyz:443");
                done();
            });
        });
    });

    describe("#shutdown()", function () {
        it("Shuts down async correctly", function(done) {
            let skillURL = "https://alexa.xappmedia.xyz/xapp?tag=JPKUnitTest&apiKey=XappMediaApiKey&appKey=DefaultApp";
            (<any> alexa).post = function(options: any, responseHandler: RequestCallback) {
                setTimeout(function () {
                    responseHandler(null, null, {
                        response: {
                            shouldEndSession: true
                        }
                    });
                }, 1);
            };
            alexa.startSession(skillURL, model, false);
            alexa.spoken("NotMatching");
            alexa.intended("NearestLocation", null);
            alexa.stop(function () {
                done();
            });
        });

        it("Shuts down immediately", function(done) {
            let skillURL = "https://alexa.xappmedia.xyz/xapp?tag=JPKUnitTest&apiKey=XappMediaApiKey&appKey=DefaultApp";
            (<any> alexa).post = function(options: any, responseHandler: RequestCallback) {
                responseHandler(null, null, {
                    response: {
                        shouldEndSession: true
                    }
                });
            };
            alexa.startSession(skillURL, model, false);
            alexa.spoken("NotMatching");
            alexa.intended("NearestLocation", null);
            alexa.stop(function () {
                done();
            });
        });
    });
});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Arcangeliella stephensii var. stephensii (Berk.) C.W. Dodge

### Remarks
null


text:
FROM ubuntu:12.04

RUN apt-get update -y && apt-get install -y python python-pip


text:
/**
 * @file gyro.cpp
 *
 * Driver for the Invensense mpu9250 connected via SPI.
 *
 * @author Andrew Tridgell
 *
 * based on the mpu6000 driver
 */

#include <px4_config.h>

#include <sys/types.h>
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>

#include <systemlib/perf_counter.h>

#include <board_config.h>
#include <drivers/drv_hrt.h>

#include <drivers/device/spi.h>
#include <drivers/device/ringbuffer.h>
#include <drivers/device/integrator.h>
#include <drivers/drv_accel.h>
#include <drivers/drv_gyro.h>
#include <drivers/drv_mag.h>
#include <mathlib/math/filter/LowPassFilter2p.hpp>
#include <lib/conversion/rotation.h>

#include "mag.h"
#include "gyro.h"
#include "mpu9250.h"

MPU9250_gyro::MPU9250_gyro(MPU9250 *parent, const char *path) :
	CDev("MPU9250_gyro", path),
	_parent(parent),
	_gyro_topic(nullptr),
	_gyro_orb_class_instance(-1),
	_gyro_class_instance(-1)
{
}

MPU9250_gyro::~MPU9250_gyro()
{
	if (_gyro_class_instance != -1) {
		unregister_class_devname(GYRO_BASE_DEVICE_PATH, _gyro_class_instance);
	}
}

int
MPU9250_gyro::init()
{
	int ret;

	// do base class init
	ret = CDev::init();

	/* if probe/setup failed, bail now */
	if (ret != OK) {
		DEVICE_DEBUG("gyro init failed");
		return ret;
	}

	_gyro_class_instance = register_class_devname(GYRO_BASE_DEVICE_PATH);

	return ret;
}

void
MPU9250_gyro::parent_poll_notify()
{
	poll_notify(POLLIN);
}

ssize_t
MPU9250_gyro::read(struct file *filp, char *buffer, size_t buflen)
{
	return _parent->gyro_read(filp, buffer, buflen);
}

int
MPU9250_gyro::ioctl(struct file *filp, int cmd, unsigned long arg)
{

	switch (cmd) {
	case DEVIOCGDEVICEID:
		return (int)CDev::ioctl(filp, cmd, arg);
		break;

	default:
		return _parent->gyro_ioctl(filp, cmd, arg);
	}
}


text:
package com.xeiam.xchange.okcoin.service.polling;

import java.io.IOException;
import java.math.BigDecimal;

import com.xeiam.xchange.Exchange;
import com.xeiam.xchange.currency.Currency;
import com.xeiam.xchange.dto.account.AccountInfo;
import com.xeiam.xchange.exceptions.NotAvailableFromExchangeException;
import com.xeiam.xchange.okcoin.OkCoinAdapters;
import com.xeiam.xchange.okcoin.dto.account.OKCoinWithdraw;
import com.xeiam.xchange.service.polling.account.PollingAccountService;

public class OkCoinAccountService extends OkCoinAccountServiceRaw implements PollingAccountService {

  /**
   * Constructor
   *
   * @param exchange
   */
  public OkCoinAccountService(Exchange exchange) {

    super(exchange);

  }

  @Override
  public AccountInfo getAccountInfo() throws IOException {

    return OkCoinAdapters.adaptAccountInfo(getUserInfo());
  }

  @Override
  public String withdrawFunds(Currency currency, BigDecimal amount, String address) throws IOException {
      String okcoinCurrency = currency == Currency.BTC ? "btc_usd" : "btc_ltc";

       OKCoinWithdraw result = withdraw(null, okcoinCurrency, address, amount);

       if(result != null)
           return result.getWithdrawId();

      return "";
  }

  @Override
  public String requestDepositAddress(Currency currency, String... args) throws IOException {

    throw new NotAvailableFromExchangeException();
  }

}


text:
require 'spec_helper'

RSpec::Matchers.define :have_an_article_written_by do |citizen|
  match do |idea|
    for article in idea.articles
      if article.author == citizen
        return true
      end
    end
    return false
  end
end

describe Admin::ArticlesController do
  let (:administrator) {
    FactoryGirl.create :administrator
  }
  let (:unsaved_article) {
    FactoryGirl.build :article
  }
  let (:article_hash) {{
      :article_type => unsaved_article.article_type,
      :title => unsaved_article.title,
      :ingress => unsaved_article.ingress,
      :body => unsaved_article.body,
      :idea_id => unsaved_article.idea.id
    }}
  let (:citizen) {
    FactoryGirl.create :citizen
  }

  before :each do
    sign_in :administrator, administrator
  end

  describe "GET 'index'" do
    it "returns http success" do
      get 'index'
      response.should be_success
    end
  end

  post :create do
    params {{:article => article_hash}}
    before do
      @article_count = Article.count
      @request.env['HTTP_REFERER'] = new_article_path
    end
    context "with idea ID specified" do
      context "with author name specified like 'John Smith'" do
        params {{:article => article_hash,
            :idea_id => unsaved_article.idea.id,
            :author => citizen.profile.name}}
        it "saves the article" do
          action! do
            its(:response) {should render_template(:create)}
            Article.count.should == @article_count + 1
            idea = unsaved_article.idea
            idea.reload
            idea.should have_an_article_written_by(citizen)
          end
        end
      end
      context "with author name specified like 'Smith, John'" do
        params {{:article => article_hash,
            :idea_id => unsaved_article.idea.id,
            :author => citizen.profile.last_name + ", " +
              citizen.profile.first_name}}
        it "saves the article" do
          action! do
            idea = unsaved_article.idea
            idea.reload
            idea.should have_an_article_written_by(citizen)
          end
        end
      end
      context "with author email address specified instead of the name" do
        params {{:article => article_hash,
            :idea_id => unsaved_article.idea.id,
            :author => citizen.email}}
        it "saves the article" do
          action! do
            idea = unsaved_article.idea
            idea.reload
            idea.should have_an_article_written_by(citizen)
          end
        end
      end
      context "with author name missing" do
        params {{:article => article_hash,
            :idea_id => unsaved_article.idea.id
          }}
        it "does not save the article" do
          action! do
            its(:response) {should be_redirect}
            its(:response) {should redirect_to(new_article_path)}
            Article.count.should == @article_count
            idea = unsaved_article.idea
            idea.reload
            idea.should_not have_an_article_written_by(nil)
          end
        end
      end
      context "with empty author name" do
        params {{:article => article_hash,
            :idea_id => unsaved_article.idea.id,
            :author => ''
          }}
        it "does not save the article" do
          action! do
            Article.count.should == @article_count
          end
        end
      end
      context "with author name that is theoretically valid but absent in the database" do
        params {{:article => article_hash,
            :idea_id => unsaved_article.idea.id,
            :author => "svub rgnvna"
          }}
        it "does not save the article" do
          action! do
            Article.count.should == @article_count
          end
        end
      end
      context "with author email address that is theoretically valid but absent in the database" do
        params {{:article => article_hash,
            :idea_id => unsaved_article.idea.id,
            :author => "gvhj@vkvkkhv.com"
          }}
        it "does not save the article" do
          action! do
            Article.count.should == @article_count
          end
        end
      end
    end
    context "with idea ID missing" do
      params {{:article => article_hash,
          :author => unsaved_article.author.profile.name}}
      it "saves the article" do
        action! do
          idea = unsaved_article.idea
          idea.reload
          idea.should have_an_article_written_by(unsaved_article.author)
        end
      end
    end
  end

end


text:
class Neuron
{
public:
    Neuron(int nbInputs);
    ~Neuron();

    double computeOutput(const std::vector<double>& inputs);

    void updateWeight(int i, double v) {m_prevDeltaWeights[i+1] = v; m_weights[i+1] += v;}
    void updateThreshold(double v) {m_prevDeltaWeights[0] = v; m_weights[0] += v;}

    std::vector<double> weights() const {return std::vector<double>(m_weights.begin()+1, m_weights.end());}
    std::vector<double> prevDeltaWeights() const {return std::vector<double>(m_prevDeltaWeights.begin()+1, m_prevDeltaWeights.end());}
    size_t size() const {return m_weights.size()-1;}
    int inputNb() const {return m_nbInputs;}
    double output() const {return m_output;}

    double threshold() const {return m_weights[0];}
    double weight(int i) const {return m_weights[i+1];}
    double prevDeltaWeight(int i) const {return m_prevDeltaWeights[i+1];}
    double prevDeltaThreshold() const {return m_prevDeltaWeights[0];}
    double delta() const {return m_delta;}

    void threshold(double t) {m_weights[0]=t;}
    void weight(int i, double v) {m_weights[i+1] = v;}
    void prevDeltaWeight(int i, double v) { m_prevDeltaWeights[i+1] = v;}
    void prevDeltaThreshold(double d) { m_prevDeltaWeights[0] = d;}
    void delta(double d) {m_delta=d;}

private:
    static const double MINIMUM_WEIGHT;
    static const double MAXIMUM_WEIGHT;

    static double squashingFunction(double x);

    void initializeWeights();
    void initializePrevDeltaWeights();

    int m_nbInputs;
    double m_delta;
    double m_output;

    std::vector<double> m_weights;
    std::vector<double> m_prevDeltaWeights; // For the momentum
};

#endif // NEURON_H


text:
def mapper(book):
    def checker(page, element):
        width=int(element.get('WIDTH'))
        height=int(element.get('HEIGHT'))
        x=int(element.get('HPOS'))
        y=int(element.get('VPOS'))
        area=width*height
        fracarea=area/(page.width*page.height)
        return page, [width, height, x, y, fracarea]

reducer=merge_under(add)

def shuffler(year, count):
    return year%count


text:
/**
 *
 * ProjectName:pandatravel
 * Description:
 * Created by qimuyunduan on 2017/7/15 .
 * Revise person:qimuyunduan
 * Revise Time:2017/7/15 下午6:25
 * @version
 *
 */
import {createTest,destroyVM} from "../utils";
import info from "../../../src/components/info.vue";

describe('info.vue',() => {
    let vm;
    afterEach(() => {
        destroyVM(vm);
    });
    it("测试元素的属性值",()=>{
        vm = createTest(info,true);
        let divs = vm.$el.querySelectorAll('div');
        let lastDiv = divs[divs.length-1];
        let span = lastDiv.querySelectorAll('span');
        let useEl = span[0].querySelector('use');
        expect(useEl.getAttribute('xlink:href')).equal('#icon-sure');
    });
    it("测试icon click",()=>{
        vm = createTest(info,true);
        let icons = vm.$el.querySelectorAll('.icon');
        let lastSpan = icons[icons.length-1].parentNode;
        let spy = sinon.spy(vm,"close");
        lastSpan.click();
        expect(spy).to.have.been.calledOnce;
        spy.restore();

    });
});


text:
angular.module('orderCloud')
    .factory('PriceBreak', PriceBreakFactory);

function PriceBreakFactory (Underscore) {
    var service = {
        addPriceBreak : addPriceBreak,
        setMinMax: setMinMax,
        deletePriceBreak: deletePriceBreak,
        addDisplayQuantity:addDisplayQuantity
    };

    function setMinMax(priceSchedule) {
            var quantities =  _.pluck(priceSchedule.PriceBreaks, 'Quantity');
            priceSchedule.MinQuantity = _.min(quantities);
        if (priceSchedule.RestrictedQuantity) {
            priceSchedule.MaxQuantity = _.max(quantities);
        }
        return priceSchedule;
    }

    function addPriceBreak( priceSchedule, price, quantity) {
        var numberExist= Underscore.findWhere(priceSchedule.PriceBreaks, {Quantity: quantity});
        if(numberExist === undefined){
            priceSchedule.PriceBreaks.push({Price: price, Quantity: quantity})
        }else{
            throw new Error('Quantity already exists, please delete and re-enter quantity to edit','Error');
        }
        displayQuantity(priceSchedule);
        return setMinMax(priceSchedule);
    }

    function addDisplayQuantity(priceSchedule){
        displayQuantity(priceSchedule);
        return setMinMax(priceSchedule);
    }

    function deletePriceBreak(priceSchedule, index) {
        priceSchedule.PriceBreaks.splice(index, 1);
        return setMinMax(priceSchedule);
    }

    function displayQuantity(priceSchedule){
        //Organize the priceschedule array in order of quantity
        priceSchedule.PriceBreaks.sort(function(a,b){return a.Quantity - b.Quantity});
        //find out the max quantity in the array
        var maxQuantity = Math.max.apply(Math,priceSchedule.PriceBreaks.map(function(object){
            return object.Quantity}));
        // go through each item in the priceschedule array
        for(var i=0; i < priceSchedule.PriceBreaks.length; i++){
            //if max number is unique, display max number  with + symbol
            if(priceSchedule.PriceBreaks[i].Quantity == maxQuantity) {
                priceSchedule.PriceBreaks[i].displayQuantity= priceSchedule.PriceBreaks[i].Quantity + "+";
            }else{
                //otherwise get the range of numbers between the current index quantity , and the next index Quantity
                var itemQuantityRange = Underscore.range(priceSchedule.PriceBreaks[i].Quantity, priceSchedule.PriceBreaks[i + 1].Quantity);
                itemQuantityRange;
                // If the difference between the range of numbers is only 1 . then just display that quantity number
                if(itemQuantityRange.length === 1){
                    priceSchedule.PriceBreaks[i].displayQuantity = itemQuantityRange[0];
                }else{
                    //the last quantity in the array of PriceBreaks minus the 1st quantity in the calculate range is less than or =1 , add only the first number in the Item
                    if(((priceSchedule.PriceBreaks[priceSchedule.PriceBreaks.length-1]).Quantity - itemQuantityRange[0]) <= 1){
                        priceSchedule.PriceBreaks[i].displayQuantity = itemQuantityRange[0];
                        //displays range between two quantities in the array
                    }else{
                        priceSchedule.PriceBreaks[i].displayQuantity = itemQuantityRange[0] + "-" + itemQuantityRange[itemQuantityRange.length-1] ;
                    }
                }
            }
        }
    }
    return service;
}


text:
function varargout = BP_annotate_GUI(varargin)
% BP_ANNOTATE_GUI MATLAB code for BP_annotate_GUI.fig
%      BP_ANNOTATE_GUI, by itself, creates a new BP_ANNOTATE_GUI or raises the existing
%      singleton*.
%
%      H = BP_ANNOTATE_GUI returns the handle to a new BP_ANNOTATE_GUI or the handle to
%      the existing singleton*.
%
%      BP_ANNOTATE_GUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in BP_ANNOTATE_GUI.M with the given input arguments.
%
%      BP_ANNOTATE_GUI('Property','Value',...) creates a new BP_ANNOTATE_GUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before BP_annotate_GUI_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to BP_annotate_GUI_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help BP_annotate_GUI

% Last Modified by GUIDE v2.5 06-Apr-2017 16:42:35

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @BP_annotate_GUI_OpeningFcn, ...
                   'gui_OutputFcn',  @BP_annotate_GUI_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before BP_annotate_GUI is made visible.
function BP_annotate_GUI_OpeningFcn(hObject, eventdata, handles, varargin)
addpath('/Users/alexandrel/Codes/ClinicLab/BP_annotate');
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to BP_annotate_GUI (see VARARGIN)

% Choose default command line output for BP_annotate_GUI
handles.output = hObject;
handles.Colors = [51, 19, 228;...
    246,108,254;...
    230,1,128;...
    106,3,239;...
    161,242,255]./255;
% Update handles structure
guidata(hObject, handles);

% UIWAIT makes BP_annotate_GUI wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = BP_annotate_GUI_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes on button press in loadbutton.
function loadbutton_Callback(hObject, eventdata, handles)
% hObject    handle to loadbutton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% actually load the data
handles.infocentertext.String = 'Loading...';
if isfield(handles,'data')
    handles = rmfield(handles,'data');
end
[handles.FileName,handles.PathName,~] = uigetfile({'*.txt; *.mat','Compatible files'},'Find the data file.');
FilePath = fullfile(handles.PathName, handles.FileName);
handles.data.waveform = load(FilePath);

% ask about data parameters, set them
prompt = {'Enter acquisition frequency (Hz):','Is the data clean? (Y or N):','Enter data units','Very high notch? (Y or N)'};
dlg_title = 'Data parameters';
num_lines = 1;
defaultans = {'1000','Y','mmHg','N'};
answer = inputdlg(prompt,dlg_title,num_lines,defaultans);
handles.data.Fs = str2num(answer{1});
handles.data.isClean = 0;
if regexp(answer{2},'y','ignorecase')
    handles.data.isClean = 1;
end
handles.data.units = 'other';
if regexp(answer{3},'mmhg','ignorecase')
    handles.data.units = 'mmHg';
else
    handles.infocentertext.String = fprintf('Data format %s is unsupported, contact administrator to add support.',answer{3});
end
handles.data.highNotch = 0;
if regexp(answer{4},'y','ignorecase')
    handles.data.highNotch = 1;
end
handles.data.time = (0:length(handles.data.waveform)-1)./handles.data.Fs;

handles = updateAxes(hObject, handles);

handles.infocentertext.String = 'Loading...done.';
% Update handles structure
guidata(hObject, handles);

% --- Executes on button press in annotatebutton.
function annotatebutton_Callback(hObject, eventdata, handles)

handles.infocentertext.String = 'Performing annotations...';
if ~handles.data.highNotch
    [ footIndex, systolicIndex, notchIndex, dicroticIndex, time, waveform ] =...
        BP_annotate( handles.data.waveform, handles.data.Fs, 0, handles.data.units, handles.data.isClean );
else
    [ footIndex, systolicIndex, notchIndex, dicroticIndex, time, waveform ] =...
        BP_annotate_high_notch( handles.data.waveform, handles.data.Fs, 0, handles.data.units, handles.data.isClean );
end
handles.data.bp_annotation.footIndex = footIndex;
handles.data.bp_annotation.systolicIndex = systolicIndex;
handles.data.bp_annotation.notchIndex = notchIndex;
handles.data.bp_annotation.dicroticIndex = dicroticIndex;
handles.data.bp_annotation.time = time;
handles.data.bp_annotation.waveform = waveform;
handles.infocentertext.String = 'Performing annotations...done.';

handles = updateAxes(hObject, handles);
% Update handles structure
guidata(hObject, handles);

% --- Executes on button press in exportbutton.
function exportbutton_Callback(hObject, eventdata, handles)
% hObject    handle to exportbutton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --- Executes on button press in clearbutton.
function clearbutton_Callback(hObject, eventdata, handles)
% hObject    handle to clearbutton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

function handles = updateAxes(hObject, handles)
axes(handles.axes1)
plot(handles.data.time, handles.data.waveform)
xlim([handles.data.time(1) handles.data.time(end)])
box off
xlabel('time (s)')
ylabel(['pressure (',handles.data.units,')'])
legend('waveform')
if isfield(handles.data,'bp_annotation')
    cla; hold on;
    plot(handles.data.bp_annotation.time, handles.data.bp_annotation.waveform,'Color',handles.Colors(1,:))
    plot(handles.data.bp_annotation.time(handles.data.bp_annotation.footIndex),...
        handles.data.bp_annotation.waveform(handles.data.bp_annotation.footIndex),...
        'v','Color',handles.Colors(2,:),'MarkerFaceColor',handles.Colors(2,:));
    plot(handles.data.bp_annotation.time(handles.data.bp_annotation.systolicIndex),...
        handles.data.bp_annotation.waveform(handles.data.bp_annotation.systolicIndex),...
        '^','Color',handles.Colors(3,:),'MarkerFaceColor',handles.Colors(3,:));
    plot(handles.data.bp_annotation.time(handles.data.bp_annotation.notchIndex),...
        handles.data.bp_annotation.waveform(handles.data.bp_annotation.notchIndex),...
        '>','Color',handles.Colors(4,:),'MarkerFaceColor',handles.Colors(4,:));
    legend({'waveform','foot','systole','notch'})
end

linkaxes([handles.axes1,handles.axes5,handles.axes4]);
% Update handles structure
guidata(hObject, handles);


text:
/**
 * Created by kikimans on 2015. 5. 20..
 */
console.log('Hello World');


text:
namespace app { namespace Uno { namespace Net { namespace Http { struct HttpMessageHandlerRequest; } } } }
namespace app { namespace Uno { struct Buffer; } }

namespace app {
namespace Experimental {
namespace Http {

struct BinaryLoader;

struct BinaryLoader__uType : ::app::Experimental::Http::Loader__uType
{
};

BinaryLoader__uType* BinaryLoader__typeof();

void BinaryLoader___ObjInit_1(BinaryLoader* __this);
void BinaryLoader__CompleteLoading(BinaryLoader* __this, ::app::Uno::Net::Http::HttpMessageHandlerRequest* resp);
void BinaryLoader__LoadCacheData(BinaryLoader* __this);
bool BinaryLoader__LoadCacheRaw(BinaryLoader* __this, ::uObject* record);
BinaryLoader* BinaryLoader__New_1(::uStatic* __this);
void BinaryLoader__OnBufferLoaded(BinaryLoader* __this, ::uArray* data);
void BinaryLoader__PrepareRequest(BinaryLoader* __this, ::app::Uno::Net::Http::HttpMessageHandlerRequest* request);

struct BinaryLoader : ::app::Experimental::Http::Loader
{
    ::uStrong< ::uDelegate*> Callback;
    ::uStrong< ::app::Uno::Buffer*> _loadedCache;

    void _ObjInit_1() { BinaryLoader___ObjInit_1(this); }
    void OnBufferLoaded(::uArray* data) { BinaryLoader__OnBufferLoaded(this, data); }
};

}}}

#endif


text: from .config import stores_loader


text:
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.Network.Models;

namespace Azure.ResourceManager.Network
{
    /// <summary> Creates a VirtualHub resource if it doesn't exist else updates the existing VirtualHub. </summary>
    public partial class VirtualHubsCreateOrUpdateOperation : Operation<VirtualHub>, IOperationSource<VirtualHub>
    {
        private readonly ArmOperationHelpers<VirtualHub> _operation;
        internal VirtualHubsCreateOrUpdateOperation(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Request request, Response response)
        {
            _operation = new ArmOperationHelpers<VirtualHub>(this, clientDiagnostics, pipeline, request, response, OperationFinalStateVia.AzureAsyncOperation, "VirtualHubsCreateOrUpdateOperation");
        }
        /// <inheritdoc />
        public override string Id => _operation.Id;

        /// <inheritdoc />
        public override VirtualHub Value => _operation.Value;

        /// <inheritdoc />
        public override bool HasCompleted => _operation.HasCompleted;

        /// <inheritdoc />
        public override bool HasValue => _operation.HasValue;

        /// <inheritdoc />
        public override Response GetRawResponse() => _operation.GetRawResponse();

        /// <inheritdoc />
        public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken);

        /// <inheritdoc />
        public override ValueTask<Response> UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken);

        /// <inheritdoc />
        public override ValueTask<Response<VirtualHub>> WaitForCompletionAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(cancellationToken);

        /// <inheritdoc />
        public override ValueTask<Response<VirtualHub>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(pollingInterval, cancellationToken);

        VirtualHub IOperationSource<VirtualHub>.CreateResult(Response response, CancellationToken cancellationToken)
        {
            using var document = JsonDocument.Parse(response.ContentStream);
            if (document.RootElement.ValueKind == JsonValueKind.Null)
            {
                return null;
            }
            else
            {
                return VirtualHub.DeserializeVirtualHub(document.RootElement);
            }
        }

        async ValueTask<VirtualHub> IOperationSource<VirtualHub>.CreateResultAsync(Response response, CancellationToken cancellationToken)
        {
            using var document = await JsonDocument.ParseAsync(response.ContentStream, default, cancellationToken).ConfigureAwait(false);
            if (document.RootElement.ValueKind == JsonValueKind.Null)
            {
                return null;
            }
            else
            {
                return VirtualHub.DeserializeVirtualHub(document.RootElement);
            }
        }
    }
}


text: Tests JSON parsing.


text:
importScripts('https://cdn.rawgit.com/zhuker/lamejs/c318d57d/lame.min.js');

var MP3encoder = new lamejs.Mp3Encoder(1, 48000, 256);

function QBAudioRecorderWorker() {
    var self = this;

    self.bufferChunks = [];
    self.bufferSize = 0;
    self.sampleRate = 0;
    self.mimeType = '';

    onmessage = function(event) {
        self.onMessage(event.data);
    };
}

QBAudioRecorderWorker.prototype = {
    postMessage: function(data) {
        postMessage(data);
    },

    onMessage: function(data) {
        var self = this;

        switch (data.cmd) {
            case 'init':
                self.mimeType = data.mimeType;
                self.sampleRate = data.sampleRate;
                self.bufferChunks = [];
                self.bufferSize = 0;
                break;
            case 'record':
                self.bufferChunks.push(new Float32Array(data.bufferChunk));
                self.bufferSize += data.bufferSize;
                break;
            case 'finish':
                self.postMessage(self.getBlobData());
                break;
        }
    },

    encodeWAV: function(samples) {
        var buffer = new ArrayBuffer(44 + samples.length * 2),
            view = new DataView(buffer);

        _writeString(view, 0, 'RIFF');
        view.setUint32(4, 32 + samples.length * 2, true);
        _writeString(view, 8, 'WAVE');
        _writeString(view, 12, 'fmt ');
        view.setUint32(16, 16, true);
        view.setUint16(20, 1, true);
        view.setUint16(22, 1, true);
        view.setUint32(24, this.sampleRate, true);
        view.setUint32(28, this.sampleRate * 2, true);
        view.setUint16(32, 2, true);
        view.setUint16(34, 16, true);
        _writeString(view, 36, 'data');
        view.setUint32(40, samples.length * 2, true);

        _floatTo16BitPCM(view, 44, samples);

        function _floatTo16BitPCM(output, offset, input) {
            for (var i = 0; i < input.length; i++, offset += 2) {
                var s = Math.max(-1, Math.min(1, input[i]));
                output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);
            }
        }

        function _writeString(view, offset, string) {
            for (var i = 0; i < string.length; i++) {
                view.setUint8(offset + i, string.charCodeAt(i));
            }
        }

        return view;
    },

    encodeMP3: function(buffer) {
        var data = new Int16Array(buffer),
            encodedBuffer = MP3encoder.encodeBuffer(data),
            flushedBuffer = MP3encoder.flush(),
            mp3Data = [];

        mp3Data.push(encodedBuffer);
        mp3Data.push(new Int8Array(flushedBuffer));

        return mp3Data;
    },

    getBlobData: function() {
        var self = this,
            result = new Float32Array(self.bufferSize),
            bufferLength = self.bufferChunks.length,
            offset = 0,
            buffer,
            view,
            data;

        for (var i = 0; i < bufferLength; i++) {
            buffer = self.bufferChunks[i];
            result.set(buffer, offset);
            offset += buffer.length;
        }

        view = self.encodeWAV(result);

        switch (self.mimeType) {
            case 'audio/wav':
                data = [view];
                break;

            case 'audio/mp3':
                data = self.encodeMP3(view.buffer);
                break;

            default:
                throw new Error();
        }

        return data;
    }
};

new QBAudioRecorderWorker();