text:
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.content.browser;

import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.SurfaceTexture;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Pair;
import android.view.Surface;

import org.chromium.base.CommandLine;
import org.chromium.base.CpuFeatures;
import org.chromium.base.Log;
import org.chromium.base.ThreadUtils;
import org.chromium.base.TraceEvent;
import org.chromium.base.VisibleForTesting;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.library_loader.Linker;
import org.chromium.content.app.ChromiumLinkerParams;
import org.chromium.content.app.PrivilegedProcessService;
import org.chromium.content.app.SandboxedProcessService;
import org.chromium.content.common.ContentSwitches;
import org.chromium.content.common.FileDescriptorInfo;
import org.chromium.content.common.IChildProcessCallback;
import org.chromium.content.common.SurfaceWrapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;

/**
 * This class provides the method to start/stop ChildProcess called by native.
 */
@JNINamespace("content")
public class ChildProcessLauncher {
    private static final String TAG = "ChildProcLauncher";

    static final int CALLBACK_FOR_UNKNOWN_PROCESS = 0;
    static final int CALLBACK_FOR_GPU_PROCESS = 1;
    static final int CALLBACK_FOR_RENDERER_PROCESS = 2;
    static final int CALLBACK_FOR_UTILITY_PROCESS = 3;

    private static class ChildConnectionAllocator {
        // Connections to services. Indices of the array correspond to the service numbers.
        private final ChildProcessConnection[] mChildProcessConnections;

        // The list of free (not bound) service indices.
        // SHOULD BE ACCESSED WITH mConnectionLock.
        private final ArrayList<Integer> mFreeConnectionIndices;
        private final Object mConnectionLock = new Object();

        private final String mChildClassName;
        private final boolean mInSandbox;
        // Each Allocator keeps a queue for the pending spawn data. Once a connection is free, we
        // dequeue the pending spawn data from the same allocator as the connection.
        private final PendingSpawnQueue mPendingSpawnQueue = new PendingSpawnQueue();

        public ChildConnectionAllocator(boolean inSandbox, int numChildServices,
                String serviceClassName) {
            mChildProcessConnections = new ChildProcessConnectionImpl[numChildServices];
            mFreeConnectionIndices = new ArrayList<Integer>(numChildServices);
            for (int i = 0; i < numChildServices; i++) {
                mFreeConnectionIndices.add(i);
            }
            mChildClassName = serviceClassName;
            mInSandbox = inSandbox;
        }

        public ChildProcessConnection allocate(
                Context context, ChildProcessConnection.DeathCallback deathCallback,
                ChromiumLinkerParams chromiumLinkerParams,
                boolean alwaysInForeground,
                ChildProcessCreationParams creationParams) {
            synchronized (mConnectionLock) {
                if (mFreeConnectionIndices.isEmpty()) {
                    Log.d(TAG, "Ran out of services to allocate.");
                    return null;
                }
                int slot = mFreeConnectionIndices.remove(0);
                assert mChildProcessConnections[slot] == null;
                mChildProcessConnections[slot] = new ChildProcessConnectionImpl(context, slot,
                        mInSandbox, deathCallback, mChildClassName, chromiumLinkerParams,
                        alwaysInForeground, creationParams);
                Log.d(TAG, "Allocator allocated a connection, sandbox: %b, slot: %d", mInSandbox,
                        slot);
                return mChildProcessConnections[slot];
            }
        }

        public void free(ChildProcessConnection connection) {
            synchronized (mConnectionLock) {
                int slot = connection.getServiceNumber();
                if (mChildProcessConnections[slot] != connection) {
                    int occupier = mChildProcessConnections[slot] == null
                            ? -1 : mChildProcessConnections[slot].getServiceNumber();
                    Log.e(TAG, "Unable to find connection to free in slot: %d "
                            + "already occupied by service: %d", slot, occupier);
                    assert false;
                } else {
                    mChildProcessConnections[slot] = null;
                    assert !mFreeConnectionIndices.contains(slot);
                    mFreeConnectionIndices.add(slot);
                    Log.d(TAG, "Allocator freed a connection, sandbox: %b, slot: %d", mInSandbox,
                            slot);
                }
            }
        }

        public boolean isFreeConnectionAvailable() {
            synchronized (mConnectionLock) {
                return !mFreeConnectionIndices.isEmpty();
            }
        }

        public PendingSpawnQueue getPendingSpawnQueue() {
            return mPendingSpawnQueue;
        }

        /** @return the count of connections managed by the allocator */
        @VisibleForTesting
        int allocatedConnectionsCountForTesting() {
            return mChildProcessConnections.length - mFreeConnectionIndices.size();
        }
    }

    private static class PendingSpawnData {
        private final Context mContext;
        private final String[] mCommandLine;
        private final int mChildProcessId;
        private final FileDescriptorInfo[] mFilesToBeMapped;
        private final long mClientContext;
        private final int mCallbackType;
        private final boolean mInSandbox;
        private final ChildProcessCreationParams mCreationParams;

        private PendingSpawnData(
                Context context,
                String[] commandLine,
                int childProcessId,
                FileDescriptorInfo[] filesToBeMapped,
                long clientContext,
                int callbackType,
                boolean inSandbox,
                ChildProcessCreationParams creationParams) {
            mContext = context;
            mCommandLine = commandLine;
            mChildProcessId = childProcessId;
            mFilesToBeMapped = filesToBeMapped;
            mClientContext = clientContext;
            mCallbackType = callbackType;
            mInSandbox = inSandbox;
            mCreationParams = creationParams;
        }

        private Context context() {
            return mContext;
        }
        private String[] commandLine() {
            return mCommandLine;
        }
        private int childProcessId() {
            return mChildProcessId;
        }
        private FileDescriptorInfo[] filesToBeMapped() {
            return mFilesToBeMapped;
        }
        private long clientContext() {
            return mClientContext;
        }
        private int callbackType() {
            return mCallbackType;
        }
        private boolean inSandbox() {
            return mInSandbox;
        }
        private ChildProcessCreationParams getCreationParams() {
            return mCreationParams;
        }
    }

    private static class PendingSpawnQueue {
        // The list of pending process spawn requests and its lock.
        // Operations on this queue must be atomical w.r.t. free connections updates.
        private Queue<PendingSpawnData> mPendingSpawns = new LinkedList<PendingSpawnData>();
        final Object mPendingSpawnsLock = new Object();

        /**
         * Queue up a spawn requests to be processed once a free service is available.
         * Called when a spawn is requested while we are at the capacity.
         */
        public void enqueueLocked(final PendingSpawnData pendingSpawn) {
            assert Thread.holdsLock(mPendingSpawnsLock);
            mPendingSpawns.add(pendingSpawn);
        }

        /**
         * Pop the next request from the queue. Called when a free service is available.
         * @return the next spawn request waiting in the queue.
         */
        public PendingSpawnData dequeueLocked() {
            assert Thread.holdsLock(mPendingSpawnsLock);
            return mPendingSpawns.poll();
        }

        /** @return the count of pending spawns in the queue */
        public int sizeLocked() {
            assert Thread.holdsLock(mPendingSpawnsLock);
            return mPendingSpawns.size();
        }
    }

    // Service class for child process.
    // Map from package name to ChildConnectionAllocator.
    private static Map<String, ChildConnectionAllocator> sSandboxedChildConnectionAllocatorMap;
    // As the default value it uses PrivilegedProcessService0.
    private static ChildConnectionAllocator sPrivilegedChildConnectionAllocator;

    private static final String NUM_SANDBOXED_SERVICES_KEY =
            "org.chromium.content.browser.NUM_SANDBOXED_SERVICES";
    private static final String NUM_PRIVILEGED_SERVICES_KEY =
            "org.chromium.content.browser.NUM_PRIVILEGED_SERVICES";
    private static final String SANDBOXED_SERVICES_NAME_KEY =
            "org.chromium.content.browser.SANDBOXED_SERVICES_NAME";
    // Overrides the number of available sandboxed services.
    @VisibleForTesting
    public static final String SWITCH_NUM_SANDBOXED_SERVICES_FOR_TESTING = "num-sandboxed-services";
    public static final String SWITCH_SANDBOXED_SERVICES_NAME_FOR_TESTING =
            "sandboxed-services-name";

    private static int getNumberOfServices(Context context, boolean inSandbox, String packageName) {
        int numServices = -1;
        if (inSandbox
                && CommandLine.getInstance().hasSwitch(
                           SWITCH_NUM_SANDBOXED_SERVICES_FOR_TESTING)) {
            String value = CommandLine.getInstance().getSwitchValue(
                    SWITCH_NUM_SANDBOXED_SERVICES_FOR_TESTING);
            if (!TextUtils.isEmpty(value)) {
                try {
                    numServices = Integer.parseInt(value);
                } catch (NumberFormatException e) {
                    Log.w(TAG, "The value of --num-sandboxed-services is formatted wrongly: "
                                    + value);
                }
            }
        } else {
            try {
                PackageManager packageManager = context.getPackageManager();
                ApplicationInfo appInfo = packageManager.getApplicationInfo(packageName,
                        PackageManager.GET_META_DATA);
                if (appInfo.metaData != null) {
                    numServices = appInfo.metaData.getInt(inSandbox
                            ? NUM_SANDBOXED_SERVICES_KEY : NUM_PRIVILEGED_SERVICES_KEY, -1);
                }
            } catch (PackageManager.NameNotFoundException e) {
                throw new RuntimeException("Could not get application info");
            }
        }
        if (numServices < 0) {
            throw new RuntimeException("Illegal meta data value for number of child services");
        }
        return numServices;
    }

    private static String getClassNameOfService(Context context, boolean inSandbox,
            String packageName) {
        if (!inSandbox) {
            return PrivilegedProcessService.class.getName();
        }
        if (CommandLine.getInstance().hasSwitch(SWITCH_SANDBOXED_SERVICES_NAME_FOR_TESTING)) {
            return CommandLine.getInstance().getSwitchValue(
                    SWITCH_SANDBOXED_SERVICES_NAME_FOR_TESTING);
        }

        String serviceName = null;
        try {
            PackageManager packageManager = context.getPackageManager();
            ApplicationInfo appInfo =
                    packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
            if (appInfo.metaData != null) {
                serviceName = appInfo.metaData.getString(SANDBOXED_SERVICES_NAME_KEY);
            }
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException("Could not get application info.");
        }

        if (serviceName != null) {
            // Check that the service exists.
            try {
                PackageManager packageManager = context.getPackageManager();
                // PackageManager#getServiceInfo() throws an exception if the service does not
                // exist.
                packageManager.getServiceInfo(new ComponentName(packageName, serviceName + "0"), 0);
                return serviceName;
            } catch (PackageManager.NameNotFoundException e) {
                throw new RuntimeException(
                        "Illegal meta data value: the child service doesn't exist");
            }
        }
        return SandboxedProcessService.class.getName();
    }

    private static void initConnectionAllocatorsIfNecessary(
            Context context, boolean inSandbox, String packageName) {
        // TODO(mariakhomenko): Uses an Object to lock the access.
        synchronized (ChildProcessLauncher.class) {
            if (inSandbox) {
                if (sSandboxedChildConnectionAllocatorMap == null) {
                    sSandboxedChildConnectionAllocatorMap =
                            new ConcurrentHashMap<String, ChildConnectionAllocator>();
                }
                if (!sSandboxedChildConnectionAllocatorMap.containsKey(packageName)) {
                    Log.w(TAG, "Create a new ChildConnectionAllocator with package name = %s,"
                                    + " inSandbox = true",
                            packageName);
                    sSandboxedChildConnectionAllocatorMap.put(packageName,
                            new ChildConnectionAllocator(true,
                                    getNumberOfServices(context, true, packageName),
                                    getClassNameOfService(context, true, packageName)));
                }
            } else if (sPrivilegedChildConnectionAllocator == null) {
                sPrivilegedChildConnectionAllocator = new ChildConnectionAllocator(false,
                        getNumberOfServices(context, false, packageName),
                        getClassNameOfService(context, false, packageName));
            }
            // TODO(pkotwicz|hanxi): Figure out when old allocators should be removed from
            // {@code sSandboxedChildConnectionAllocatorMap}.
        }
    }

    /**
     * Note: please make sure that the Allocator has been initialized before calling this function.
     * Otherwise, always calls {@link initConnectionAllocatorsIfNecessary} first.
     */
    private static ChildConnectionAllocator getConnectionAllocator(
            String packageName, boolean inSandbox) {
        if (!inSandbox) {
            return sPrivilegedChildConnectionAllocator;
        }
        return sSandboxedChildConnectionAllocatorMap.get(packageName);
    }

    /**
     * Get the PendingSpawnQueue of the Allocator. Initialize the Allocator if needed.
     */
    private static PendingSpawnQueue getPendingSpawnQueue(Context context, String packageName,
            boolean inSandbox) {
        initConnectionAllocatorsIfNecessary(context, inSandbox, packageName);
        return getConnectionAllocator(packageName, inSandbox).getPendingSpawnQueue();
    }

    private static ChildProcessConnection allocateConnection(Context context, boolean inSandbox,
            ChromiumLinkerParams chromiumLinkerParams, boolean alwaysInForeground,
            ChildProcessCreationParams creationParams) {
        ChildProcessConnection.DeathCallback deathCallback =
                new ChildProcessConnection.DeathCallback() {
                    @Override
                    public void onChildProcessDied(ChildProcessConnection connection) {
                        if (connection.getPid() != 0) {
                            stop(connection.getPid());
                        } else {
                            freeConnection(connection);
                        }
                    }
                };
        String packageName = creationParams != null ? creationParams.getPackageName()
                : context.getPackageName();
        initConnectionAllocatorsIfNecessary(context, inSandbox, packageName);
        return getConnectionAllocator(packageName, inSandbox)
                .allocate(context, deathCallback, chromiumLinkerParams, alwaysInForeground,
                        creationParams);
    }

    private static boolean sLinkerInitialized = false;
    private static long sLinkerLoadAddress = 0;

    private static ChromiumLinkerParams getLinkerParamsForNewConnection() {
        if (!sLinkerInitialized) {
            if (Linker.isUsed()) {
                sLinkerLoadAddress = Linker.getInstance().getBaseLoadAddress();
                if (sLinkerLoadAddress == 0) {
                    Log.i(TAG, "Shared RELRO support disabled!");
                }
            }
            sLinkerInitialized = true;
        }

        if (sLinkerLoadAddress == 0) return null;

        // Always wait for the shared RELROs in service processes.
        final boolean waitForSharedRelros = true;
        if (Linker.areTestsEnabled()) {
            Linker linker = Linker.getInstance();
            return new ChromiumLinkerParams(sLinkerLoadAddress,
                                            waitForSharedRelros,
                                            linker.getTestRunnerClassNameForTesting(),
                                            linker.getImplementationForTesting());
        } else {
            return new ChromiumLinkerParams(sLinkerLoadAddress,
                                            waitForSharedRelros);
        }
    }

    private static ChildProcessConnection allocateBoundConnection(Context context,
            String[] commandLine, boolean inSandbox, boolean alwaysInForeground,
            ChildProcessCreationParams creationParams) {
        ChromiumLinkerParams chromiumLinkerParams = getLinkerParamsForNewConnection();
        ChildProcessConnection connection = allocateConnection(
                context, inSandbox, chromiumLinkerParams, alwaysInForeground, creationParams);
        if (connection != null) {
            connection.start(commandLine);

            String packageName = creationParams != null ? creationParams.getPackageName()
                    : context.getPackageName();
            if (inSandbox && !getConnectionAllocator(packageName, inSandbox)
                    .isFreeConnectionAvailable()) {
                // Proactively releases all the moderate bindings once all the sandboxed services
                // are allocated, which will be very likely to have some of them killed by OOM
                // killer.
                sBindingManager.releaseAllModerateBindings();
            }
        }
        return connection;
    }

    private static final long FREE_CONNECTION_DELAY_MILLIS = 1;

    private static void freeConnection(ChildProcessConnection connection) {
        synchronized (ChildProcessLauncher.class) {
            if (connection.equals(sSpareSandboxedConnection)) sSpareSandboxedConnection = null;
        }

        // Freeing a service should be delayed. This is so that we avoid immediately reusing the
        // freed service (see http://crbug.com/164069): the framework might keep a service process
        // alive when it's been unbound for a short time. If a new connection to the same service
        // is bound at that point, the process is reused and bad things happen (mostly static
        // variables are set when we don't expect them to).
        final ChildProcessConnection conn = connection;
        ThreadUtils.postOnUiThreadDelayed(new Runnable() {
            @Override
            public void run() {
                final PendingSpawnData pendingSpawn = freeConnectionAndDequeuePending(conn);
                if (pendingSpawn != null) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            startInternal(pendingSpawn.context(), pendingSpawn.commandLine(),
                                    pendingSpawn.childProcessId(), pendingSpawn.filesToBeMapped(),
                                    pendingSpawn.clientContext(), pendingSpawn.callbackType(),
                                    pendingSpawn.inSandbox(), pendingSpawn.getCreationParams());
                        }
                    }).start();
                }
            }
        }, FREE_CONNECTION_DELAY_MILLIS);
    }

    private static PendingSpawnData freeConnectionAndDequeuePending(ChildProcessConnection conn) {
        ChildConnectionAllocator allocator = getConnectionAllocator(
                conn.getPackageName(), conn.isInSandbox());
        assert allocator != null;
        PendingSpawnQueue pendingSpawnQueue = allocator.getPendingSpawnQueue();
        synchronized (pendingSpawnQueue.mPendingSpawnsLock) {
            allocator.free(conn);
            return pendingSpawnQueue.dequeueLocked();
        }
    }

    // Represents an invalid process handle; same as base/process/process.h kNullProcessHandle.
    private static final int NULL_PROCESS_HANDLE = 0;

    // Map from pid to ChildService connection.
    private static Map<Integer, ChildProcessConnection> sServiceMap =
            new ConcurrentHashMap<Integer, ChildProcessConnection>();

    // A pre-allocated and pre-bound connection ready for connection setup, or null.
    private static ChildProcessConnection sSpareSandboxedConnection = null;

    // Manages oom bindings used to bind chind services.
    private static BindingManager sBindingManager = BindingManagerImpl.createBindingManager();

    // Map from surface texture id to Surface.
    private static Map<Pair<Integer, Integer>, Surface> sSurfaceTextureSurfaceMap =
            new ConcurrentHashMap<Pair<Integer, Integer>, Surface>();

    // Whether the main application is currently brought to the foreground.
    private static boolean sApplicationInForeground = true;

    @VisibleForTesting
    public static void setBindingManagerForTesting(BindingManager manager) {
        sBindingManager = manager;
    }

    /** @return true iff the child process is protected from out-of-memory killing */
    @CalledByNative
    private static boolean isOomProtected(int pid) {
        return sBindingManager.isOomProtected(pid);
    }

    private static void registerSurfaceTextureSurface(
            int surfaceTextureId, int clientId, Surface surface) {
        Pair<Integer, Integer> key = new Pair<Integer, Integer>(surfaceTextureId, clientId);
        sSurfaceTextureSurfaceMap.put(key, surface);
    }

    private static void unregisterSurfaceTextureSurface(int surfaceTextureId, int clientId) {
        Pair<Integer, Integer> key = new Pair<Integer, Integer>(surfaceTextureId, clientId);
        Surface surface = sSurfaceTextureSurfaceMap.remove(key);
        if (surface == null) return;

        assert surface.isValid();
        surface.release();
    }

    @CalledByNative
    private static void createSurfaceTextureSurface(
            int surfaceTextureId, int clientId, SurfaceTexture surfaceTexture) {
        registerSurfaceTextureSurface(surfaceTextureId, clientId, new Surface(surfaceTexture));
    }

    @CalledByNative
    private static void destroySurfaceTextureSurface(int surfaceTextureId, int clientId) {
        unregisterSurfaceTextureSurface(surfaceTextureId, clientId);
    }

    @CalledByNative
    private static SurfaceWrapper getSurfaceTextureSurface(
            int surfaceTextureId, int clientId) {
        Pair<Integer, Integer> key = new Pair<Integer, Integer>(surfaceTextureId, clientId);

        Surface surface = sSurfaceTextureSurfaceMap.get(key);
        if (surface == null) {
            Log.e(TAG, "Invalid Id for surface texture.");
            return null;
        }
        assert surface.isValid();
        return new SurfaceWrapper(surface);
    }

    /**
     * Sets the visibility of the child process when it changes or when it is determined for the
     * first time.
     */
    @CalledByNative
    public static void setInForeground(int pid, boolean inForeground) {
        sBindingManager.setInForeground(pid, inForeground);
    }

    /**
     * Called when the renderer commits a navigation. This signals a time at which it is safe to
     * rely on renderer visibility signalled through setInForeground. See http://crbug.com/421041.
     */
    public static void determinedVisibility(int pid) {
        sBindingManager.determinedVisibility(pid);
    }

    /**
     * Called when the embedding application is sent to background.
     */
    public static void onSentToBackground() {
        sApplicationInForeground = false;
        sBindingManager.onSentToBackground();
    }

    /**
     * Starts moderate binding management.
     * Note: WebAPKs and non WebAPKs share the same moderate binding pool, so the size of the
     * shared moderate binding pool is always set based on the number of sandboxes processes
     * used by Chrome.
     * @param context Android's context.
     * @param moderateBindingTillBackgrounded true if the BindingManager should add a moderate
     * binding to a render process when it is created and remove the moderate binding when Chrome is
     * sent to the background.
     */
    public static void startModerateBindingManagement(
            Context context, boolean moderateBindingTillBackgrounded) {
        sBindingManager.startModerateBindingManagement(context,
                getNumberOfServices(context, true, context.getPackageName()),
                moderateBindingTillBackgrounded);
    }

    /**
     * Called when the embedding application is brought to foreground.
     */
    public static void onBroughtToForeground() {
        sApplicationInForeground = true;
        sBindingManager.onBroughtToForeground();
    }

    /**
     * Returns whether the application is currently in the foreground.
     */
    static boolean isApplicationInForeground() {
        return sApplicationInForeground;
    }

    /**
     * Should be called early in startup so the work needed to spawn the child process can be done
     * in parallel to other startup work. Must not be called on the UI thread. Spare connection is
     * created in sandboxed child process.
     * @param context the application context used for the connection.
     */
    public static void warmUp(Context context) {
        synchronized (ChildProcessLauncher.class) {
            assert !ThreadUtils.runningOnUiThread();
            if (sSpareSandboxedConnection == null) {
                ChildProcessCreationParams params = ChildProcessCreationParams.get();
                if (params != null) {
                    params = params.copy();
                }
                sSpareSandboxedConnection = allocateBoundConnection(context, null, true, false,
                        params);
            }
        }
    }

    @CalledByNative
    private static FileDescriptorInfo makeFdInfo(
            int id, int fd, boolean autoClose, long offset, long size) {
        ParcelFileDescriptor pFd;
        if (autoClose) {
            // Adopt the FD, it will be closed when we close the ParcelFileDescriptor.
            pFd = ParcelFileDescriptor.adoptFd(fd);
        } else {
            try {
                pFd = ParcelFileDescriptor.fromFd(fd);
            } catch (IOException e) {
                Log.e(TAG, "Invalid FD provided for process connection, aborting connection.", e);
                return null;
            }
        }
        return new FileDescriptorInfo(id, pFd, offset, size);
    }

    /**
     * Spawns and connects to a child process. May be called on any thread. It will not block, but
     * will instead callback to {@link #nativeOnChildProcessStarted} when the connection is
     * established. Note this callback will not necessarily be from the same thread (currently it
     * always comes from the main thread).
     *
     * @param context Context used to obtain the application context.
     * @param commandLine The child process command line argv.
     * @param filesToBeMapped File IDs, FDs, offsets, and lengths to pass through.
     * @param clientContext Arbitrary parameter used by the client to distinguish this connection.
     */
    @CalledByNative
    private static void start(Context context, final String[] commandLine, int childProcessId,
            FileDescriptorInfo[] filesToBeMapped, long clientContext) {
        assert clientContext != 0;

        int callbackType = CALLBACK_FOR_UNKNOWN_PROCESS;
        boolean inSandbox = true;
        String processType =
                ContentSwitches.getSwitchValue(commandLine, ContentSwitches.SWITCH_PROCESS_TYPE);
        ChildProcessCreationParams params = ChildProcessCreationParams.get();
        if (params != null) {
            params = params.copy();
        }
        if (ContentSwitches.SWITCH_RENDERER_PROCESS.equals(processType)) {
            callbackType = CALLBACK_FOR_RENDERER_PROCESS;
        } else {
            if (params != null && !params.getPackageName().equals(context.getPackageName())) {
                // WebViews and WebAPKs have renderer processes running in their applications.
                // When launching these renderer processes, {@link ChildProcessConnectionImpl}
                // requires the package name of the application which holds the renderer process.
                // Therefore, the package name in ChildProcessCreationParams could be the package
                // name of WebViews, WebAPKs, or Chrome, depending on the host application.
                // Except renderer process, all other child processes should use Chrome's package
                // name. In WebAPK, ChildProcessCreationParams are initialized with WebAPK's
                // package name. Make a copy of the WebAPK's params, but replace the package with
                // Chrome's package to use when initializing a non-renderer processes.
                params = new ChildProcessCreationParams(context.getPackageName(),
                        params.getIsExternalService(), params.getLibraryProcessType());
            }
            if (ContentSwitches.SWITCH_GPU_PROCESS.equals(processType)) {
                callbackType = CALLBACK_FOR_GPU_PROCESS;
                inSandbox = false;
            } else if (ContentSwitches.SWITCH_UTILITY_PROCESS.equals(processType)) {
                // We only support sandboxed right now.
                callbackType = CALLBACK_FOR_UTILITY_PROCESS;
            } else {
                assert false;
            }
        }

        startInternal(context, commandLine, childProcessId, filesToBeMapped, clientContext,
                callbackType, inSandbox, params);
    }

    private static void startInternal(
            Context context,
            final String[] commandLine,
            int childProcessId,
            FileDescriptorInfo[] filesToBeMapped,
            long clientContext,
            int callbackType,
            boolean inSandbox,
            ChildProcessCreationParams creationParams) {
        try {
            TraceEvent.begin("ChildProcessLauncher.startInternal");

            ChildProcessConnection allocatedConnection = null;
            String packageName = creationParams != null ? creationParams.getPackageName()
                    : context.getPackageName();
            synchronized (ChildProcessLauncher.class) {
                if (inSandbox && sSpareSandboxedConnection != null
                        && sSpareSandboxedConnection.getPackageName().equals(packageName)) {
                    allocatedConnection = sSpareSandboxedConnection;
                    sSpareSandboxedConnection = null;
                }
            }
            if (allocatedConnection == null) {
                boolean alwaysInForeground = false;
                if (callbackType == CALLBACK_FOR_GPU_PROCESS) alwaysInForeground = true;
                PendingSpawnQueue pendingSpawnQueue = getPendingSpawnQueue(
                        context, packageName, inSandbox);
                synchronized (pendingSpawnQueue.mPendingSpawnsLock) {
                    allocatedConnection = allocateBoundConnection(
                            context, commandLine, inSandbox, alwaysInForeground, creationParams);
                    if (allocatedConnection == null) {
                        Log.d(TAG, "Allocation of new service failed. Queuing up pending spawn.");
                        pendingSpawnQueue.enqueueLocked(new PendingSpawnData(context, commandLine,
                                childProcessId, filesToBeMapped, clientContext,
                                callbackType, inSandbox, creationParams));
                        return;
                    }
                }
            }

            Log.d(TAG, "Setting up connection to process: slot=%d",
                    allocatedConnection.getServiceNumber());
            triggerConnectionSetup(allocatedConnection, commandLine, childProcessId,
                    filesToBeMapped, callbackType, clientContext);
        } finally {
            TraceEvent.end("ChildProcessLauncher.startInternal");
        }
    }

    /**
     * Create the common bundle to be passed to child processes.
     * @param context Application context.
     * @param commandLine Command line params to be passed to the service.
     * @param linkerParams Linker params to start the service.
     */
    protected static Bundle createsServiceBundle(
            String[] commandLine, FileDescriptorInfo[] filesToBeMapped, Bundle sharedRelros) {
        Bundle bundle = new Bundle();
        bundle.putStringArray(ChildProcessConstants.EXTRA_COMMAND_LINE, commandLine);
        bundle.putParcelableArray(ChildProcessConstants.EXTRA_FILES, filesToBeMapped);
        bundle.putInt(ChildProcessConstants.EXTRA_CPU_COUNT, CpuFeatures.getCount());
        bundle.putLong(ChildProcessConstants.EXTRA_CPU_FEATURES, CpuFeatures.getMask());
        bundle.putBundle(Linker.EXTRA_LINKER_SHARED_RELROS, sharedRelros);
        return bundle;
    }

    @VisibleForTesting
    static void triggerConnectionSetup(
            final ChildProcessConnection connection,
            String[] commandLine,
            int childProcessId,
            FileDescriptorInfo[] filesToBeMapped,
            final int callbackType,
            final long clientContext) {
        ChildProcessConnection.ConnectionCallback connectionCallback =
                new ChildProcessConnection.ConnectionCallback() {
                    @Override
                    public void onConnected(int pid) {
                        Log.d(TAG, "on connect callback, pid=%d context=%d callbackType=%d",
                                pid, clientContext, callbackType);
                        if (pid != NULL_PROCESS_HANDLE) {
                            sBindingManager.addNewConnection(pid, connection);
                            sServiceMap.put(pid, connection);
                        }
                        // If the connection fails and pid == 0, the Java-side cleanup was already
                        // handled by DeathCallback. We still have to call back to native for
                        // cleanup there.
                        if (clientContext != 0) {  // Will be 0 in Java instrumentation tests.
                            nativeOnChildProcessStarted(clientContext, pid);
                        }
                    }
                };

        assert callbackType != CALLBACK_FOR_UNKNOWN_PROCESS;
        connection.setupConnection(commandLine,
                                   filesToBeMapped,
                                   createCallback(childProcessId, callbackType),
                                   connectionCallback,
                                   Linker.getInstance().getSharedRelros());
    }

    /**
     * Terminates a child process. This may be called from any thread.
     *
     * @param pid The pid (process handle) of the service connection obtained from {@link #start}.
     */
    @CalledByNative
    static void stop(int pid) {
        Log.d(TAG, "stopping child connection: pid=%d", pid);
        ChildProcessConnection connection = sServiceMap.remove(pid);
        if (connection == null) {
            logPidWarning(pid, "Tried to stop non-existent connection");
            return;
        }
        sBindingManager.clearConnection(pid);
        connection.stop();
        freeConnection(connection);
    }

    /**
     * This implementation is used to receive callbacks from the remote service.
     */
    private static IChildProcessCallback createCallback(
            final int childProcessId, final int callbackType) {
        return new IChildProcessCallback.Stub() {
            /**
             * This is called by the remote service regularly to tell us about new values. Note that
             * IPC calls are dispatched through a thread pool running in each process, so the code
             * executing here will NOT be running in our main thread -- so, to update the UI, we
             * need to use a Handler.
             */
            @Override
            public void establishSurfacePeer(
                    int pid, Surface surface, int primaryID, int secondaryID) {
                // Do not allow a malicious renderer to connect to a producer. This is only used
                // from stream textures managed by the GPU process.
                if (callbackType != CALLBACK_FOR_GPU_PROCESS) {
                    Log.e(TAG, "Illegal callback for non-GPU process.");
                    return;
                }

                nativeEstablishSurfacePeer(pid, surface, primaryID, secondaryID);
            }

            @Override
            public void forwardSurfaceForSurfaceRequest(
                    long requestTokenHigh, long requestTokenLow, Surface surface) {
                // Do not allow a malicious renderer to connect to a producer. This is only used
                // from stream textures managed by the GPU process.
                if (callbackType != CALLBACK_FOR_GPU_PROCESS) {
                    Log.e(TAG, "Illegal callback for non-GPU process.");
                    return;
                }

                nativeCompleteScopedSurfaceRequest(requestTokenHigh, requestTokenLow, surface);
            }

            @Override
            public SurfaceWrapper getViewSurface(int surfaceId) {
                // Do not allow a malicious renderer to get to our view surface.
                if (callbackType != CALLBACK_FOR_GPU_PROCESS) {
                    Log.e(TAG, "Illegal callback for non-GPU process.");
                    return null;
                }
                Surface surface = ChildProcessLauncher.nativeGetViewSurface(surfaceId);
                if (surface == null) {
                    return null;
                }
                return new SurfaceWrapper(surface);
            }

            @Override
            public void registerSurfaceTextureSurface(
                    int surfaceTextureId, int clientId, Surface surface) {
                if (callbackType != CALLBACK_FOR_GPU_PROCESS) {
                    Log.e(TAG, "Illegal callback for non-GPU process.");
                    return;
                }

                ChildProcessLauncher.registerSurfaceTextureSurface(surfaceTextureId, clientId,
                        surface);
            }

            @Override
            public void unregisterSurfaceTextureSurface(
                    int surfaceTextureId, int clientId) {
                if (callbackType != CALLBACK_FOR_GPU_PROCESS) {
                    Log.e(TAG, "Illegal callback for non-GPU process.");
                    return;
                }

                ChildProcessLauncher.unregisterSurfaceTextureSurface(surfaceTextureId, clientId);
            }

            @Override
            public SurfaceWrapper getSurfaceTextureSurface(int surfaceTextureId) {
                if (callbackType != CALLBACK_FOR_RENDERER_PROCESS) {
                    Log.e(TAG, "Illegal callback for non-renderer process.");
                    return null;
                }

                return ChildProcessLauncher.getSurfaceTextureSurface(surfaceTextureId,
                        childProcessId);
            }
        };
    }

    static void logPidWarning(int pid, String message) {
        // This class is effectively a no-op in single process mode, so don't log warnings there.
        if (pid > 0 && !nativeIsSingleProcess()) {
            Log.w(TAG, "%s, pid=%d", message, pid);
        }
    }

    @VisibleForTesting
    static ChildProcessConnection allocateBoundConnectionForTesting(Context context,
            ChildProcessCreationParams creationParams) {
        return allocateBoundConnection(context, null, true, false, creationParams);
    }

    @VisibleForTesting
    static ChildProcessConnection allocateConnectionForTesting(Context context,
            ChildProcessCreationParams creationParams) {
        return allocateConnection(
                context, true, getLinkerParamsForNewConnection(), false, creationParams);
    }

    /**
     * Queue up a spawn requests for testing.
     */
    @VisibleForTesting
    static void enqueuePendingSpawnForTesting(Context context, String[] commandLine,
            ChildProcessCreationParams creationParams, boolean inSandbox) {
        String packageName = creationParams != null ? creationParams.getPackageName()
                : context.getPackageName();
        PendingSpawnQueue pendingSpawnQueue = getPendingSpawnQueue(context,
                packageName, inSandbox);
        synchronized (pendingSpawnQueue.mPendingSpawnsLock) {
            pendingSpawnQueue.enqueueLocked(new PendingSpawnData(context, commandLine, 1,
                    new FileDescriptorInfo[0], 0, CALLBACK_FOR_RENDERER_PROCESS, true,
                    creationParams));
        }
    }

    /**
     * @return the number of sandboxed connections of given {@link packageName} managed by the
     * allocator.
     */
    @VisibleForTesting
    static int allocatedSandboxedConnectionsCountForTesting(Context context, String packageName) {
        initConnectionAllocatorsIfNecessary(context, true, packageName);
        return sSandboxedChildConnectionAllocatorMap.get(packageName)
                .allocatedConnectionsCountForTesting();
    }

    /** @return the count of services set up and working */
    @VisibleForTesting
    static int connectedServicesCountForTesting() {
        return sServiceMap.size();
    }

    /**
     * @param context The context.
     * @param packageName The package name of the {@link ChildProcessAlocator}.
     * @param inSandbox Whether the connection is sandboxed.
     * @return the count of pending spawns in the queue.
     */
    @VisibleForTesting
    static int pendingSpawnsCountForTesting(Context context, String packageName,
            boolean inSandbox) {
        PendingSpawnQueue pendingSpawnQueue = getPendingSpawnQueue(context, packageName, inSandbox);
        synchronized (pendingSpawnQueue.mPendingSpawnsLock) {
            return pendingSpawnQueue.sizeLocked();
        }
    }

    /**
     * Kills the child process for testing.
     * @return true iff the process was killed as expected
     */
    @VisibleForTesting
    public static boolean crashProcessForTesting(int pid) {
        if (sServiceMap.get(pid) == null) return false;

        try {
            ((ChildProcessConnectionImpl) sServiceMap.get(pid)).crashServiceForTesting();
        } catch (RemoteException ex) {
            return false;
        }

        return true;
    }

    private static native void nativeOnChildProcessStarted(long clientContext, int pid);
    private static native void nativeEstablishSurfacePeer(
            int pid, Surface surface, int primaryID, int secondaryID);
    private static native void nativeCompleteScopedSurfaceRequest(
            long requestTokenHigh, long requestTokenLow, Surface surface);
    private static native boolean nativeIsSingleProcess();
    private static native Surface nativeGetViewSurface(int surfaceId);
}


text:
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.webview_shell;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.VisibleForTesting;
import androidx.webkit.WebViewClientCompat;

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;

import org.chromium.base.Log;

/**
 * A main activity to handle WPT requests.
 *
 * This is currently implemented to support minimum viable implementation such that
 * multi-window and JavaScript are enabled by default.
 * Note: multi-window support in this shell is implemented, but due to a bug
 *       in WebView (https://crbug.com/100272), it does not work properly unless a delay is given.
 */
public class WebPlatformTestsActivity extends Activity {
    private static final String TAG = "WPTActivity";
    private static final boolean DEBUG = false;

    /**
     * A callback for testing.
     */
    @VisibleForTesting
    public interface TestCallback {
        /** Called after child layout is added. */
        void onChildLayoutAdded(WebView webView);
        /** Called after child layout is removed. */
        void onChildLayoutRemoved();
    }

    private BiMap<ViewGroup, WebView> mLayoutToWebViewBiMap = HashBiMap.create();

    private LayoutInflater mLayoutInflater;
    private RelativeLayout mRootLayout;
    private WebView mWebView;
    private TestCallback mTestCallback;

    private class MultiWindowWebChromeClient extends WebChromeClient {
        @Override
        public boolean onCreateWindow(
                WebView parentWebView, boolean isDialog, boolean isUserGesture, Message resultMsg) {
            if (DEBUG) Log.i(TAG, "onCreateWindow");
            WebView childWebView = createChildLayoutAndGetNewWebView(parentWebView);
            WebSettings settings = childWebView.getSettings();
            setUpWebSettings(settings);
            childWebView.setWebViewClient(new WebViewClientCompat() {
                @Override
                public void onPageFinished(WebView childWebView, String url) {
                    if (DEBUG) Log.i(TAG, "onPageFinished");
                    // Once the view has loaded, display its title for debugging.
                    ViewGroup childLayout = mLayoutToWebViewBiMap.inverse().get(childWebView);
                    TextView childTitleText = childLayout.findViewById(R.id.childTitleText);
                    childTitleText.setText(childWebView.getTitle());
                }
            });
            childWebView.setWebChromeClient(new MultiWindowWebChromeClient());
            // Tell the transport about the new view
            WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
            transport.setWebView(childWebView);
            resultMsg.sendToTarget();
            if (mTestCallback != null) mTestCallback.onChildLayoutAdded(childWebView);
            return true;
        }

        @Override
        public void onCloseWindow(WebView webView) {
            ViewGroup childLayout = mLayoutToWebViewBiMap.inverse().get(webView);
            if (childLayout == mRootLayout) {
                Log.w(TAG, "Ignoring onCloseWindow() on the top-level webview.");
            } else {
                closeChild(childLayout);
            }
        }
    }

    /** Remove and destroy a webview if it exists. */
    private void removeAndDestroyWebView(WebView webView) {
        if (webView == null) return;
        ViewGroup parent = (ViewGroup) webView.getParent();
        if (parent != null) parent.removeView(webView);
        webView.destroy();
    }

    private String getUrlFromIntent() {
        if (getIntent() == null) return null;
        return getIntent().getDataString();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WebView.setWebContentsDebuggingEnabled(true);
        mLayoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        setContentView(R.layout.activity_web_platform_tests);
        mRootLayout = findViewById(R.id.rootLayout);
        mWebView = mRootLayout.findViewById(R.id.rootWebView);
        mLayoutToWebViewBiMap.put(mRootLayout, mWebView);

        String url = getUrlFromIntent();
        if (url == null) {
            // This is equivalent to Chrome's WPT setup.
            setUpMainWebView("about:blank");
        } else {
            Log.w(TAG,
                    "Handling a non-empty intent. This should only be used for testing. URL: "
                            + url);
            setUpMainWebView(url);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        removeAndDestroyWebView(mWebView);
        mWebView = null;
    }

    private WebView createChildLayoutAndGetNewWebView(WebView parentWebView) {
        // Add all the child layouts to the root layout such that we can remove
        // a child layout without affecting any grand child layout.
        final ViewGroup parentLayout = mRootLayout;
        // Provide parent such that MATCH_PARENT layout params can work. Ignore the return value
        // which is parentLayout.
        mLayoutInflater.inflate(R.layout.activity_web_platform_tests_child, parentLayout);
        // Choose what has just been added.
        LinearLayout childLayout =
                (LinearLayout) parentLayout.getChildAt(parentLayout.getChildCount() - 1);
        Button childCloseButton = childLayout.findViewById(R.id.childCloseButton);
        childCloseButton.setOnClickListener((View v) -> { closeChild(childLayout); });
        WebView childWebView = childLayout.findViewById(R.id.childWebView);
        mLayoutToWebViewBiMap.put(childLayout, childWebView);
        return childWebView;
    }

    private void setUpWebSettings(WebSettings settings) {
        // Required by WPT.
        settings.setJavaScriptEnabled(true);
        // Enable multi-window.
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setSupportMultipleWindows(true);
        // Respect "viewport" HTML meta tag. This is false by default, but set to false to be clear.
        settings.setUseWideViewPort(false);
        settings.setDomStorageEnabled(true);
    }

    private void setUpMainWebView(String url) {
        setUpWebSettings(mWebView.getSettings());
        mWebView.setWebChromeClient(new MultiWindowWebChromeClient());
        mWebView.loadUrl(url);
    }

    private void closeChild(ViewGroup childLayout) {
        if (DEBUG) Log.i(TAG, "closeChild");
        ViewGroup parent = (ViewGroup) childLayout.getParent();
        if (parent != null) parent.removeView(childLayout);
        WebView childWebView = mLayoutToWebViewBiMap.get(childLayout);
        removeAndDestroyWebView(childWebView);
        mLayoutToWebViewBiMap.remove(childLayout);
        if (mTestCallback != null) mTestCallback.onChildLayoutRemoved();
    }

    @VisibleForTesting
    public void setTestCallback(TestCallback testDelegate) {
        mTestCallback = testDelegate;
    }

    @VisibleForTesting
    public WebView getTestRunnerWebView() {
        return mWebView;
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace Autofac.Benchmarks;

public class PropertyInjectionBenchmark
{
    private IContainer _container;

    [GlobalSetup]
    public void Setup()
    {
        var builder = new ContainerBuilder();
        builder.RegisterType<A>().PropertiesAutowired();
        builder.RegisterType<B1>().PropertiesAutowired();
        builder.RegisterType<B2>().PropertiesAutowired();
        builder.RegisterType<C1>().PropertiesAutowired();
        builder.RegisterType<C2>().PropertiesAutowired();
        builder.RegisterType<D1>();
        builder.RegisterType<D2>();
        _container = builder.Build();
    }

    [Benchmark]
    public void Resolve()
    {
        var instance = _container.Resolve<A>();
        GC.KeepAlive(instance);
    }

    internal class A
    {
        public B1 B1 { get; set; }

        public B2 B2 { get; set; }
    }

    internal class B1
    {
        public C1 C1 { get; set; }
    }

    internal class B2
    {
        public C2 C2 { get; set; }
    }

    internal class C1
    {
        public D1 D1 { get; set; }
    }

    internal class C2
    {
        public D2 D2 { get; set; }
    }

    internal class D1 { }

    internal class D2 { }
}


text:
var package_json = require('./package.json');
var Binary = require('./lib/binary_name.js').Binary;
var util = require('./build-util/tools.js');

var cp = require('child_process');
var fs = require('fs');
var mkdirp = require('mkdirp');
var path = require('path');

var opts = {
    name: 'node_sleep',
    force: false,
    stage: false,
    configuration: 'Release',
    target_arch: process.arch,
    platform: process.platform,
    uri: 'http://node-sleep.s3.amazonaws.com/',
    tool: 'node-gyp',
    paths: {}
};

function log(msg) {
    console.log('['+package_json.name+']: ' + msg);
}

// only for dev
function log_debug(msg) {
    log(msg);
}

function done(err) {
    if (err) {
        log(err);
        process.exit(1);
    }
    process.exit(0);
}

function build(opts,callback) {
    var shell_cmd = opts.tool;
    if (opts.tool === 'node-gyp' && process.platform === 'win32') {
        shell_cmd = 'node-gyp.cmd';
    }
    var shell_args = ['rebuild'].concat(opts.args);
    var cmd = cp.spawn(shell_cmd,shell_args, {cwd: undefined, env: process.env, customFds: [ 0, 1, 2]});
    cmd.on('error', function (err) {
        if (err) {
            return callback(new Error("Failed to execute '" + shell_cmd + ' ' + shell_args.join(' ') + "' (" + err + ")"));
        }
    });
    // exit not close to support node v0.6.x
    cmd.on('exit', function (code) {
        if (code !== 0) {
            return callback(new Error("Failed to execute '" + shell_cmd + ' ' + shell_args.join(' ') + "' (" + code + ")"));
        }
        move(opts,callback);
    });
}

function move(opts,callback) {
    try {
        fs.statSync(opts.paths.build_module_path);
    } catch (ex) {
        return callback(new Error('Build succeeded but target not found at ' + opts.paths.build_module_path));
    }
    try {
        mkdirp.sync(path.dirname(opts.paths.runtime_module_path));
        log('Created: ' + path.dirname(opts.paths.runtime_module_path));
    } catch (err) {
        log_debug(err);
    }
    fs.renameSync(opts.paths.build_module_path,opts.paths.runtime_module_path);
    if (opts.stage) {
        try {
            mkdirp.sync(path.dirname(opts.paths.staged_module_file_name));
            log('Created: ' + path.dirname(opts.paths.staged_module_file_name));
        } catch (err) {
            log_debug(err);
        }
        fs.writeFileSync(opts.paths.staged_module_file_name,fs.readFileSync(opts.paths.runtime_module_path));
        // drop build metadata into build folder
        var metapath = path.join(path.dirname(opts.paths.staged_module_file_name),'build-info.json');
        // more build info
        opts.date = new Date();
        opts.node_features = process.features;
        opts.versions = process.versions;
        opts.config = process.config;
        opts.execPath = process.execPath;
        fs.writeFileSync(metapath,JSON.stringify(opts,null,2));
        //tarball(opts,callback);
        return callback();
    } else {
        log('Installed in ' + opts.paths.runtime_module_path + '');
        return callback();
    }
}

function rel(p) {
    return path.relative(process.cwd(),p);
}

// build it!
opts = util.parse_args(process.argv.slice(2), opts);
opts.binary = new Binary(opts);
var versioned = opts.binary.getRequirePath();
opts.paths.runtime_module_path = rel(path.join(__dirname, 'lib', versioned));
opts.paths.runtime_folder = rel(path.join(__dirname, 'lib', 'binding',opts.binary.configuration));
var staged_module_path = path.join(__dirname, 'stage', opts.binary.getModuleAbi(), opts.binary.getBasePath());
opts.paths.staged_module_file_name = rel(path.join(staged_module_path,opts.binary.filename()));
opts.paths.build_module_path = rel(path.join(__dirname, 'build', opts.binary.configuration, opts.binary.filename()));

build(opts, done);


text:
package com.sequenceiq.cloudbreak.domain.converter;

import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.base.GatewayType;
import com.sequenceiq.cloudbreak.converter.DefaultEnumConverter;

public class GatewayTypeConverter extends DefaultEnumConverter<GatewayType> {

    @Override
    public GatewayType getDefault() {
        return GatewayType.CENTRAL;
    }
}


text:
package com.ironz.binaryprefs.exception;

/**
 * Exception will be thrown if lock acquire/release operations fails
 */
public final class LockOperationException extends RuntimeException {

    public LockOperationException(Throwable cause) {
        super(cause);
    }
}


text:
package android.support.v4.view.animation;

import android.graphics.Path;
import android.view.animation.Interpolator;
import android.view.animation.PathInterpolator;

class PathInterpolatorCompatApi21 {
    private PathInterpolatorCompatApi21() {
    }

    public static Interpolator create(Path path) {
        return new PathInterpolator(path);
    }

    public static Interpolator create(float controlX, float controlY) {
        return new PathInterpolator(controlX, controlY);
    }

    public static Interpolator create(float controlX1, float controlY1, float controlX2, float controlY2) {
        return new PathInterpolator(controlX1, controlY1, controlX2, controlY2);
    }
}


text:
<?php

Class Order extends CI_Model
{
	public function get_orders_by_user()
	{
		$query = "SELECT orders.id as id, orders.total as total, orders.created_at as order_date"
	}
}
?>


text:
<?xml version="1.0"?>
<!--

-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../vendor/magento/mtf/etc/pages.xsd">
    <page name="PromoQuoteNew" area="Adminhtml" mca="promo_quote/new" module="Mage_SalesRule">
        <block name="formPageActions" class="Mage\Adminhtml\Test\Block\FormPageActions" locator=".form-buttons" strategy="css selector"/>
        <block name="salesRuleForm" class="Mage\Adminhtml\Test\Block\Promo\Quote\Edit\PromoQuoteForm" locator="[id='page:main-container']" strategy="css selector"/>
    </page>
</config>


text:
"""Directives are special no-op functions that serve as compilation markers.

They provide static information like type hints, compilation and TensorFlow
overrides.

These serve as annotations in the compiled code, allowing the user some control
over the compilation process. They have no functional role at runtime.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

UNSPECIFIED = object()

def set_element_type(entity, dtype, shape=UNSPECIFIED):
  """Indicates that the entity is expected hold items of specified type/shape.

  The staged TensorFlow ops will reflect and assert this data type. Ignored
  otherwise.

  Args:
    entity: The entity to annotate.
    dtype: TensorFlow dtype value to assert for entity.
    shape: Optional shape to assert for entity.
  """
  del entity
  del dtype
  del shape

def set_loop_options(
    parallel_iterations=UNSPECIFIED,
    back_prop=UNSPECIFIED,
    swap_memory=UNSPECIFIED,
    maximum_iterations=UNSPECIFIED):
  """Specifies additional arguments to be passed to the enclosing while_loop.

  The parameters apply to and only to the immediately enclosing loop. It only
  has effect if the loop is staged as a TF while_loop; otherwise the parameters
  have no effect.

  Args:
    parallel_iterations: See tf.while_loop.
    back_prop: See tf.while_loop.
    swap_memory: See tf.while_loop.
    maximum_iterations: See tf.while_loop.
  """
  del parallel_iterations
  del back_prop
  del swap_memory
  del maximum_iterations


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

<title>An Easy Way to Make Ggplot2 Boxplots, ezplot - Part 2 | Become Great at R</title>
<meta name="generator" content="Jekyll v3.9.2" />
<meta property="og:title" content="An Easy Way to Make Ggplot2 Boxplots, ezplot - Part 2" />
<meta name="author" content="Guangming Lang" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="Updated October 4, 2018" />
<meta property="og:description" content="Updated October 4, 2018" />
<link rel="canonical" href="http://localhost:4000/r/an-easy-way-to-make-ggplot2-boxplots-ezplot-part2/" />
<meta property="og:url" content="http://localhost:4000/r/an-easy-way-to-make-ggplot2-boxplots-ezplot-part2/" />
<meta property="og:site_name" content="Become Great at R" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2015-04-26T00:00:00+09:00" />
<meta name="twitter:card" content="summary" />
<meta property="twitter:title" content="An Easy Way to Make Ggplot2 Boxplots, ezplot - Part 2" />
<meta name="twitter:site" content="@" />
<meta name="twitter:creator" content="@Guangming Lang" />

  <link rel="stylesheet" href="/assets/css/main.css">
  <link rel="stylesheet" href="/assets/css/skins/default.css">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,400i,700,700i|Lora:400,400i,700,700i">
  <link rel="alternate" type="application/atom+xml" title="Become Great at R" href="/atom.xml">

Skip links

Skip to primary navigation

Skip to content

Skip to footer

    Menu

About

R

Data Analysis

Books

Apps

Cartoon

Become Great at R

Master the R programming language

An Easy Way to Make Ggplot2 Boxplots, ezplot - Part 2

        by Guangming Lang

1 min read

    <time class="page-date dt-published" datetime="2015-04-26T00:00:00+09:00">April 26, 2015
</time>

Categories

r

Updated October 4, 2018

Previously, I introduced the ezplot package and showed how to use it to make high quality bar charts. Today, I'm going to show you how to make boxplots using ezplot. Once again, it's super simple.

Load ezplot

Make sure you first install ezplot by running the command devtools::install_github("gmlang/ezplot").

library(ezplot)
library(dplyr)

Draw boxplots.

The ezplot package comes with a films dataset obtained from IMBD.com. Let's
draw a boxplot of budget vs. year_cat.

plt = mk_boxplot(films) # plt() is a function that can produce boxplot

# plot distributions of budget over the years
p = plt("year_cat", "budget")
print(p)

We see the y-axis tick labels are in scientific notations, which makes it difficult to look at. We can use the dollar scale instead.

scale_axis(p, scale = "dollar")

## Scale for 'y' is already present. Adding another scale for 'y', which
## will replace the existing scale.

Notice that all boxes are squashed down, indicating budget is heavily right-skewed. To remedy this, we can use the log10 scale on the y-axis.

scale_axis(p, scale = "log10")

## Scale for 'y' is already present. Adding another scale for 'y', which
## will replace the existing scale.

Please drop a comment below if you have questions.

   Share
   Tweet
   LinkedIn
   Reddit

Previous

         An Easy Way to Make Ggplot2 Plots, ezplot - Part 1

Next

        An Easy Way to Make Ggplot2 Histograms and Density Plots, ezplot - Part 3

© 2022 Become Great at R. Powered by Jekyll & So Simple.


text:
package logging

import (
	"bytes"
	"fmt"
	"log"
	"os"
	"strings"
	"sync/atomic"
	"time"
)

// Redactor is an interface for types that may contain sensitive information
// (like passwords), which shouldn't be printed to the log. The idea was found
// in relog as part of the vitness project.
type Redactor interface {
	Redacted() interface{}
}

// Redact returns a string of * having the same length as s.
func Redact(s string) string {
	return strings.Repeat("*", len(s))
}

var (
	// Sequence number is incremented and utilized for all log records created.
	sequenceNo uint64

	// timeNow is a customizable for testing purposes.
	timeNow = time.Now
)

// Annotation is a key/value entry; the Annotator backend can
// add annotations
type Annotation struct {
	Key string
	Value interface{}
}

// Record represents a log record and contains the timestamp when the record
// was created, an increasing id, filename and line and finally the actual
// formatted log line.
type Record struct {
	Id     uint64
	Time   time.Time
	Module string
	Level  Level
	Annotations []Annotation

	// message is kept as a pointer to have shallow copies update this once
	// needed.
	message   *string
	args      []interface{}
	fmt       string
	formatter Formatter
	formatted string
}

func (r *Record) Formatted(calldepth int) string {
	if r.formatted == "" {
		var buf bytes.Buffer
		r.formatter.Format(calldepth+1, r, &buf)
		r.formatted = buf.String()
	}
	return r.formatted
}

func (r *Record) Message() string {
	if r.message == nil {
		// Redact the arguments that implements the Redactor interface
		for i, arg := range r.args {
			if redactor, ok := arg.(Redactor); ok == true {
				r.args[i] = redactor.Redacted()
			}
		}
		msg := fmt.Sprintf(r.fmt, r.args...)
		r.message = &msg
	}
	return *r.message
}

type LevelLogger interface {
	// a logging.LevelLogger is also a standardlog.Logger
	Fatal(v ...interface{})
	Fatalf(format string, v ...interface{})
	Fatalln(v ...interface{})
	Panic(v ...interface{})
	Panicf(format string, v ...interface{})
	Panicln(v ...interface{})
	Print(v ...interface{})
	Printf(format string, v ...interface{})
	Println(v ...interface{})

	// Go1 details of log.Logger that don't seem appropriate to
	// the abstract notion of logging
	Output(calldepth int, s string) error
	Outputf(adjcalldepth int, format string, args ...interface{})
	Prefix() string
	Flags() int
	SetFlags(flag int)
	SetPrefix(prefix string)

	// and then we have our own goodies

	Debug(format string, args ...interface{})
	Info(format string, args ...interface{})
	Notice(format string, args ...interface{})
	Warning(format string, args ...interface{})
	Error(format string, args ...interface{})
	Critical(format string, args ...interface{})
}

type Logger struct {
	Module string
	flags  int
	// the Level at which we Output records (defaults to INFO)
	OutputLevel Level
	backend LeveledBackend
	annotater Annotater
}

func (l *Logger) SetBackend(b LeveledBackend) {
	l.backend = b
}

func (l *Logger) Backend() LeveledBackend {
	if l.backend == nil {
		return defaultBackend
	} else {
		return l.backend
	}
}

// TODO call NewLogger and remove MustGetLogger?
// GetLogger creates and returns a Logger object based on the module name.
func GetLogger(module string) (*Logger, error) {
	return &Logger{
		Module:      module,
		OutputLevel: INFO,
	}, nil
}

// MustGetLogger is like GetLogger but panics if the logger can't be created.
// It simplifies safe initialization of a global logger for eg. a package.
func MustGetLogger(module string) *Logger {
	logger, err := GetLogger(module)
	if err != nil {
		panic("logger: " + module + ": " + err.Error())
	}
	return logger
}

// Reset restores the internal state of the logging library.
func Reset() {
	// TODO make a global Init() method to be less magic? or make it such that
	// if there's no backends at all configured, we could use some tricks to
	// automatically setup backends based if we have a TTY or not.
	sequenceNo = 0
	b := SetBackend(NewLogBackend(os.Stderr, "", log.LstdFlags))
	b.SetLevel(DEBUG, "")
	SetFormatter(DefaultFormatter)
	timeNow = time.Now
}

// InitForTesting is a convenient method when using logging in a test. Once
// called, the time will be frozen to January 1, 1970 UTC.
func InitForTesting(level Level) *MemoryBackend {
	Reset()

	memoryBackend := NewMemoryBackend(10240)

	leveledBackend := AddModuleLevel(memoryBackend)
	leveledBackend.SetLevel(level, "")
	SetBackend(leveledBackend)

	timeNow = func() time.Time {
		return time.Unix(0, 0).UTC()
	}
	return memoryBackend
}

// IsEnabledFor returns true if the logger is enabled for the given level.
func (l *Logger) IsEnabledFor(level Level) bool {
	return l.Backend().IsEnabledFor(level, l.Module)
}

func (l *Logger) Log(lvl Level, format string, args ...interface{}) {
	// Create the logging record and pass it in to the backend
	record := &Record{
		Id:     atomic.AddUint64(&sequenceNo, 1),
		Time:   timeNow(),
		Module: l.Module,
		Level:  lvl,
		fmt:    format,
		args:   args,
	}
	if l.annotater != nil {
		l.annotater.Annotate(record)
	}
	// TODO use channels to fan out the records to all backends?
	// TODO in case of errors, do something (tricky)

	// calldepth=2 brings the stack up to the caller of the level
	// methods, Info(), Fatal(), etc.
	l.Backend().Log(lvl, 2, record)
}

func (l *Logger) Print(v ...interface{}) {
	l.Output(2, fmt.Sprint(v...))
}

func (l *Logger) Printf(format string, v ...interface{}) {
	l.Output(2, fmt.Sprintf(format, v...))
}

func (l *Logger) Println(v ...interface{}) {
	l.Output(2, fmt.Sprintln(v...))
}

func (l *Logger) Output(calldepth int, s string) error {
	// Create the logging record and pass it in to the backend
	record := &Record{
		Id:     atomic.AddUint64(&sequenceNo, 1),
		Time:   timeNow(),
		Module: l.Module,
		Level:  l.OutputLevel,
		fmt:    "%s",
		args:   []interface{}{s},
	}
	if l.annotater != nil {
		l.annotater.Annotate(record)
	}

	// TODO use channels to fan out the records to all backends?
	// TODO in case of errors, do something (tricky)

	// calldepth=2 brings the stack up to the caller of the level
	// methods, Info(), Fatal(), etc.
	l.Backend().Log(l.OutputLevel, calldepth, record)
	return nil
}

func (l *Logger) Outputf(adjdepth int, fmt string, args ...interface{}) {
	// Create the logging record and pass it in to the backend
	record := &Record{
		Id:     atomic.AddUint64(&sequenceNo, 1),
		Time:   timeNow(),
		Module: l.Module,
		Level:  l.OutputLevel,
		fmt:    fmt,
		args:   args,
	}

	// TODO use channels to fan out the records to all backends?
	// TODO in case of errors, do something (tricky)

	// calldepth=2 brings the stack up to the level of our caller
	l.Backend().Log(l.OutputLevel, 1+adjdepth, record)
}

func (l *Logger) SetFlags(flag int) {
	l.flags = flag
}

func (l *Logger) Flags() int {
	return l.flags
}

func (l *Logger) SetPrefix(p string) {
	l.Module = p
}

func (l *Logger) Prefix() string {
	return l.Module
}

// Fatal is equivalent to l.Critical(fmt.Sprint()) followed by a call to os.Exit(1).
func (l *Logger) Fatal(args ...interface{}) {
	s := fmt.Sprint(args...)
	l.Log(CRITICAL, "%s", s)
	os.Exit(1)
}

// Fatalf is equivalent to l.Critical followed by a call to os.Exit(1).
func (l *Logger) Fatalf(format string, args ...interface{}) {
	l.Log(CRITICAL, format, args...)
	os.Exit(1)
}

// Fatalln is equivalent to l.Critical(fmt.Sprintln()) followed by a call to os.Exit(1).
func (l *Logger) Fatalln(args ...interface{}) {
	s := fmt.Sprintln(args...)
	l.Log(CRITICAL, "%s", s)
	os.Exit(1)
}

// Panic is equivalent to l.Critical(fmt.Sprint()) followed by a call to panic().
func (l *Logger) Panic(args ...interface{}) {
	s := fmt.Sprint(args...)
	l.Log(CRITICAL, "%s", s)
	panic(s)
}

// Panicf is equivalent to l.Critical followed by a call to panic().
func (l *Logger) Panicf(format string, args ...interface{}) {
	s := fmt.Sprintf(format, args...)
	l.Log(CRITICAL, "%s", s)
	panic(s)
}

// Panicln is equivalent to l.Critical(fmt.Sprintln()) followed by a call to panic().
func (l *Logger) Panicln(args ...interface{}) {
	s := fmt.Sprintln(args...)
	l.Log(CRITICAL, "%s", s)
	panic(s)
}

// Critical logs a message using CRITICAL as log level.
func (l *Logger) Critical(format string, args ...interface{}) {
	l.Log(CRITICAL, format, args...)
}

// Error logs a message using ERROR as log level.
func (l *Logger) Error(format string, args ...interface{}) {
	l.Log(ERROR, format, args...)
}

// Warning logs a message using WARNING as log level.
func (l *Logger) Warning(format string, args ...interface{}) {
	l.Log(WARNING, format, args...)
}

// Notice logs a message using NOTICE as log level.
func (l *Logger) Notice(format string, args ...interface{}) {
	l.Log(NOTICE, format, args...)
}

// Info logs a message using INFO as log level.
func (l *Logger) Info(format string, args ...interface{}) {
	l.Log(INFO, format, args...)
}

// Debug logs a message using DEBUG as log level.
func (l *Logger) Debug(format string, args ...interface{}) {
	l.Log(DEBUG, format, args...)
}

func init() {
	Reset()
}


text:
# Makefile.in generated by automake 1.11.6 from Makefile.am.
# doc/libogg/Makefile.  Generated from Makefile.in by configure.

# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software
# Foundation, Inc.
# This Makefile.in is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.

am__make_dryrun = \
  { \
    am__dry=no; \
    case $$MAKEFLAGS in \
      *\\[\ \	]*) \
        echo 'am--echo: ; @echo "AM"  OK' | $(MAKE) -f - 2>/dev/null \
          | grep '^AM OK$$' >/dev/null || am__dry=yes;; \
      *) \
        for am__flg in $$MAKEFLAGS; do \
          case $$am__flg in \
            *=*|--*) ;; \
            *n*) am__dry=yes; break;; \
          esac; \
        done;; \
    esac; \
    test $$am__dry = yes; \
  }
pkgdatadir = $(datadir)/libogg
pkgincludedir = $(includedir)/libogg
pkglibdir = $(libdir)/libogg
pkglibexecdir = $(libexecdir)/libogg
am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
install_sh_DATA = $(install_sh) -c -m 644
install_sh_PROGRAM = $(install_sh) -c
install_sh_SCRIPT = $(install_sh) -c
INSTALL_HEADER = $(INSTALL_DATA)
transform = $(program_transform_name)
NORMAL_INSTALL = :
PRE_INSTALL = :
POST_INSTALL = :
NORMAL_UNINSTALL = :
PRE_UNINSTALL = :
POST_UNINSTALL = :
build_triplet = x86_64-unknown-linux-gnu
host_triplet = arm-unknown-linux-gnu
subdir = doc/libogg
DIST_COMMON = $(dist_apidoc_DATA) $(srcdir)/Makefile.am \
	$(srcdir)/Makefile.in
ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
am__aclocal_m4_deps = $(top_srcdir)/configure.in
am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
	$(ACLOCAL_M4)
mkinstalldirs = $(install_sh) -d
CONFIG_HEADER = $(top_builddir)/config.h
CONFIG_CLEAN_FILES =
CONFIG_CLEAN_VPATH_FILES =
SOURCES =
DIST_SOURCES =
am__can_run_installinfo = \
  case $$AM_UPDATE_INFO_DIR in \
    n|no|NO) false;; \
    *) (install-info --version) >/dev/null 2>&1;; \
  esac
am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
am__vpath_adj = case $$p in \
    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
    *) f=$$p;; \
  esac;
am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
am__install_max = 40
am__nobase_strip_setup = \
  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
am__nobase_strip = \
  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
am__nobase_list = $(am__nobase_strip_setup); \
  for p in $$list; do echo "$$p $$p"; done | \
  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
    if (++n[$$2] == $(am__install_max)) \
      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
    END { for (dir in files) print dir, files[dir] }'
am__base_list = \
  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
am__uninstall_files_from_dir = { \
  test -z "$$files" \
    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
         $(am__cd) "$$dir" && rm -f $$files; }; \
  }
am__installdirs = "$(DESTDIR)$(apidocdir)"
DATA = $(dist_apidoc_DATA)
DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
ACLOCAL = ${SHELL} /home/retsu/FFmpeg-Android/jni/libogg/missing --run aclocal-1.11
AMTAR = $${TAR-tar}
AR = /home/retsu/android-ndk/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86/bin/arm-linux-androideabi-ar
AUTOCONF = ${SHELL} /home/retsu/FFmpeg-Android/jni/libogg/missing --run autoconf
AUTOHEADER = ${SHELL} /home/retsu/FFmpeg-Android/jni/libogg/missing --run autoheader
AUTOMAKE = ${SHELL} /home/retsu/FFmpeg-Android/jni/libogg/missing --run automake-1.11
AWK = gawk
CC = /home/retsu/android-ndk/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86/bin/arm-linux-androideabi-gcc --sysroot=/home/retsu/android-ndk/platforms/android-9/arch-arm/
CCDEPMODE = depmode=none
CFLAGS = -O20 -Wall -ffast-math -fsigned-char -mfloat-abi=softfp -mfpu=neon -marm -march=armv7-a -mtune=cortex-a8 -mthumb -D__thumb__  -lgcc
CPP = /home/retsu/android-ndk/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86/bin/arm-linux-androideabi-gcc --sysroot=/home/retsu/android-ndk/platforms/android-9/arch-arm/ -E
CPPFLAGS = -mfloat-abi=softfp -mfpu=neon -marm -march=armv7-a -mtune=cortex-a8 -mthumb -D__thumb__
CYGPATH_W = echo
DEBUG = -g -Wall -fsigned-char -mfloat-abi=softfp -mfpu=neon -marm -march=armv7-a -mtune=cortex-a8 -mthumb -D__thumb__  -lgcc
DEFS = -DHAVE_CONFIG_H
DEPDIR = .deps
DLLTOOL = false
DSYMUTIL =
DUMPBIN =
ECHO_C =
ECHO_N = -n
ECHO_T =
EGREP = /bin/grep -E
EXEEXT =
FGREP = /bin/grep -F
GREP = /bin/grep
INCLUDE_INTTYPES_H = 1
INCLUDE_STDINT_H = 1
INCLUDE_SYS_TYPES_H = 1
INSTALL = /usr/bin/install -c
INSTALL_DATA = ${INSTALL} -m 644
INSTALL_PROGRAM = ${INSTALL}
INSTALL_SCRIPT = ${INSTALL}
INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
LD = /home/retsu/android-ndk/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86/arm-linux-androideabi/bin/ld
LDFLAGS = -Wl,-rpath-link=/home/retsu/android-ndk/platforms/android-9/arch-arm//usr/lib -L/home/retsu/android-ndk/platforms/android-9/arch-arm//usr/lib -lc -lm -ldl -llog
LIBOBJS =  ${LIBOBJDIR}memcmp$U.o
LIBS =
LIBTOOL = $(SHELL) $(top_builddir)/libtool
LIBTOOL_DEPS = ./ltmain.sh
LIB_AGE = 8
LIB_CURRENT = 8
LIB_REVISION = 1
LIPO =
LN_S = ln -s
LTLIBOBJS =  ${LIBOBJDIR}memcmp$U.lo
MAINT =
MAKEINFO = ${SHELL} /home/retsu/FFmpeg-Android/jni/libogg/missing --run makeinfo
MANIFEST_TOOL = :
MKDIR_P = /bin/mkdir -p
NM = /home/retsu/android-ndk/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86/bin/arm-linux-androideabi-nm
NMEDIT =
OBJDUMP = objdump
OBJEXT = o
OPT =
OTOOL =
OTOOL64 =
PACKAGE = libogg
PACKAGE_BUGREPORT = ogg-dev@xiph.org
PACKAGE_NAME = libogg
PACKAGE_STRING = libogg 1.3.1
PACKAGE_TARNAME = libogg
PACKAGE_URL =
PACKAGE_VERSION = 1.3.1
PATH_SEPARATOR = :
PROFILE = -Wall -W -pg -g -O20 -ffast-math -fsigned-char -mfloat-abi=softfp -mfpu=neon -marm -march=armv7-a -mtune=cortex-a8 -mthumb -D__thumb__  -lgcc
RANLIB = /home/retsu/android-ndk/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86/bin/arm-linux-androideabi-ranlib
SED = /bin/sed
SET_MAKE =
SHELL = /bin/bash
SIZE16 = int16_t
SIZE32 = int32_t
SIZE64 = int64_t
STRIP = /home/retsu/android-ndk/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86/bin/arm-linux-androideabi-strip
USIZE16 = uint16_t
USIZE32 = uint32_t
VERSION = 1.3.1
abs_builddir = /home/retsu/FFmpeg-Android/jni/libogg/doc/libogg
abs_srcdir = /home/retsu/FFmpeg-Android/jni/libogg/doc/libogg
abs_top_builddir = /home/retsu/FFmpeg-Android/jni/libogg
abs_top_srcdir = /home/retsu/FFmpeg-Android/jni/libogg
ac_ct_AR =
ac_ct_CC =
ac_ct_DUMPBIN =
am__include = include
am__leading_dot = .
am__quote =
am__tar = $${TAR-tar} chof - "$$tardir"
am__untar = $${TAR-tar} xf -
bindir = ${exec_prefix}/bin
build = x86_64-unknown-linux-gnu
build_alias =
build_cpu = x86_64
build_os = linux-gnu
build_vendor = unknown
builddir = .
datadir = ${datarootdir}
datarootdir = ${prefix}/share
docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
dvidir = ${docdir}
exec_prefix = ${prefix}
host = arm-unknown-linux-gnu
host_alias = arm-linux
host_cpu = arm
host_os = linux-gnu
host_vendor = unknown
htmldir = ${docdir}
includedir = ${prefix}/include
infodir = ${datarootdir}/info
install_sh = ${SHELL} /home/retsu/FFmpeg-Android/jni/libogg/install-sh
libdir = ${exec_prefix}/lib
libexecdir = ${exec_prefix}/libexec
localedir = ${datarootdir}/locale
localstatedir = ${prefix}/var
mandir = ${datarootdir}/man
mkdir_p = /bin/mkdir -p
oldincludedir = /usr/include
pdfdir = ${docdir}
prefix = /home/retsu/FFmpeg-Android/jni/libogg/../ffmpeg-build/armeavi-v7a-neon
program_transform_name = s,x,x,
psdir = ${docdir}
sbindir = ${exec_prefix}/sbin
sharedstatedir = ${prefix}/com
srcdir = .
sysconfdir = ${prefix}/etc
target_alias =
top_build_prefix = ../../
top_builddir = ../..
top_srcdir = ../..
apidocdir = $(htmldir)/libogg
dist_apidoc_DATA = bitpacking.html datastructures.html decoding.html encoding.html\
	general.html index.html ogg_iovec_t.html ogg_packet.html ogg_packet_clear.html\
	ogg_page.html ogg_page_bos.html ogg_page_checksum_set.html\
	ogg_page_continued.html ogg_page_eos.html ogg_page_granulepos.html\
	ogg_page_packets.html ogg_page_pageno.html ogg_page_serialno.html\
	ogg_page_version.html ogg_stream_check.html ogg_stream_clear.html ogg_stream_destroy.html\
	ogg_stream_eos.html ogg_stream_flush.html ogg_stream_flush_fill.html ogg_stream_init.html\
	ogg_stream_iovecin.html ogg_stream_packetin.html ogg_stream_packetout.html\
	ogg_stream_packetpeek.html ogg_stream_pagein.html\
	ogg_stream_pageout.html ogg_stream_pageout_fill.html ogg_stream_reset.html\
	ogg_stream_reset_serialno.html ogg_stream_state.html\
	ogg_sync_buffer.html ogg_sync_check.html ogg_sync_clear.html ogg_sync_destroy.html\
	ogg_sync_init.html ogg_sync_pageout.html ogg_sync_pageseek.html\
	ogg_sync_reset.html ogg_sync_state.html ogg_sync_wrote.html\
	oggpack_adv.html oggpack_adv1.html oggpack_bits.html\
	oggpack_buffer.html oggpack_bytes.html oggpack_get_buffer.html\
	oggpack_look.html oggpack_look1.html oggpack_read.html\
	oggpack_read1.html oggpack_readinit.html oggpack_reset.html\
	oggpack_write.html oggpack_writealign.html oggpack_writecheck.html oggpack_writeclear.html\
	oggpack_writecopy.html oggpack_writeinit.html oggpack_writetrunc.html\
	overview.html reference.html style.css

all: all-am

.SUFFIXES:
$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
	@for dep in $?; do \
	  case '$(am__configure_deps)' in \
	    *$$dep*) \
	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
	        && { if test -f $@; then exit 0; else break; fi; }; \
	      exit 1;; \
	  esac; \
	done; \
	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu doc/libogg/Makefile'; \
	$(am__cd) $(top_srcdir) && \
	  $(AUTOMAKE) --gnu doc/libogg/Makefile
.PRECIOUS: Makefile
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
	@case '$?' in \
	  *config.status*) \
	    cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
	  *) \
	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
	    cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
	esac;

$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh

$(top_srcdir)/configure:  $(am__configure_deps)
	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(am__aclocal_m4_deps):

mostlyclean-libtool:
	-rm -f *.lo

clean-libtool:
	-rm -rf .libs _libs
install-dist_apidocDATA: $(dist_apidoc_DATA)
	@$(NORMAL_INSTALL)
	@list='$(dist_apidoc_DATA)'; test -n "$(apidocdir)" || list=; \
	if test -n "$$list"; then \
	  echo " $(MKDIR_P) '$(DESTDIR)$(apidocdir)'"; \
	  $(MKDIR_P) "$(DESTDIR)$(apidocdir)" || exit 1; \
	fi; \
	for p in $$list; do \
	  if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
	  echo "$$d$$p"; \
	done | $(am__base_list) | \
	while read files; do \
	  echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(apidocdir)'"; \
	  $(INSTALL_DATA) $$files "$(DESTDIR)$(apidocdir)" || exit $$?; \
	done

uninstall-dist_apidocDATA:
	@$(NORMAL_UNINSTALL)
	@list='$(dist_apidoc_DATA)'; test -n "$(apidocdir)" || list=; \
	files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
	dir='$(DESTDIR)$(apidocdir)'; $(am__uninstall_files_from_dir)
tags: TAGS
TAGS:

ctags: CTAGS
CTAGS:

distdir: $(DISTFILES)
	@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
	list='$(DISTFILES)'; \
	  dist_files=`for file in $$list; do echo $$file; done | \
	  sed -e "s|^$$srcdirstrip/||;t" \
	      -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
	case $$dist_files in \
	  */*) $(MKDIR_P) `echo "$$dist_files" | \
			   sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
			   sort -u` ;; \
	esac; \
	for file in $$dist_files; do \
	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
	  if test -d $$d/$$file; then \
	    dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
	    if test -d "$(distdir)/$$file"; then \
	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
	    fi; \
	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
	    fi; \
	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
	  else \
	    test -f "$(distdir)/$$file" \
	    || cp -p $$d/$$file "$(distdir)/$$file" \
	    || exit 1; \
	  fi; \
	done
check-am: all-am
check: check-am
all-am: Makefile $(DATA)
installdirs:
	for dir in "$(DESTDIR)$(apidocdir)"; do \
	  test -z "$$dir" || $(MKDIR_P) "$$dir"; \
	done
install: install-am
install-exec: install-exec-am
install-data: install-data-am
uninstall: uninstall-am

install-am: all-am
	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am

installcheck: installcheck-am
install-strip:
	if test -z '$(STRIP)'; then \
	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
	      install; \
	else \
	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
	    "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
	fi
mostlyclean-generic:

clean-generic:

distclean-generic:
	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
	-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)

maintainer-clean-generic:
	@echo "This command is intended for maintainers to use"
	@echo "it deletes files that may require special tools to rebuild."
clean: clean-am

clean-am: clean-generic clean-libtool mostlyclean-am

distclean: distclean-am
	-rm -f Makefile
distclean-am: clean-am distclean-generic

dvi: dvi-am

dvi-am:

html: html-am

html-am:

info: info-am

info-am:

install-data-am: install-dist_apidocDATA

install-dvi: install-dvi-am

install-dvi-am:

install-exec-am:

install-html: install-html-am

install-html-am:

install-info: install-info-am

install-info-am:

install-man:

install-pdf: install-pdf-am

install-pdf-am:

install-ps: install-ps-am

install-ps-am:

installcheck-am:

maintainer-clean: maintainer-clean-am
	-rm -f Makefile
maintainer-clean-am: distclean-am maintainer-clean-generic

mostlyclean: mostlyclean-am

mostlyclean-am: mostlyclean-generic mostlyclean-libtool

pdf: pdf-am

pdf-am:

ps: ps-am

ps-am:

uninstall-am: uninstall-dist_apidocDATA

.MAKE: install-am install-strip

.PHONY: all all-am check check-am clean clean-generic clean-libtool \
	distclean distclean-generic distclean-libtool distdir dvi \
	dvi-am html html-am info info-am install install-am \
	install-data install-data-am install-dist_apidocDATA \
	install-dvi install-dvi-am install-exec install-exec-am \
	install-html install-html-am install-info install-info-am \
	install-man install-pdf install-pdf-am install-ps \
	install-ps-am install-strip installcheck installcheck-am \
	installdirs maintainer-clean maintainer-clean-generic \
	mostlyclean mostlyclean-generic mostlyclean-libtool pdf pdf-am \
	ps ps-am uninstall uninstall-am uninstall-dist_apidocDATA

update-doc-version:
	@YEAR=$$(date +%Y); DAY=$$(date +%Y%m%d);					\
	for f in $(srcdir)/*.html; do							\
		sed -e "s/2000-[0-9]\{4\} Xiph.Org/2000-$$YEAR Xiph.Org/g"		\
		    -e "s/libogg release [0-9. -]\+/libogg release $(VERSION) - $$DAY/g"\
			< $$f > $$f.tmp;						\
		if diff -q $$f $$f.tmp > /dev/null; then				\
			rm $$f.tmp;							\
		else									\
			mv $$f.tmp $$f;							\
		fi;									\
	done;

# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:


text:
//*********************************************************//
//    Copyright (c) Microsoft. All rights reserved.
//
//    Apache 2.0 License
//
//    You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
//    implied. See the License for the specific language governing
//    permissions and limitations under the License.
//
//*********************************************************//

using System;
using System.Runtime.InteropServices;

namespace Microsoft.VisualStudioTools.Project {
    internal static class UnsafeNativeMethods {
        [DllImport(ExternDll.Kernel32, EntryPoint = "GlobalLock", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        internal static extern IntPtr GlobalLock(IntPtr h);

        [DllImport(ExternDll.Kernel32, EntryPoint = "GlobalUnlock", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        internal static extern bool GlobalUnLock(IntPtr h);

        [DllImport(ExternDll.Kernel32, EntryPoint = "GlobalSize", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        internal static extern IntPtr GlobalSize(IntPtr h);

        [DllImport(ExternDll.Ole32, ExactSpelling = true, CharSet = CharSet.Unicode)]
        internal static extern int OleSetClipboard(Microsoft.VisualStudio.OLE.Interop.IDataObject dataObject);

        [DllImport(ExternDll.Ole32, ExactSpelling = true, CharSet = CharSet.Unicode)]
        internal static extern int OleGetClipboard(out Microsoft.VisualStudio.OLE.Interop.IDataObject dataObject);

        [DllImport(ExternDll.Ole32, ExactSpelling = true, CharSet = CharSet.Unicode)]
        internal static extern int OleFlushClipboard();

        [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Unicode)]
        internal static extern int OpenClipboard(IntPtr newOwner);

        [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Unicode)]
        internal static extern int EmptyClipboard();

        [DllImport(ExternDll.User32, ExactSpelling = true, CharSet = CharSet.Unicode)]
        internal static extern int CloseClipboard();

        [DllImport(ExternDll.Comctl32, CharSet = CharSet.Auto)]
        internal static extern int ImageList_GetImageCount(HandleRef himl);

        [DllImport(ExternDll.Comctl32, CharSet = CharSet.Auto)]
        internal static extern bool ImageList_Draw(HandleRef himl, int i, HandleRef hdcDst, int x, int y, int fStyle);

        [DllImport(ExternDll.Shell32, EntryPoint = "DragQueryFileW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        internal static extern uint DragQueryFile(IntPtr hDrop, uint iFile, char[] lpszFile, uint cch);

        [DllImport(ExternDll.User32, SetLastError = true, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
        internal static extern uint RegisterClipboardFormat(string format);
    }
}


text:
package storage::synology::snmp::mode::components::fan;

use strict;
use warnings;

my %map_status = (1 => 'Normal', 2 => 'Failed');

my $mapping = {
    synoSystemsystemFanStatus   => { oid => '.1.3.6.1.4.1.6574.1.4.1', map => \%map_status  },
    synoSystemcpuFanStatus      => { oid => '.1.3.6.1.4.1.6574.1.4.2', map => \%map_status  },
};
my $oid_fan = '.1.3.6.1.4.1.6574.1.4';

sub load {
    my ($self) = @_;

    push @{$self->{request}}, { oid => $oid_fan };
}

sub check {
    my ($self) = @_;

    $self->{output}->output_add(long_msg => "Checking cpu fan");
    $self->{components}->{fan} = {name => 'fan', total => 0, skip => 0};
    return if ($self->check_filter(section => 'fan'));

    my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$oid_fan}, instance => '0');
    if (!$self->check_filter(section => 'fan', instance => 'cpu')) {
        $self->{components}->{fan}->{total}++;

        $self->{output}->output_add(long_msg => sprintf("cpu fan state is %s.",
                                          $result->{synoSystemcpuFanStatus}));
        my $exit = $self->get_severity(label => 'default', section => 'fan', instance => 'cpu', value => $result->{synoSystemcpuFanStatus});
        if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) {
            $self->{output}->output_add(severity => $exit,
                                        short_msg => sprintf("CPU fan status is %s", $result->{synoSystemcpuFanStatus}));
        }
    }

    if (!$self->check_filter(section => 'fan', instance => 'system')) {
        $self->{components}->{fan}->{total}++;
        $self->{output}->output_add(long_msg => sprintf("system fan state is %s.",
                                        $result->{synoSystemsystemFanStatus}));
        my $exit = $self->get_severity(label => 'default', section => 'fan', instance => 'system', value => $result->{synoSystemsystemFanStatus});
        if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) {
            $self->{output}->output_add(severity => $exit,
                                        short_msg => sprintf("System fan status is %s", $result->{synoSystemsystemFanStatus}));
        }
    }
}

1;


text:
import { noRegistryFunctionReturn } from '../../../config/errors';
import { warnIfDebug } from '../../../utils/log';
import parser from '../../../Ractive/config/custom/template/parser';
import { findInstance } from '../../../shared/registry';

export default function getPartialTemplate ( ractive, name, parentFragment ) {
	var partial;

	// If the partial in instance or view heirarchy instances, great
	if ( partial = getPartialFromRegistry( ractive, name, parentFragment || {} ) ) {
		return partial;
	}

	// Does it exist on the page as a script tag?
	partial = parser.fromId( name, { noThrow: true } );

	if ( partial ) {
		// parse and register to this ractive instance
		let parsed = parser.parse( partial, parser.getParseOptions( ractive ) );

		// register (and return main partial if there are others in the template)
		return ractive.partials[ name ] = parsed.t;
	}
}

function getPartialFromRegistry ( ractive, name, parentFragment ) {
	let fn, partial = findParentPartial( name, parentFragment.owner );

	// if there was an instance up-hierarchy, cool
	if ( partial ) return partial;

	// find first instance in the ractive or view hierarchy that has this partial
	var instance = findInstance( 'partials', ractive, name );

	if ( !instance ) { return; }

	partial = instance.partials[ name ];

	// partial is a function?
	if ( typeof partial === 'function' ) {
		fn = partial.bind( instance );
		fn.isOwner = instance.partials.hasOwnProperty(name);
		partial = fn.call( ractive, parser );
	}

	if ( !partial && partial !== '' ) {
		warnIfDebug( noRegistryFunctionReturn, name, 'partial', 'partial', { ractive });
		return;
	}

	// If this was added manually to the registry,
	// but hasn't been parsed, parse it now
	if ( !parser.isParsed( partial ) ) {

		// use the parseOptions of the ractive instance on which it was found
		let parsed = parser.parse( partial, parser.getParseOptions( instance ) );

		// Partials cannot contain nested partials!
		// TODO add a test for this
		if ( parsed.p ) {
			warnIfDebug( 'Partials ({{>%s}}) cannot contain nested inline partials', name, { ractive });
		}

		// if fn, use instance to store result, otherwise needs to go
		// in the correct point in prototype chain on instance or constructor
		let target = fn ? instance : findOwner( instance, name );

		// may be a template with partials, which need to be registered and main template extracted
		target.partials[ name ] = partial = parsed.t;
	}

	// store for reset
	if ( fn ) {
		partial._fn = fn;
	}

	return partial.v ? partial.t : partial;
}

function findOwner ( ractive, key ) {
	return ractive.partials.hasOwnProperty( key )
		? ractive
		: findConstructor( ractive.constructor, key);
}

function findConstructor ( constructor, key ) {
	if ( !constructor ) { return; }
	return constructor.partials.hasOwnProperty( key )
		? constructor
		: findConstructor( constructor._Parent, key );
}

function findParentPartial( name, parent ) {
	if ( parent ) {
		if ( parent.template && parent.template.p && parent.template.p[name] ) {
			return parent.template.p[name];
		} else if ( parent.parentFragment && parent.parentFragment.owner ) {
			return findParentPartial( name, parent.parentFragment.owner );
		}
	}
}