text:
package android.app;

import com.android.internal.util.ArrayUtils;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.IIntentReceiver;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageManager;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.CompatibilityInfo;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Process;
import android.os.RemoteException;
import android.os.StrictMode;
import android.os.Trace;
import android.os.UserHandle;
import android.util.AndroidRuntimeException;
import android.util.Slog;
import android.view.CompatibilityInfoHolder;
import android.view.Display;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;

final class IntentReceiverLeaked extends AndroidRuntimeException {
    public IntentReceiverLeaked(String msg) {
        super(msg);
    }
}

final class ServiceConnectionLeaked extends AndroidRuntimeException {
    public ServiceConnectionLeaked(String msg) {
        super(msg);
    }
}

/**
 * Local state maintained about a currently loaded .apk.
 * @hide
 */
public final class LoadedApk {

    private static final String TAG = "LoadedApk";

    private final ActivityThread mActivityThread;
    private final ApplicationInfo mApplicationInfo;
    final String mPackageName;
    private final String mAppDir;
    private final String mResDir;
    private final String[] mSharedLibraries;
    private final String mDataDir;
    private final String mLibDir;
    private final File mDataDirFile;
    private final ClassLoader mBaseClassLoader;
    private final boolean mSecurityViolation;
    private final boolean mIncludeCode;
    public final CompatibilityInfoHolder mCompatibilityInfo = new CompatibilityInfoHolder();
    Resources mResources;
    private ClassLoader mClassLoader;
    private Application mApplication;

    private final HashMap<Context, HashMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher>> mReceivers
        = new HashMap<Context, HashMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher>>();
    private final HashMap<Context, HashMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher>> mUnregisteredReceivers
    = new HashMap<Context, HashMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher>>();
    private final HashMap<Context, HashMap<ServiceConnection, LoadedApk.ServiceDispatcher>> mServices
        = new HashMap<Context, HashMap<ServiceConnection, LoadedApk.ServiceDispatcher>>();
    private final HashMap<Context, HashMap<ServiceConnection, LoadedApk.ServiceDispatcher>> mUnboundServices
        = new HashMap<Context, HashMap<ServiceConnection, LoadedApk.ServiceDispatcher>>();

    int mClientCount = 0;

    Application getApplication() {
        return mApplication;
    }

    /**
     * Create information about a new .apk
     *
     * NOTE: This constructor is called with ActivityThread's lock held,
     * so MUST NOT call back out to the activity manager.
     */
    public LoadedApk(ActivityThread activityThread, ApplicationInfo aInfo,
            CompatibilityInfo compatInfo,
            ActivityThread mainThread, ClassLoader baseLoader,
            boolean securityViolation, boolean includeCode) {
        mActivityThread = activityThread;
        mApplicationInfo = aInfo;
        mPackageName = aInfo.packageName;
        mAppDir = aInfo.sourceDir;
        final int myUid = Process.myUid();
        mResDir = aInfo.uid == myUid ? aInfo.sourceDir
                : aInfo.publicSourceDir;
        if (!UserHandle.isSameUser(aInfo.uid, myUid) && !Process.isIsolated()) {
            aInfo.dataDir = PackageManager.getDataDirForUser(UserHandle.getUserId(myUid),
                    mPackageName);
        }
        mSharedLibraries = aInfo.sharedLibraryFiles;
        mDataDir = aInfo.dataDir;
        mDataDirFile = mDataDir != null ? new File(mDataDir) : null;
        mLibDir = aInfo.nativeLibraryDir;
        mBaseClassLoader = baseLoader;
        mSecurityViolation = securityViolation;
        mIncludeCode = includeCode;
        mCompatibilityInfo.set(compatInfo);

        if (mAppDir == null) {
            if (ActivityThread.mSystemContext == null) {
                ActivityThread.mSystemContext =
                    ContextImpl.createSystemContext(mainThread);
                ActivityThread.mSystemContext.getResources().updateConfiguration(
                         mainThread.getConfiguration(),
                         mainThread.getDisplayMetricsLocked(
                                 Display.DEFAULT_DISPLAY, compatInfo),
                         compatInfo);
                //Slog.i(TAG, "Created system resources "
                //        + mSystemContext.getResources() + ": "
                //        + mSystemContext.getResources().getConfiguration());
            }
            mClassLoader = ActivityThread.mSystemContext.getClassLoader();
            mResources = ActivityThread.mSystemContext.getResources();
        }
    }

    public LoadedApk(ActivityThread activityThread, String name,
            Context systemContext, ApplicationInfo info, CompatibilityInfo compatInfo) {
        mActivityThread = activityThread;
        mApplicationInfo = info != null ? info : new ApplicationInfo();
        mApplicationInfo.packageName = name;
        mPackageName = name;
        mAppDir = null;
        mResDir = null;
        mSharedLibraries = null;
        mDataDir = null;
        mDataDirFile = null;
        mLibDir = null;
        mBaseClassLoader = null;
        mSecurityViolation = false;
        mIncludeCode = true;
        mClassLoader = systemContext.getClassLoader();
        mResources = systemContext.getResources();
        mCompatibilityInfo.set(compatInfo);
    }

    public String getPackageName() {
        return mPackageName;
    }

    public ApplicationInfo getApplicationInfo() {
        return mApplicationInfo;
    }

    public boolean isSecurityViolation() {
        return mSecurityViolation;
    }

    /**
     * Gets the array of shared libraries that are listed as
     * used by the given package.
     *
     * @param packageName the name of the package (note: not its
     * file name)
     * @return null-ok; the array of shared libraries, each one
     * a fully-qualified path
     */
    private static String[] getLibrariesFor(String packageName) {
        ApplicationInfo ai = null;
        try {
            ai = ActivityThread.getPackageManager().getApplicationInfo(packageName,
                    PackageManager.GET_SHARED_LIBRARY_FILES, UserHandle.myUserId());
        } catch (RemoteException e) {
            throw new AssertionError(e);
        }

        if (ai == null) {
            return null;
        }

        return ai.sharedLibraryFiles;
    }

    /**
     * Combines two arrays (of library names) such that they are
     * concatenated in order but are devoid of duplicates. The
     * result is a single string with the names of the libraries
     * separated by colons, or null if both lists
     * were null or empty.
     *
     * @param list1 null-ok; the first list
     * @param list2 null-ok; the second list
     * @return null-ok; the combination
     */
    private static String combineLibs(String[] list1, String[] list2) {
        StringBuilder result = new StringBuilder(300);
        boolean first = true;

        if (list1 != null) {
            for (String s : list1) {
                if (first) {
                    first = false;
                } else {
                    result.append(':');
                }
                result.append(s);
            }
        }

        // Only need to check for duplicates if list1 was non-empty.
        boolean dupCheck = !first;

        if (list2 != null) {
            for (String s : list2) {
                if (dupCheck && ArrayUtils.contains(list1, s)) {
                    continue;
                }

                if (first) {
                    first = false;
                } else {
                    result.append(':');
                }
                result.append(s);
            }
        }

        return result.toString();
    }

    public ClassLoader getClassLoader() {
        synchronized (this) {
            if (mClassLoader != null) {
                return mClassLoader;
            }

            if (mIncludeCode && !mPackageName.equals("android")) {
                String zip = mAppDir;
                String libraryPath = mLibDir;

                /*
                 * The following is a bit of a hack to inject
                 * instrumentation into the system: If the app
                 * being started matches one of the instrumentation names,
                 * then we combine both the "instrumentation" and
                 * "instrumented" app into the path, along with the
                 * concatenation of both apps' shared library lists.
                 */

                String instrumentationAppDir =
                        mActivityThread.mInstrumentationAppDir;
                String instrumentationAppLibraryDir =
                        mActivityThread.mInstrumentationAppLibraryDir;
                String instrumentationAppPackage =
                        mActivityThread.mInstrumentationAppPackage;
                String instrumentedAppDir =
                        mActivityThread.mInstrumentedAppDir;
                String instrumentedAppLibraryDir =
                        mActivityThread.mInstrumentedAppLibraryDir;
                String[] instrumentationLibs = null;

                if (mAppDir.equals(instrumentationAppDir)
                        || mAppDir.equals(instrumentedAppDir)) {
                    zip = instrumentationAppDir + ":" + instrumentedAppDir;
                    libraryPath = instrumentationAppLibraryDir + ":" + instrumentedAppLibraryDir;
                    if (! instrumentedAppDir.equals(instrumentationAppDir)) {
                        instrumentationLibs =
                            getLibrariesFor(instrumentationAppPackage);
                    }
                }

                if ((mSharedLibraries != null) ||
                        (instrumentationLibs != null)) {
                    zip =
                        combineLibs(mSharedLibraries, instrumentationLibs)
                        + ':' + zip;
                }

                /*
                 * With all the combination done (if necessary, actually
                 * create the class loader.
                 */

                if (ActivityThread.localLOGV)
                    Slog.v(ActivityThread.TAG, "Class path: " + zip + ", JNI path: " + libraryPath);

                // Temporarily disable logging of disk reads on the Looper thread
                // as this is early and necessary.
                StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();

                mClassLoader =
                    ApplicationLoaders.getDefault().getClassLoader(
                        zip, libraryPath, mBaseClassLoader);
                initializeJavaContextClassLoader();

                StrictMode.setThreadPolicy(oldPolicy);
            } else {
                if (mBaseClassLoader == null) {
                    mClassLoader = ClassLoader.getSystemClassLoader();
                } else {
                    mClassLoader = mBaseClassLoader;
                }
            }
            return mClassLoader;
        }
    }

    /**
     * Setup value for Thread.getContextClassLoader(). If the
     * package will not run in in a VM with other packages, we set
     * the Java context ClassLoader to the
     * PackageInfo.getClassLoader value. However, if this VM can
     * contain multiple packages, we intead set the Java context
     * ClassLoader to a proxy that will warn about the use of Java
     * context ClassLoaders and then fall through to use the
     * system ClassLoader.
     *
     *
 Note that this is similar to but not the same as the
     * android.content.Context.getClassLoader(). While both
     * context class loaders are typically set to the
     * PathClassLoader used to load the package archive in the
     * single application per VM case, a single Android process
     * may contain several Contexts executing on one thread with
     * their own logical ClassLoaders while the Java context
     * ClassLoader is a thread local. This is why in the case when
     * we have multiple packages per VM we do not set the Java
     * context ClassLoader to an arbitrary but instead warn the
     * user to set their own if we detect that they are using a
     * Java library that expects it to be set.
     */
    private void initializeJavaContextClassLoader() {
        IPackageManager pm = ActivityThread.getPackageManager();
        android.content.pm.PackageInfo pi;
        try {
            pi = pm.getPackageInfo(mPackageName, 0, UserHandle.myUserId());
        } catch (RemoteException e) {
            throw new AssertionError(e);
        }
        /*
         * Two possible indications that this package could be
         * sharing its virtual machine with other packages:
         *
         * 1.) the sharedUserId attribute is set in the manifest,
         *     indicating a request to share a VM with other
         *     packages with the same sharedUserId.
         *
         * 2.) the application element of the manifest has an
         *     attribute specifying a non-default process name,
         *     indicating the desire to run in another packages VM.
         */
        boolean sharedUserIdSet = (pi.sharedUserId != null);
        boolean processNameNotDefault =
            (pi.applicationInfo != null &&
             !mPackageName.equals(pi.applicationInfo.processName));
        boolean sharable = (sharedUserIdSet || processNameNotDefault);
        ClassLoader contextClassLoader =
            (sharable)
            ? new WarningContextClassLoader()
            : mClassLoader;
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }

    private static class WarningContextClassLoader extends ClassLoader {

        private static boolean warned = false;

        private void warn(String methodName) {
            if (warned) {
                return;
            }
            warned = true;
            Thread.currentThread().setContextClassLoader(getParent());
            Slog.w(ActivityThread.TAG, "ClassLoader." + methodName + ": " +
                  "The class loader returned by " +
                  "Thread.getContextClassLoader() may fail for processes " +
                  "that host multiple applications. You should explicitly " +
                  "specify a context class loader. For example: " +
                  "Thread.setContextClassLoader(getClass().getClassLoader());");
        }

        @Override public URL getResource(String resName) {
            warn("getResource");
            return getParent().getResource(resName);
        }

        @Override public Enumeration<URL> getResources(String resName) throws IOException {
            warn("getResources");
            return getParent().getResources(resName);
        }

        @Override public InputStream getResourceAsStream(String resName) {
            warn("getResourceAsStream");
            return getParent().getResourceAsStream(resName);
        }

        @Override public Class<?> loadClass(String className) throws ClassNotFoundException {
            warn("loadClass");
            return getParent().loadClass(className);
        }

        @Override public void setClassAssertionStatus(String cname, boolean enable) {
            warn("setClassAssertionStatus");
            getParent().setClassAssertionStatus(cname, enable);
        }

        @Override public void setPackageAssertionStatus(String pname, boolean enable) {
            warn("setPackageAssertionStatus");
            getParent().setPackageAssertionStatus(pname, enable);
        }

        @Override public void setDefaultAssertionStatus(boolean enable) {
            warn("setDefaultAssertionStatus");
            getParent().setDefaultAssertionStatus(enable);
        }

        @Override public void clearAssertionStatus() {
            warn("clearAssertionStatus");
            getParent().clearAssertionStatus();
        }
    }

    public String getAppDir() {
        return mAppDir;
    }

    public String getLibDir() {
        return mLibDir;
    }

    public String getResDir() {
        return mResDir;
    }

    public String getDataDir() {
        return mDataDir;
    }

    public File getDataDirFile() {
        return mDataDirFile;
    }

    public AssetManager getAssets(ActivityThread mainThread) {
        return getResources(mainThread).getAssets();
    }

    public Resources getResources(ActivityThread mainThread) {
        if (mResources == null) {
            mResources = mainThread.getTopLevelResources(mResDir,
                    Display.DEFAULT_DISPLAY, null, this);
        }
        return mResources;
    }

    public Application makeApplication(boolean forceDefaultAppClass,
            Instrumentation instrumentation) {
        if (mApplication != null) {
            return mApplication;
        }

        Application app = null;

        String appClass = mApplicationInfo.className;
        if (forceDefaultAppClass || (appClass == null)) {
            appClass = "android.app.Application";
        }

        try {
            java.lang.ClassLoader cl = getClassLoader();
            ContextImpl appContext = new ContextImpl();
            appContext.init(this, null, mActivityThread);
            app = mActivityThread.mInstrumentation.newApplication(
                    cl, appClass, appContext);
            appContext.setOuterContext(app);
        } catch (Exception e) {
            if (!mActivityThread.mInstrumentation.onException(app, e)) {
                throw new RuntimeException(
                    "Unable to instantiate application " + appClass
                    + ": " + e.toString(), e);
            }
        }
        mActivityThread.mAllApplications.add(app);
        mApplication = app;

        if (instrumentation != null) {
            try {
                instrumentation.callApplicationOnCreate(app);
            } catch (Exception e) {
                if (!instrumentation.onException(app, e)) {
                    throw new RuntimeException(
                        "Unable to create application " + app.getClass().getName()
                        + ": " + e.toString(), e);
                }
            }
        }

        return app;
    }

    public void removeContextRegistrations(Context context,
            String who, String what) {
        final boolean reportRegistrationLeaks = StrictMode.vmRegistrationLeaksEnabled();
        HashMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher> rmap =
            mReceivers.remove(context);
        if (rmap != null) {
            Iterator<LoadedApk.ReceiverDispatcher> it = rmap.values().iterator();
            while (it.hasNext()) {
                LoadedApk.ReceiverDispatcher rd = it.next();
                IntentReceiverLeaked leak = new IntentReceiverLeaked(
                        what + " " + who + " has leaked IntentReceiver "
                        + rd.getIntentReceiver() + " that was " +
                        "originally registered here. Are you missing a " +
                        "call to unregisterReceiver()?");
                leak.setStackTrace(rd.getLocation().getStackTrace());
                Slog.e(ActivityThread.TAG, leak.getMessage(), leak);
                if (reportRegistrationLeaks) {
                    StrictMode.onIntentReceiverLeaked(leak);
                }
                try {
                    ActivityManagerNative.getDefault().unregisterReceiver(
                            rd.getIIntentReceiver());
                } catch (RemoteException e) {
                    // system crashed, nothing we can do
                }
            }
        }
        mUnregisteredReceivers.remove(context);
        //Slog.i(TAG, "Receiver registrations: " + mReceivers);
        HashMap<ServiceConnection, LoadedApk.ServiceDispatcher> smap =
            mServices.remove(context);
        if (smap != null) {
            Iterator<LoadedApk.ServiceDispatcher> it = smap.values().iterator();
            while (it.hasNext()) {
                LoadedApk.ServiceDispatcher sd = it.next();
                ServiceConnectionLeaked leak = new ServiceConnectionLeaked(
                        what + " " + who + " has leaked ServiceConnection "
                        + sd.getServiceConnection() + " that was originally bound here");
                leak.setStackTrace(sd.getLocation().getStackTrace());
                Slog.e(ActivityThread.TAG, leak.getMessage(), leak);
                if (reportRegistrationLeaks) {
                    StrictMode.onServiceConnectionLeaked(leak);
                }
                try {
                    ActivityManagerNative.getDefault().unbindService(
                            sd.getIServiceConnection());
                } catch (RemoteException e) {
                    // system crashed, nothing we can do
                }
                sd.doForget();
            }
        }
        mUnboundServices.remove(context);
        //Slog.i(TAG, "Service registrations: " + mServices);
    }

    public IIntentReceiver getReceiverDispatcher(BroadcastReceiver r,
            Context context, Handler handler,
            Instrumentation instrumentation, boolean registered) {
        synchronized (mReceivers) {
            LoadedApk.ReceiverDispatcher rd = null;
            HashMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher> map = null;
            if (registered) {
                map = mReceivers.get(context);
                if (map != null) {
                    rd = map.get(r);
                }
            }
            if (rd == null) {
                rd = new ReceiverDispatcher(r, context, handler,
                        instrumentation, registered);
                if (registered) {
                    if (map == null) {
                        map = new HashMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher>();
                        mReceivers.put(context, map);
                    }
                    map.put(r, rd);
                }
            } else {
                rd.validate(context, handler);
            }
            rd.mForgotten = false;
            return rd.getIIntentReceiver();
        }
    }

    public IIntentReceiver forgetReceiverDispatcher(Context context,
            BroadcastReceiver r) {
        synchronized (mReceivers) {
            HashMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher> map = mReceivers.get(context);
            LoadedApk.ReceiverDispatcher rd = null;
            if (map != null) {
                rd = map.get(r);
                if (rd != null) {
                    map.remove(r);
                    if (map.size() == 0) {
                        mReceivers.remove(context);
                    }
                    if (r.getDebugUnregister()) {
                        HashMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher> holder
                                = mUnregisteredReceivers.get(context);
                        if (holder == null) {
                            holder = new HashMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher>();
                            mUnregisteredReceivers.put(context, holder);
                        }
                        RuntimeException ex = new IllegalArgumentException(
                                "Originally unregistered here:");
                        ex.fillInStackTrace();
                        rd.setUnregisterLocation(ex);
                        holder.put(r, rd);
                    }
                    rd.mForgotten = true;
                    return rd.getIIntentReceiver();
                }
            }
            HashMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher> holder
                    = mUnregisteredReceivers.get(context);
            if (holder != null) {
                rd = holder.get(r);
                if (rd != null) {
                    RuntimeException ex = rd.getUnregisterLocation();
                    throw new IllegalArgumentException(
                            "Unregistering Receiver " + r
                            + " that was already unregistered", ex);
                }
            }
            if (context == null) {
                throw new IllegalStateException("Unbinding Receiver " + r
                        + " from Context that is no longer in use: " + context);
            } else {
                throw new IllegalArgumentException("Receiver not registered: " + r);
            }

        }
    }

    static final class ReceiverDispatcher {

        final static class InnerReceiver extends IIntentReceiver.Stub {
            final WeakReference<LoadedApk.ReceiverDispatcher> mDispatcher;
            final LoadedApk.ReceiverDispatcher mStrongRef;

            InnerReceiver(LoadedApk.ReceiverDispatcher rd, boolean strong) {
                mDispatcher = new WeakReference<LoadedApk.ReceiverDispatcher>(rd);
                mStrongRef = strong ? rd : null;
            }
            public void performReceive(Intent intent, int resultCode, String data,
                    Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
                LoadedApk.ReceiverDispatcher rd = mDispatcher.get();
                if (ActivityThread.DEBUG_BROADCAST) {
                    int seq = intent.getIntExtra("seq", -1);
                    Slog.i(ActivityThread.TAG, "Receiving broadcast " + intent.getAction() + " seq=" + seq
                            + " to " + (rd != null ? rd.mReceiver : null));
                }
                if (rd != null) {
                    rd.performReceive(intent, resultCode, data, extras,
                            ordered, sticky, sendingUser);
                } else {
                    // The activity manager dispatched a broadcast to a registered
                    // receiver in this process, but before it could be delivered the
                    // receiver was unregistered.  Acknowledge the broadcast on its
                    // behalf so that the system's broadcast sequence can continue.
                    if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,
                            "Finishing broadcast to unregistered receiver");
                    IActivityManager mgr = ActivityManagerNative.getDefault();
                    try {
                        if (extras != null) {
                            extras.setAllowFds(false);
                        }
                        mgr.finishReceiver(this, resultCode, data, extras, false);
                    } catch (RemoteException e) {
                        Slog.w(ActivityThread.TAG, "Couldn't finish broadcast to unregistered receiver");
                    }
                }
            }
        }

        final IIntentReceiver.Stub mIIntentReceiver;
        final BroadcastReceiver mReceiver;
        final Context mContext;
        final Handler mActivityThread;
        final Instrumentation mInstrumentation;
        final boolean mRegistered;
        final IntentReceiverLeaked mLocation;
        RuntimeException mUnregisterLocation;
        boolean mForgotten;

        final class Args extends BroadcastReceiver.PendingResult implements Runnable {
            private Intent mCurIntent;
            private final boolean mOrdered;

            public Args(Intent intent, int resultCode, String resultData, Bundle resultExtras,
                    boolean ordered, boolean sticky, int sendingUser) {
                super(resultCode, resultData, resultExtras,
                        mRegistered ? TYPE_REGISTERED : TYPE_UNREGISTERED,
                        ordered, sticky, mIIntentReceiver.asBinder(), sendingUser);
                mCurIntent = intent;
                mOrdered = ordered;
            }

            public void run() {
                final BroadcastReceiver receiver = mReceiver;
                final boolean ordered = mOrdered;

                if (ActivityThread.DEBUG_BROADCAST) {
                    int seq = mCurIntent.getIntExtra("seq", -1);
                    Slog.i(ActivityThread.TAG, "Dispatching broadcast " + mCurIntent.getAction()
                            + " seq=" + seq + " to " + mReceiver);
                    Slog.i(ActivityThread.TAG, "  mRegistered=" + mRegistered
                            + " mOrderedHint=" + ordered);
                }

                final IActivityManager mgr = ActivityManagerNative.getDefault();
                final Intent intent = mCurIntent;
                mCurIntent = null;

                if (receiver == null || mForgotten) {
                    if (mRegistered && ordered) {
                        if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,
                                "Finishing null broadcast to " + mReceiver);
                        sendFinished(mgr);
                    }
                    return;
                }

                Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastReceiveReg");
                try {
                    ClassLoader cl =  mReceiver.getClass().getClassLoader();
                    intent.setExtrasClassLoader(cl);
                    setExtrasClassLoader(cl);
                    receiver.setPendingResult(this);
                    receiver.onReceive(mContext, intent);
                } catch (Exception e) {
                    if (mRegistered && ordered) {
                        if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,
                                "Finishing failed broadcast to " + mReceiver);
                        sendFinished(mgr);
                    }
                    if (mInstrumentation == null ||
                            !mInstrumentation.onException(mReceiver, e)) {
                        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                        throw new RuntimeException(
                            "Error receiving broadcast " + intent
                            + " in " + mReceiver, e);
                    }
                }

                if (receiver.getPendingResult() != null) {
                    finish();
                }
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
            }
        }

        ReceiverDispatcher(BroadcastReceiver receiver, Context context,
                Handler activityThread, Instrumentation instrumentation,
                boolean registered) {
            if (activityThread == null) {
                throw new NullPointerException("Handler must not be null");
            }

            mIIntentReceiver = new InnerReceiver(this, !registered);
            mReceiver = receiver;
            mContext = context;
            mActivityThread = activityThread;
            mInstrumentation = instrumentation;
            mRegistered = registered;
            mLocation = new IntentReceiverLeaked(null);
            mLocation.fillInStackTrace();
        }

        void validate(Context context, Handler activityThread) {
            if (mContext != context) {
                throw new IllegalStateException(
                    "Receiver " + mReceiver +
                    " registered with differing Context (was " +
                    mContext + " now " + context + ")");
            }
            if (mActivityThread != activityThread) {
                throw new IllegalStateException(
                    "Receiver " + mReceiver +
                    " registered with differing handler (was " +
                    mActivityThread + " now " + activityThread + ")");
            }
        }

        IntentReceiverLeaked getLocation() {
            return mLocation;
        }

        BroadcastReceiver getIntentReceiver() {
            return mReceiver;
        }

        IIntentReceiver getIIntentReceiver() {
            return mIIntentReceiver;
        }

        void setUnregisterLocation(RuntimeException ex) {
            mUnregisterLocation = ex;
        }

        RuntimeException getUnregisterLocation() {
            return mUnregisterLocation;
        }

        public void performReceive(Intent intent, int resultCode, String data,
                Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
            if (ActivityThread.DEBUG_BROADCAST) {
                int seq = intent.getIntExtra("seq", -1);
                Slog.i(ActivityThread.TAG, "Enqueueing broadcast " + intent.getAction() + " seq=" + seq
                        + " to " + mReceiver);
            }
            Args args = new Args(intent, resultCode, data, extras, ordered,
                    sticky, sendingUser);
            if (!mActivityThread.post(args)) {
                if (mRegistered && ordered) {
                    IActivityManager mgr = ActivityManagerNative.getDefault();
                    if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,
                            "Finishing sync broadcast to " + mReceiver);
                    args.sendFinished(mgr);
                }
            }
        }

    }

    public final IServiceConnection getServiceDispatcher(ServiceConnection c,
            Context context, Handler handler, int flags) {
        synchronized (mServices) {
            LoadedApk.ServiceDispatcher sd = null;
            HashMap<ServiceConnection, LoadedApk.ServiceDispatcher> map = mServices.get(context);
            if (map != null) {
                sd = map.get(c);
            }
            if (sd == null) {
                sd = new ServiceDispatcher(c, context, handler, flags);
                if (map == null) {
                    map = new HashMap<ServiceConnection, LoadedApk.ServiceDispatcher>();
                    mServices.put(context, map);
                }
                map.put(c, sd);
            } else {
                sd.validate(context, handler);
            }
            return sd.getIServiceConnection();
        }
    }

    public final IServiceConnection forgetServiceDispatcher(Context context,
            ServiceConnection c) {
        synchronized (mServices) {
            HashMap<ServiceConnection, LoadedApk.ServiceDispatcher> map
                    = mServices.get(context);
            LoadedApk.ServiceDispatcher sd = null;
            if (map != null) {
                sd = map.get(c);
                if (sd != null) {
                    map.remove(c);
                    sd.doForget();
                    if (map.size() == 0) {
                        mServices.remove(context);
                    }
                    if ((sd.getFlags()&Context.BIND_DEBUG_UNBIND) != 0) {
                        HashMap<ServiceConnection, LoadedApk.ServiceDispatcher> holder
                                = mUnboundServices.get(context);
                        if (holder == null) {
                            holder = new HashMap<ServiceConnection, LoadedApk.ServiceDispatcher>();
                            mUnboundServices.put(context, holder);
                        }
                        RuntimeException ex = new IllegalArgumentException(
                                "Originally unbound here:");
                        ex.fillInStackTrace();
                        sd.setUnbindLocation(ex);
                        holder.put(c, sd);
                    }
                    return sd.getIServiceConnection();
                }
            }
            HashMap<ServiceConnection, LoadedApk.ServiceDispatcher> holder
                    = mUnboundServices.get(context);
            if (holder != null) {
                sd = holder.get(c);
                if (sd != null) {
                    RuntimeException ex = sd.getUnbindLocation();
                    throw new IllegalArgumentException(
                            "Unbinding Service " + c
                            + " that was already unbound", ex);
                }
            }
            if (context == null) {
                throw new IllegalStateException("Unbinding Service " + c
                        + " from Context that is no longer in use: " + context);
            } else {
                throw new IllegalArgumentException("Service not registered: " + c);
            }
        }
    }

    static final class ServiceDispatcher {
        private final ServiceDispatcher.InnerConnection mIServiceConnection;
        private final ServiceConnection mConnection;
        private final Context mContext;
        private final Handler mActivityThread;
        private final ServiceConnectionLeaked mLocation;
        private final int mFlags;

        private RuntimeException mUnbindLocation;

        private boolean mDied;
        private boolean mForgotten;

        private static class ConnectionInfo {
            IBinder binder;
            IBinder.DeathRecipient deathMonitor;
        }

        private static class InnerConnection extends IServiceConnection.Stub {
            final WeakReference<LoadedApk.ServiceDispatcher> mDispatcher;

            InnerConnection(LoadedApk.ServiceDispatcher sd) {
                mDispatcher = new WeakReference<LoadedApk.ServiceDispatcher>(sd);
            }

            public void connected(ComponentName name, IBinder service) throws RemoteException {
                LoadedApk.ServiceDispatcher sd = mDispatcher.get();
                if (sd != null) {
                    sd.connected(name, service);
                }
            }
        }

        private final HashMap<ComponentName, ServiceDispatcher.ConnectionInfo> mActiveConnections
            = new HashMap<ComponentName, ServiceDispatcher.ConnectionInfo>();

        ServiceDispatcher(ServiceConnection conn,
                Context context, Handler activityThread, int flags) {
            mIServiceConnection = new InnerConnection(this);
            mConnection = conn;
            mContext = context;
            mActivityThread = activityThread;
            mLocation = new ServiceConnectionLeaked(null);
            mLocation.fillInStackTrace();
            mFlags = flags;
        }

        void validate(Context context, Handler activityThread) {
            if (mContext != context) {
                throw new RuntimeException(
                    "ServiceConnection " + mConnection +
                    " registered with differing Context (was " +
                    mContext + " now " + context + ")");
            }
            if (mActivityThread != activityThread) {
                throw new RuntimeException(
                    "ServiceConnection " + mConnection +
                    " registered with differing handler (was " +
                    mActivityThread + " now " + activityThread + ")");
            }
        }

        void doForget() {
            synchronized(this) {
                Iterator<ServiceDispatcher.ConnectionInfo> it = mActiveConnections.values().iterator();
                while (it.hasNext()) {
                    ServiceDispatcher.ConnectionInfo ci = it.next();
                    ci.binder.unlinkToDeath(ci.deathMonitor, 0);
                }
                mActiveConnections.clear();
                mForgotten = true;
            }
        }

        ServiceConnectionLeaked getLocation() {
            return mLocation;
        }

        ServiceConnection getServiceConnection() {
            return mConnection;
        }

        IServiceConnection getIServiceConnection() {
            return mIServiceConnection;
        }

        int getFlags() {
            return mFlags;
        }

        void setUnbindLocation(RuntimeException ex) {
            mUnbindLocation = ex;
        }

        RuntimeException getUnbindLocation() {
            return mUnbindLocation;
        }

        public void connected(ComponentName name, IBinder service) {
            if (mActivityThread != null) {
                mActivityThread.post(new RunConnection(name, service, 0));
            } else {
                doConnected(name, service);
            }
        }

        public void death(ComponentName name, IBinder service) {
            ServiceDispatcher.ConnectionInfo old;

            synchronized (this) {
                mDied = true;
                old = mActiveConnections.remove(name);
                if (old == null || old.binder != service) {
                    // Death for someone different than who we last
                    // reported...  just ignore it.
                    return;
                }
                old.binder.unlinkToDeath(old.deathMonitor, 0);
            }

            if (mActivityThread != null) {
                mActivityThread.post(new RunConnection(name, service, 1));
            } else {
                doDeath(name, service);
            }
        }

        public void doConnected(ComponentName name, IBinder service) {
            ServiceDispatcher.ConnectionInfo old;
            ServiceDispatcher.ConnectionInfo info;

            synchronized (this) {
                if (mForgotten) {
                    // We unbound before receiving the connection; ignore
                    // any connection received.
                    return;
                }
                old = mActiveConnections.get(name);
                if (old != null && old.binder == service) {
                    // Huh, already have this one.  Oh well!
                    return;
                }

                if (service != null) {
                    // A new service is being connected... set it all up.
                    mDied = false;
                    info = new ConnectionInfo();
                    info.binder = service;
                    info.deathMonitor = new DeathMonitor(name, service);
                    try {
                        service.linkToDeath(info.deathMonitor, 0);
                        mActiveConnections.put(name, info);
                    } catch (RemoteException e) {
                        // This service was dead before we got it...  just
                        // don't do anything with it.
                        mActiveConnections.remove(name);
                        return;
                    }

                } else {
                    // The named service is being disconnected... clean up.
                    mActiveConnections.remove(name);
                }

                if (old != null) {
                    old.binder.unlinkToDeath(old.deathMonitor, 0);
                }
            }

            // If there was an old service, it is not disconnected.
            if (old != null) {
                mConnection.onServiceDisconnected(name);
            }
            // If there is a new service, it is now connected.
            if (service != null) {
                mConnection.onServiceConnected(name, service);
            }
        }

        public void doDeath(ComponentName name, IBinder service) {
            mConnection.onServiceDisconnected(name);
        }

        private final class RunConnection implements Runnable {
            RunConnection(ComponentName name, IBinder service, int command) {
                mName = name;
                mService = service;
                mCommand = command;
            }

            public void run() {
                if (mCommand == 0) {
                    doConnected(mName, mService);
                } else if (mCommand == 1) {
                    doDeath(mName, mService);
                }
            }

            final ComponentName mName;
            final IBinder mService;
            final int mCommand;
        }

        private final class DeathMonitor implements IBinder.DeathRecipient
        {
            DeathMonitor(ComponentName name, IBinder service) {
                mName = name;
                mService = service;
            }

            public void binderDied() {
                death(mName, mService);
            }

            final ComponentName mName;
            final IBinder mService;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <bean id="remoteRelayReceiver" class="de.paluch.midi.relay.relay.RemoteRelayReceiverWrapper">
        <property name="delegate" ref="${device}" />
    </bean>

    <bean id="ethrly16A" class="de.paluch.midi.relay.relay.ETHRLY16">
        <property name="hostname" value="${ethrlyHostnameA}" />
        <property name="port" value="${ethrlyPort}" />
    </bean>

    <bean id="ethrly16B" class="de.paluch.midi.relay.relay.ETHRLY16">
        <property name="hostname" value="${ethrlyHostnameB}" />
        <property name="port" value="${ethrlyPort}" />
    </bean>

    <bean name="switchOnJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
        <property name="jobClass" value="de.paluch.midi.relay.job.SwitchOnJob" />
        <property name="durability" value="true" />
        <property name="jobDataAsMap">
            <map>
                <entry key="remoteRelayReceiver" value-ref="remoteRelayReceiver" />
            </map>
        </property>
    </bean>

    <bean name="switchOffJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
        <property name="jobClass" value="de.paluch.midi.relay.job.SwitchOffJob" />
        <property name="durability" value="true" />
        <property name="jobDataAsMap">
            <map>
                <entry key="remoteRelayReceiver" value-ref="remoteRelayReceiver" />
            </map>
        </property>
    </bean>

    <bean name="playJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
        <property name="jobClass" value="de.paluch.midi.relay.job.PlayJob" />
        <property name="durability" value="true" />
        <property name="jobDataAsMap">
            <map>
                <entry key="midiPlayer" value-ref="midiPlayer" />
            </map>
        </property>
    </bean>

    <bean name="connectionWatchdog" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
        <property name="jobClass" value="de.paluch.midi.relay.job.ConnectionWatchdogJob" />
        <property name="durability" value="true" />
        <property name="jobDataAsMap">
            <map>
                <entry key="remoteRelayReceiver" value-ref="remoteRelayReceiver" />
            </map>
        </property>
    </bean>

    <bean id="switchOnEarlyTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="switchOnJob" />
        <property name="cronExpression" value="0 0 5 * * ?" />
    </bean>

    <bean id="switchOffEarlyTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="switchOffJob" />
        <property name="cronExpression" value="0 0 8 * * ?" />
    </bean>

    <bean id="switchOffLateTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="switchOffJob" />
        <property name="cronExpression" value="0 0 20 * * ?" />
    </bean>

    <bean id="playTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="playJob" />
        <property name="cronExpression" value="${timerCronExpression}" />
    </bean>

    <bean id="connectionWatchdogTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
        <property name="jobDetail" ref="connectionWatchdog" />
        <property name="startDelay" value="10000" />
        <property name="repeatInterval" value="360000" />
    </bean>

    <!-- *** Start Quartz engine *** -->
    <bean id="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="connectionWatchdogTrigger" />
                <!-- <ref bean="switchOnEarlyTrigger"/>
                <ref bean="switchOffEarlyTrigger"/>
                <ref bean="switchOffLateTrigger"/>
                <ref bean="playTrigger"/> -->
            </list>
        </property>

        <property name="jobDetails">
            <list>
                <ref bean="playJob" />
                <ref bean="switchOnJob" />
                <ref bean="switchOffJob" />
            </list>
        </property>
        <property name="quartzProperties">
            <props>
                <!-- ThreadPool -->
                <prop key="org.quartz.threadPool.class">org.quartz.simpl.SimpleThreadPool</prop>
                <prop key="org.quartz.threadPool.threadCount">4</prop>
            </props>
        </property>
    </bean>

</beans>

redpajama_set_name: RedPajamaGithub


text:
/**
 * @author André König <andre.koenig@posteo.de>
 *
 */

'use strict';

var termcolors = {
    gray : function gray (value) {
        return '\x1b[90m' + value + '\x1b[39m';
    },
    green : function green (value) {
        return '\x1b[32m' + value + '\x1b[39m';
    },
    red : function red (value) {
        return '\x1b[31m' + value + '\x1b[39m';
    }
};

/**
 * Prints, well, an error.
 *
 * @param  {object} err The error object.
 *
 */
exports.printError = function printError (err) {
    return console.error(termcolors.red(err));
};

/**
 * Print a pick.
 *
 * @param  {object} pick A #npmawesome pick.
 *
 */
exports.printPick = function printPick (pick) {
    return console.log('%s - %s: %s', termcolors.gray(pick.pubdate), termcolors.green(pick.title), termcolors.gray(pick.guid));
};


text:
class GrailsAT25 < Formula
  desc "Web application framework for the Groovy language"
  homepage "https://grails.org"
  url "https://github.com/grails/grails-core/releases/download/v2.5.6/grails-2.5.6.zip"
  sha256 "58c1283d7748449bc3cecf8c9fe883157f2a279fa75ff14aa6d6388461527187"

  bottle :unneeded

  depends_on :java

  def install
    rm_f Dir["bin/*.bat", "bin/cygrails", "*.bat"]
    prefix.install %w[LICENSE README]
    libexec.install Dir["*"]
    bin.mkpath
    Dir["#{libexec}/bin/*"].each do |f|
      next unless File.extname(f).empty?
      ln_s f, bin+File.basename(f)
    end
  end

  test do
    ENV["JAVA_HOME"] = `/usr/libexec/java_home`.chomp
    assert_match "Grails version: #{version}",
      shell_output("#{bin}/grails --version")
  end
end


text:
package com.beepscore.android.spotifystreamer;

import android.os.Parcel;
import android.os.Parcelable;

/**
 * Class TrackParcelable is similar to Track, but is Parcelable.
 * It has a subset of Track properties.
 * Can't have a property that is type Track??
 * https://developer.android.com/reference/android/os/Parcelable.html
 * Created by stevebaker on 7/11/15.
 */
public class TrackParcelable implements Parcelable {

    String artistName;
    String albumName;
    String name;
    String imageNarrowestUrl;
    String imageWidestUrl;
    String previewUrl;

    // constructor
    public TrackParcelable(String artistName,
                           String albumName, String name,
                           String imageNarrowestUrl,
                           String imageWidestUrl,
                           String previewUrl) {
        this.artistName = artistName;
        this.albumName = albumName;
        this.name = name;
        this.imageNarrowestUrl = imageNarrowestUrl;
        this.imageWidestUrl = imageWidestUrl;
        this.previewUrl = previewUrl;
    }

    // private constructor
    private TrackParcelable(Parcel in) {
        artistName = in.readString();
        albumName = in.readString();
        name = in.readString();
        imageNarrowestUrl = in.readString();
        imageWidestUrl = in.readString();
        previewUrl = in.readString();
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public String toString() {
        final String separator = " ";
        return artistName
                + separator + albumName
                + separator + name
                + separator + imageNarrowestUrl
                + separator + imageWidestUrl
                + separator + previewUrl;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        // second argument can be used as a list index when parceling a list object
        // must decode in same order used by encode
        parcel.writeString(artistName);
        parcel.writeString(albumName);
        parcel.writeString(name);
        parcel.writeString(imageNarrowestUrl);
        parcel.writeString(imageWidestUrl);
        parcel.writeString(previewUrl);
    }

    public static final Parcelable.Creator<TrackParcelable> CREATOR =
            new Parcelable.Creator<TrackParcelable>() {

                @Override
                public TrackParcelable createFromParcel(Parcel parcel) {
                    return new TrackParcelable(parcel);
                }

                @Override
                public TrackParcelable[] newArray(int i) {
                    return new TrackParcelable[i];
                }
            };

}


text:
module Moo.CommandInterface
    ( commands
    , commandOptionUsage
    , findCommand
    , getCommandArgs
    , usageString
    ) where

import Data.Maybe
import Moo.CommandHandlers
import Moo.Core
import System.Console.GetOpt

-- |The available commands; used to dispatch from the command line and
-- used to generate usage output.
-- |The available commands; used to dispatch from the command line and
-- used to generate usage output.
commands :: [Command]
commands = [ Command "new" [migrationName]
                           []
                           ["no-ask", configFile]
                           "Create a new empty migration"
                           newCommand

           , Command "apply" [migrationName]
                             []
                             [testOption, configFile]
                             "Apply the specified migration and its \
                             \dependencies"
                             applyCommand

           , Command "revert" [migrationName]
                              []
                              [testOption, configFile]
                              "Revert the specified migration and those \
                              \that depend on it"
                              revertCommand

           , Command "test" [migrationName]
                            []
                            [configFile]
                            "Test the specified migration by applying \
                            \and reverting it in a transaction, then \
                            \roll back"
                            testCommand

           , Command "upgrade" []
                               []
                               [testOption, configFile]
                               "Install all migrations that have not yet \
                               \been installed"

                               upgradeCommand

           , Command "upgrade-list" []
                                    []
                                    []
                                    "Show the list of migrations not yet \
                                    \installed"
                                    upgradeListCommand

           , Command "reinstall" [migrationName]
                                 []
                                 [testOption, configFile]
                                 "Reinstall a migration by reverting, then \
                                 \reapplying it"
                                 reinstallCommand

           , Command "list" []
                            []
                            [configFile]
                            "List migrations already installed in the backend"
                            listCommand
           ]
    where migrationName = "migrationName"
          testOption    = "test"
          configFile    = "config-file"

findCommand :: String -> Maybe Command
findCommand name = listToMaybe [ c | c <- commands, _cName c == name ]

commandOptions :: [ OptDescr (CommandOptions -> IO CommandOptions) ]
commandOptions =  [ optionConfigFile
                  , optionTest
                  , optionNoAsk
                  ]

optionConfigFile :: OptDescr (CommandOptions -> IO CommandOptions)
optionConfigFile = Option "c" ["config-file"]
                   (ReqArg (\arg opt ->
                             return opt { _configFilePath = Just arg }) "FILE")
                   "Specify location of configuration file"

optionTest :: OptDescr (CommandOptions -> IO CommandOptions)
optionTest = Option "t" ["test"]
             (NoArg (\opt -> return opt { _test = True }))
             "Perform the action then rollback when finished"

optionNoAsk :: OptDescr (CommandOptions -> IO CommandOptions)
optionNoAsk = Option "n" ["no-ask"]
              (NoArg (\opt -> return opt { _noAsk = True }))
              "Do not interactively ask any questions, just do it"

getCommandArgs :: [String] -> IO ( CommandOptions, [String] )
getCommandArgs args = do
  let (actions, required, _) =  getOpt RequireOrder commandOptions args
  opts <- foldl (>>=) defaultOptions actions
  return ( opts, required )

defaultOptions :: IO CommandOptions
defaultOptions = return $ CommandOptions Nothing False False

commandOptionUsage :: String
commandOptionUsage = usageInfo "Options:" commandOptions

usageString :: Command -> String
usageString command =
    unwords (_cName command:optionalArgs ++ options ++ requiredArgs)
    where
      requiredArgs = map (\s -> "<" ++ s ++ ">") $ _cRequired command
      optionalArgs = map (\s -> "[" ++ s ++ "]") $ _cOptional command
      options = map (\s -> "["++ "--" ++ s ++ "]")  optionStrings
      optionStrings = _cAllowedOptions command


text:
package org.camunda.bpm.model.cmmn.instance;

import java.util.Collection;

import org.camunda.bpm.model.cmmn.instance.CmmnModelElementInstanceTest;

/**
 * @author Roman Smirnov
 *
 */
public class PlanItemTransitionStandardEventTest extends CmmnModelElementInstanceTest {

  public TypeAssumption getTypeAssumption() {
    return new TypeAssumption(false);
  }

  @Override
  public Collection<ChildElementAssumption> getChildElementAssumptions() {
    return null;
  }

  @Override
  public Collection<AttributeAssumption> getAttributesAssumptions() {
    return null;
  }

}


text:
Outside contributions to this library are welcome.

# Contributing directly to the code

In order to make contributions, please follow these basic steps:

* Fork the public repository
* Create a separate branch on your fork.  Commit your changes to this fork
* Create a pull request against the upstream ```master``` branch

Once your changes have been reviewed and all is well, the request will be merged in.

### Some things to keep in mind

* PHRETS follows the PSR-1/PSR-2 coding style
* Please include automated tests which prove the functionality you're including or fixing
* Please include a description of your change and what value it provides

# Contributing to documentation

The documentation for PHRETS lives within the ```docs/``` directory in the [main repository](http://github.com/troydavisson/PHRETS).  Using the same flow as code changes, please contribute any fixes, corrections or additions to the documentation you feel are necessary.

Once the documentation pull request has been merged in, the published documentation will automatically update.


text:
package iptables

type Interface interface {
	Append(table, chain string, rulespec ...string) error
	Delete(table, chain string, rulespec ...string) error
	Insert(table, chain string, pos int, rulespec ...string) error
}


text:
package com.af.experiments.FxCameraApp.ogles;

public interface Texture {
    int getTexName();
    int getWidth();
    int getHeight();
    void setup();
    void release();
}


text:
package manifold.collections.api.range;

public abstract class NumberRange<E extends Number & Comparable<E>, ME extends NumberRange<E, ME>> extends AbstractIterableRange<E, E, Void, ME>
{
  @SuppressWarnings({"UnusedDeclaration"})
  public NumberRange( E left, E right, E step )
  {
    this( left, right, step, true, true, false );
  }

  public NumberRange( E left, E right, E step, boolean leftClosed, boolean rightClosed, boolean reverse )
  {
    super( left, right, step, null, leftClosed, rightClosed, reverse );
  }
}


text:
package direct.interceptor.handler.manager;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import direct.interceptor.handler.InterceptHandler;
import direct.interceptor.handler.InterceptManager;

public class SuperInterceptManager implements InterceptManager {

	private List<InterceptManager> managers = new ArrayList<>();

	public void addManager(InterceptManager manager) {
		if (manager == null) {
			return;
		}
		this.managers.add(manager);
	}

	@Override
	public InterceptHandler getHandler(
			Annotation annotation,
			Class<?> annotationClass,
			Class<?> originClasss,
			Method originMethod) {
		for (InterceptManager manager : managers) {
			InterceptHandler handler = manager.getHandler(annotation, annotationClass, originClasss, originMethod);
			if (handler != null) {
				return handler;
			}
		}
		return null;
	}

}


text:
tags: clown house
layout: post
title: "Creepy clown says adios"
---

We moved into our house a little over two years ago. The woman who
lived there before us was older, I'd guess in her upper 60s, and
seemed a little bitter and crabby, someone who spent a lot of her time
smoking and watching the local news on a tiny TV in the kitchen.

The second time we met her Barb commented on the clowns that were
all over the house: paintings, small statues even in the bathroom. The
lady said, "You know, I used to be a clown." Barb and I gave each
other the barely raised eyebrow that married couples develop that
says, "Did I hear what I just think I heard? Honey, follow up on
that..."

So I said, trying to sound like I didn't quite hear her, "I'm
sorry, did you say you were a clown?" She confirmed, said that it was
a long time ago but in that tone of voice that said she might want to
talk about it. But since the house was being inspected and we had more
important things to do, we let it drop.

When we opened up our empty house for the first time we
half-expected to find clowns. Thankfully, we were disappointed. We
merrily went about ripping up carpet and wallpaper for a couple of
months and the clowns left our minds.

But a couple months after we moved in we found the clown from the
photo, leering at us from the attic. We didn't find it immediately
because it was back a little from the door, and because the attic
doesn't have a light you wouldn't immediately see it unless you were
looking. So the first time I saw his evil face clown it gave me a
nasty start. Not quite Stephen King, but still creepy.

Being lazy bastards we left it up there -- we didn't have much need
for the attic beyond a few boxes. But with baby stuff taking over the
spare bedroom we needed to use it more. So, I finally took the clown
down to the curb this morning, finally rid of the last clown in the
house. It had better be the last we see of it.


text:
IdAllocator::IdAllocator(const size_t start, const size_t end)
    : _start(start), _end(end),
      _allocated(end - start)
{

}

unsigned int IdAllocator::allocate(void)
{
    LockGuard guard(_mutex);

    const size_t size = _allocated.size();
    for (size_t i = 0; i < size; i++) {
        if (_allocated[i]) {
            continue;
        }

        _allocated[i] = true;
        return (_start + i);
    }

    return -1;
}

void IdAllocator::deallocate(const unsigned int id)
{
    LockGuard guard(_mutex);

    if (!this->isAllocated(id)) {
        return;;
    }

    _allocated[id - _start] = false;
}

bool IdAllocator::isAllocated(const unsigned int id) {
    LockGuard guard(_mutex);

    return ((size_t)id >= _start && (size_t)id <= _end) && _allocated[id - _start];
}


text:
layout: page
title: Silicon Archive Holdings Party
date: 2016-05-24
author: Cheryl Clay
tags: weekly links, java
status: published
summary: Praesent euismod diam sed ex convallis efficitur. Nulla.
banner: images/banner/office-01.jpg
booking:
  startDate: 03/30/2017
  endDate: 04/04/2017
  ctyhocn: AUSOHHX
  groupCode: SAHP
published: true
---
Ut ultrices neque eget ornare dictum. Mauris volutpat egestas enim, vitae facilisis mi convallis semper. Nulla ut tellus pulvinar, convallis diam id, iaculis ex. Pellentesque blandit non diam sed suscipit. In hac habitasse platea dictumst. Phasellus vitae nisi vulputate, rutrum mi consequat, hendrerit risus. Mauris a nunc eu ipsum vehicula facilisis. Duis molestie cursus dolor, ac fringilla nibh tempus vitae. Aenean blandit eget velit sit amet elementum. In finibus tortor vel lacus tristique vulputate. Donec feugiat eget dolor a dignissim. Suspendisse nec nisl aliquet lacus ultricies sagittis vel id ante. Donec mi justo, luctus cursus suscipit ut, tempor quis sem. Etiam id nisl placerat, scelerisque ex eu, iaculis nunc. Nunc ex felis, rhoncus eget nisl eu, convallis malesuada ante. Vestibulum interdum gravida congue.

1 Fusce ultrices purus in lorem euismod, et dapibus nisl sagittis
1 Donec ac velit a nunc pharetra bibendum
1 Nulla id tellus sit amet velit imperdiet rutrum
1 Sed sodales nunc volutpat urna maximus, at luctus enim porta
1 Fusce ac tellus in augue dictum vestibulum
1 Vestibulum pharetra nisl non risus malesuada sodales.

Aliquam nibh quam, laoreet eu imperdiet a, euismod eget quam. Aliquam eget mattis nisl. Nullam ac suscipit libero. Sed interdum, enim non pulvinar semper, nisi arcu sagittis leo, sit amet scelerisque nisl diam id orci. Maecenas ac dignissim risus. Curabitur dictum tellus consequat cursus tempus. Vivamus accumsan, odio ut consequat gravida, massa nunc rutrum massa, et viverra mi ipsum in tortor. Nullam scelerisque, ante eu ullamcorper lacinia, tortor mauris blandit diam, sit amet placerat libero urna non neque.


text:
import _ from 'underscore';

/*
* Callback hooks provide an easy way to add extra steps to common operations.
* @namespace RocketChat.promises
*/

RocketChat.promises = {};

/*
* Callback priorities
*/

RocketChat.promises.priority = {
	HIGH: -1000,
	MEDIUM: 0,
	LOW: 1000
};

/*
* Add a callback function to a hook
* @param {String} hook - The name of the hook
* @param {Function} callback - The callback function
*/

RocketChat.promises.add = function(hook, callback, p = RocketChat.promises.priority.MEDIUM, id) {
	const priority = !_.isNumber(p) ? RocketChat.promises.priority.MEDIUM : p;
	callback.priority = priority;
	callback.id = id || Random.id();
	RocketChat.promises[hook] = RocketChat.promises[hook] || [];
	if (RocketChat.promises[hook].find(cb => cb.id === callback.id)) {
		return;
	}
	RocketChat.promises[hook].push(callback);
};

/*
* Remove a callback from a hook
* @param {string} hook - The name of the hook
* @param {string} id - The callback's id
*/

RocketChat.promises.remove = function(hookName, id) {
	RocketChat.promises[hookName] = _.reject(RocketChat.promises[hookName], (callback) => callback.id === id);
};

/*
* Successively run all of a hook's callbacks on an item
* @param {String} hook - The name of the hook
* @param {Object} item - The post, comment, modifier, etc. on which to run the callbacks
* @param {Object} [constant] - An optional constant that will be passed along to each callback
* @returns {Object} Returns the item after it's been through all the callbacks for this hook
*/

RocketChat.promises.run = function(hook, item, constant) {
	let callbacks = RocketChat.promises[hook];
	if (callbacks == null || callbacks.length === 0) {
		return Promise.resolve(item);
	}
	callbacks = _.sortBy(callbacks, (callback) => callback.priority || RocketChat.promises.priority.MEDIUM);
	return callbacks.reduce(function(previousPromise, callback) {
		return new Promise(function(resolve, reject) {
			return previousPromise.then((result) => callback(result, constant).then(resolve, reject));
		});
	}, Promise.resolve(item));
};

/*
* Successively run all of a hook's callbacks on an item, in async mode (only works on server)
* @param {String} hook - The name of the hook
* @param {Object} item - The post, comment, modifier, etc. on which to run the callbacks
* @param {Object} [constant] - An optional constant that will be passed along to each callback
*/

RocketChat.promises.runAsync = function(hook, item, constant) {
	const callbacks = RocketChat.promises[hook];
	if (!Meteor.isServer || callbacks == null || callbacks.length === 0) {
		return item;
	}
	Meteor.defer(() => {
		_.sortBy(callbacks, (callback) => callback.priority || RocketChat.promises.priority.MEDIUM).forEach(function(callback) {
			callback(item, constant);
		});
	});
};


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

import com.sun.javafx.scene.control.skin.VirtualFlow;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.DataSource;
import model.User;

/**
 *
 * @author MLBaiche
 */
public class UserDao {

    private DataSource dataSource;

    private final String SELECT_ALL_USER="SELECT * FROM T_USER";
    private final String INSERT_USER="INSERT INTO T_USER(NOM,PRENOM,MAIL,PASSWORD,TELEPHONE,PROFIL,BONUS) VALUES(?,?,?,?,?,?,?)";
    private final String ADD_RESTAURANT_TO_USER="INSERT INTO T_USER_RESTAURANT(MAIL,ID_RESTAURANT) VALUES(?,?)";
    private final String SELECT_USER_BY_EMAIL="SELECT * FROM T_USER WHERE MAIL=?";
    private final String SELECT_CONNECTED_USER="SELECT * FROM T_USER WHERE MAIL=? AND PASSWORD=?";
    private final String UPDATE_USER="UPDATE T_USER SET NOM=?, PRENOM=? , PASSWORD=? , TELEPHONE=?, PROFIL=?   WHERE MAIL=?";
    private final String ADD_RESERVATION="INSERT INTO T_USER_RESERVATION (MAIL,ID_RES) VALUES (?,?)";

    public void setDataSource(DataSource dataSource){
        this.dataSource=dataSource;
    }

    public List<User> loadAll(){
        List<User> liste= new ArrayList<User>();
        Connection con = null;

        try {
            con = dataSource.getConnection();
            PreparedStatement ps = con.prepareStatement(SELECT_ALL_USER);
            ResultSet rs = ps.executeQuery();

            while(rs.next()){
                User user = new User();
                user.setNom(rs.getString("NOM"));
                user.setPrenom(rs.getString("PRENOM"));
                user.setEmail(rs.getString("MAIL"));
                user.setPassword(rs.getString("PASSWORD"));
                user.setTelephone(rs.getString("TELEPHONE"));
                if(rs.getInt("PROFIL")==1){
                    user.setProfil(true);
                }else
                    user.setProfil(false);

                user.setBonus(rs.getInt("BONUS"));
                //  rajouter les autres....
                System.out.println("nom : "+user.getNom());
                liste.add(user);
            }

            rs.close();
            ps.close();

        } catch (SQLException ex) {
            Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (con != null) {
            try {
		con.close();
		} catch (SQLException e) {}
            }

        }
        return liste;
    }

        public int addUser(User user){
            Connection con = null;
            int rs=0;

        try {
            con = dataSource.getConnection();
            PreparedStatement ps = con.prepareStatement(INSERT_USER);
            int i=1;
            ps.setString(i++, user.getNom());
            ps.setString(i++, user.getPrenom());
            ps.setString(i++, user.getEmail());
            ps.setString(i++, user.getPassword());
            ps.setString(i++, user.getTelephone());
            if(user.getProfil()){
                ps.setInt(i++,1);
            }else
                ps.setInt(i++,0);

            ps.setInt(i, user.getBonus());
            System.out.println("USER : "+user.toString());
            rs = ps.executeUpdate();
            System.out.println("Resultat insertion : "+rs);

        } catch (SQLException ex) {
            Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (con != null) {
            try {
		con.close();
		} catch (SQLException e) {}
            }

        }
        return rs;
        }

    public boolean existsUser(String email) {
        Connection con = null;
        boolean result=false;

        try {
            // ouvrir la connexion
            con = dataSource.getConnection();
            // preparer la requete
            PreparedStatement ps = con.prepareStatement(SELECT_USER_BY_EMAIL);
            // remplacer les parametres de la requete
            ps.setString(1, email);
            // executer la requete
            ResultSet rs = ps.executeQuery();

            // recuperer le resultat
            result=rs.next();
            System.out.println("USER EXISTS : "+result);

            rs.close();
            ps.close();

        } catch (SQLException ex) {
            Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (con != null) {
            try {
		con.close();
		} catch (SQLException e) {}
            }

        }
        return result;
    }

    public boolean isConnected(User u){
     Connection con = null;
        boolean result=false;

        try {
            // ouvrir la connexion
            con = dataSource.getConnection();
            // preparer la requete
            PreparedStatement ps = con.prepareStatement(SELECT_CONNECTED_USER);
            // remplacer les parametres de la requete
            ps.setString(1, u.getEmail());
            ps.setString(2, u.getPassword());
            // executer la requete
            ResultSet rs = ps.executeQuery();

            // recuperer le resultat
            result=rs.next();
            System.out.println("USER EXISTS : "+result);

            rs.close();
            ps.close();

        } catch (SQLException ex) {
            Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (con != null) {
            try {
		con.close();
		} catch (SQLException e) {}
            }

        }
        return result;
    }

    public void addRestaurant(String user, int id_rest) {
        Connection con = null;
        int rs=0;

        try {
            // ouvrir la connexion
            con = dataSource.getConnection();
            // preparer la requete
            PreparedStatement ps = con.prepareStatement(ADD_RESTAURANT_TO_USER);
            // remplacer les parametres de la requete
            ps.setString(1, user);
            ps.setInt(2, id_rest);
            // executer la requete
             rs = ps.executeUpdate();

            ps.close();

        } catch (SQLException ex) {
            Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (con != null) {
            try {
		con.close();
		} catch (SQLException e) {}
            }

        }

    }

    public User getByMail(String email) {
        Connection con = null;
        User user=null;
        try {
            // ouvrir la connexion
            con = dataSource.getConnection();
            // preparer la requete
            PreparedStatement ps = con.prepareStatement(SELECT_USER_BY_EMAIL);
            // remplacer les parametres de la requete
            ps.setString(1, email);
            // executer la requete
            ResultSet rs = ps.executeQuery();

            // recuperer le resultat

             if(rs.next()){
                 user = new User();
                user.setNom(rs.getString("NOM"));
                user.setPrenom(rs.getString("PRENOM"));
                user.setEmail(rs.getString("MAIL"));
                user.setPassword(rs.getString("PASSWORD"));
                user.setTelephone(rs.getString("TELEPHONE"));
                if(rs.getInt("PROFIL")==1){
                    user.setProfil(true);
                }else
                    user.setProfil(false);

                user.setBonus(rs.getInt("BONUS"));
                //  rajouter les autres....
                System.out.println("nom : "+user.getNom());

            }

            rs.close();
            ps.close();

        } catch (SQLException ex) {
            Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (con != null) {
            try {
		con.close();
		} catch (SQLException e) {}
            }

        }
        return user;
    }

    public int updateUser(User user) {
        Connection con = null;
            int rs=0;

        try {
            con = dataSource.getConnection();
            PreparedStatement ps = con.prepareStatement(UPDATE_USER);
            int i=1;
            ps.setString(i++, user.getNom());
            ps.setString(i++, user.getPrenom());

            ps.setString(i++, user.getPassword());
            ps.setString(i++, user.getTelephone());
            if(user.getProfil()){
                ps.setInt(i++,1);
            }else
                ps.setInt(i++,0);

            ps.setString(i++, user.getEmail());

            rs = ps.executeUpdate();

        } catch (SQLException ex) {
            Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (con != null) {
            try {
		con.close();
		} catch (SQLException e) {}
            }

        }
        return rs;
    }

    public void addReservation(String user, int idRes) {
         Connection con = null;
            int rs=0;

        try {
            con = dataSource.getConnection();
            PreparedStatement ps = con.prepareStatement(ADD_RESERVATION);
            int i=1;
            ps.setString(i++, user);
           ps.setInt(i++, idRes);

            rs = ps.executeUpdate();

        } catch (SQLException ex) {
            Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (con != null) {
            try {
		con.close();
		} catch (SQLException e) {}
            }

        }

    }
}


text:
<?php

/**
 * This file is part of the Spryker Demoshop.
 * For full license information, please view the LICENSE file that was distributed with this source code.
 */

namespace Pyz\Yves\ProductSet;

use Pyz\Yves\Product\Plugin\StorageProductMapperPlugin;
use Spryker\Yves\Kernel\AbstractBundleDependencyProvider;
use Spryker\Yves\Kernel\Container;

class ProductSetDependencyProvider extends AbstractBundleDependencyProvider
{
    public const CLIENT_CART = 'CLIENT_CART';
    public const CLIENT_PRODUCT = 'CLIENT_PRODUCT';
    public const CLIENT_PRODUCT_SET = 'CLIENT_PRODUCT_SET';

    public const PLUGIN_STORAGE_PRODUCT_MAPPER = 'PLUGIN_STORAGE_PRODUCT_MAPPER';

    /**
     * @param \Spryker\Yves\Kernel\Container $container
     *
     * @return \Spryker\Yves\Kernel\Container
     */
    public function provideDependencies(Container $container)
    {
        $this->provideCartClient($container);
        $this->provideProductClient($container);
        $this->provideProductSetClient($container);

        $this->provideStorageProductMapperPlugin($container);

        return $container;
    }

    /**
     * @param \Spryker\Yves\Kernel\Container $container
     *
     * @return void
     */
    protected function provideCartClient(Container $container)
    {
        $container[self::CLIENT_CART] = function (Container $container) {
            return $container->getLocator()->cart()->client();
        };
    }

    /**
     * @param \Spryker\Yves\Kernel\Container $container
     *
     * @return void
     */
    protected function provideProductClient(Container $container)
    {
        $container[self::CLIENT_PRODUCT] = function (Container $container) {
            return $container->getLocator()->product()->client();
        };
    }

    /**
     * @param \Spryker\Yves\Kernel\Container $container
     *
     * @return void
     */
    protected function provideProductSetClient(Container $container)
    {
        $container[self::CLIENT_PRODUCT_SET] = function (Container $container) {
            return $container->getLocator()->productSet()->client();
        };
    }

    /**
     * @param \Spryker\Yves\Kernel\Container $container
     *
     * @return void
     */
    protected function provideStorageProductMapperPlugin(Container $container)
    {
        $container[self::PLUGIN_STORAGE_PRODUCT_MAPPER] = function (Container $container) {
            return new StorageProductMapperPlugin();
        };
    }
}


text:
#ifndef rtkDenoisingBPDQImageFilter_h
#define rtkDenoisingBPDQImageFilter_h

#include "rtkForwardDifferenceGradientImageFilter.h"
#include "rtkBackwardDifferenceDivergenceImageFilter.h"

#include <itkCastImageFilter.h>
#include <itkSubtractImageFilter.h>
#include <itkMultiplyImageFilter.h>
#include <itkInPlaceImageFilter.h>

namespace rtk
{
/** \class DenoisingBPDQImageFilter
 * \brief Base class for Basis Pursuit DeQuantization denoising filters
 *
 * \author Cyril Mory
 *
 * \ingroup IntensityImageFilters
 */

template< typename TOutputImage, typename TGradientImage>
class DenoisingBPDQImageFilter :
        public itk::InPlaceImageFilter< TOutputImage, TOutputImage >
{
public:

  /** Standard class typedefs. */
  typedef DenoisingBPDQImageFilter                              Self;
  typedef itk::InPlaceImageFilter< TOutputImage, TOutputImage>  Superclass;
  typedef itk::SmartPointer<Self>                               Pointer;
  typedef itk::SmartPointer<const Self>                         ConstPointer;

  /** Method for creation through the object factory. */
  itkNewMacro(Self)

  /** Run-time type information (and related methods). */
  itkTypeMacro(DenoisingBPDQImageFilter, ImageToImageFilter)

  /** Sub filter type definitions */
  typedef ForwardDifferenceGradientImageFilter
            <TOutputImage,
             typename TOutputImage::ValueType,
             typename TOutputImage::ValueType,
             TGradientImage>                                                      GradientFilterType;
  typedef itk::MultiplyImageFilter<TOutputImage>                                  MultiplyFilterType;
  typedef itk::SubtractImageFilter<TOutputImage>                                  SubtractImageFilterType;
  typedef itk::SubtractImageFilter<TGradientImage>                                SubtractGradientFilterType;
  typedef itk::InPlaceImageFilter<TGradientImage>                                 ThresholdFilterType;
  typedef BackwardDifferenceDivergenceImageFilter<TGradientImage, TOutputImage>   DivergenceFilterType;

  itkGetMacro(NumberOfIterations, int)
  itkSetMacro(NumberOfIterations, int)

  itkSetMacro(Gamma, double)
  itkGetMacro(Gamma, double)

protected:
  DenoisingBPDQImageFilter();
  ~DenoisingBPDQImageFilter() ITK_OVERRIDE {}

  void GenerateData() ITK_OVERRIDE;

  void GenerateOutputInformation() ITK_OVERRIDE;

  virtual ThresholdFilterType* GetThresholdFilter(){return ITK_NULLPTR;}

  /** Sub filter pointers */
  typename GradientFilterType::Pointer                  m_GradientFilter;
  typename MultiplyFilterType::Pointer                  m_MultiplyFilter;
  typename SubtractImageFilterType::Pointer             m_SubtractFilter;
  typename SubtractGradientFilterType::Pointer          m_SubtractGradientFilter;
  typename DivergenceFilterType::Pointer                m_DivergenceFilter;

  double m_Gamma;
  double m_Beta;
  double m_MinSpacing;
  int    m_NumberOfIterations;
  bool   m_DimensionsProcessed[TOutputImage::ImageDimension];

private:
  DenoisingBPDQImageFilter(const Self&); //purposely not implemented
  void operator=(const Self&); //purposely not implemented

  virtual void SetPipelineForFirstIteration();
  virtual void SetPipelineAfterFirstIteration();
};

} // end namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#include "rtkDenoisingBPDQImageFilter.hxx"
#endif

#endif //__rtkDenoisingBPDQImageFilter__


text:
namespace OElite.Restme.BigBuyUtils
{
    public class BigBuyProductVariationAssociation
    {
        public long Id { get; set; }
        public long Product { get; set; }
        public string Sku { get; set; }
        public string Ean13 { get; set; }
        public decimal ExtraWeight { get; set; }
        public decimal WholesalePrice { get; set; }
        public decimal RetailPrice { get; set; }
    }

    public class BigBuyProductVariation
    {

    }
}


text:
#import "SNSSetSubscriptionAttributesRequest.h"

@implementation SNSSetSubscriptionAttributesRequest

@synthesize subscriptionArn;
@synthesize attributeName;
@synthesize attributeValue;

-(id)init
{
    if (self = [super init]) {
        subscriptionArn = nil;
        attributeName   = nil;
        attributeValue  = nil;
    }

    return self;
}

-(id)initWithSubscriptionArn:(NSString *)theSubscriptionArn andAttributeName:(NSString *)theAttributeName andAttributeValue:(NSString *)theAttributeValue
{
    if (self = [self init]) {
        self.subscriptionArn = theSubscriptionArn;
        self.attributeName   = theAttributeName;
        self.attributeValue  = theAttributeValue;
    }

    return self;
}

-(NSString *)description
{
    NSMutableString *buffer = [[NSMutableString alloc] initWithCapacity:256];

    [buffer appendString:@"{"];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"SubscriptionArn: %@,", subscriptionArn] autorelease]];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"AttributeName: %@,", attributeName] autorelease]];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"AttributeValue: %@,", attributeValue] autorelease]];
    [buffer appendString:[super description]];
    [buffer appendString:@"}"];

    return [buffer autorelease];
}

-(void)dealloc
{
    [subscriptionArn release];
    [attributeName release];
    [attributeValue release];

    [super dealloc];
}

@end


text:
import copy
import logging
import os

from pylib import android_commands
from pylib import cmd_helper
from pylib import ports
from pylib.utils import emulator
from pylib.utils import xvfb

import gtest_config
import test_sharder

def _FullyQualifiedTestSuites(exe, option_test_suite, build_type):
  """Get a list of absolute paths to test suite targets.

  Args:
    exe: if True, use the executable-based test runner.
    option_test_suite: the test_suite specified as an option.
    build_type: 'Release' or 'Debug'.

  Returns:
    A list of tuples containing the suite and absolute path.
    Ex. ('content_unittests',
          '/tmp/chrome/src/out/Debug/content_unittests_apk/'
          'content_unittests-debug.apk')
  """
  test_suite_dir = os.path.join(cmd_helper.OutDirectory.get(), build_type)
  if option_test_suite:
    all_test_suites = [option_test_suite]
  else:
    all_test_suites = gtest_config.STABLE_TEST_SUITES

  if exe:
    qualified_test_suites = [os.path.join(test_suite_dir, t)
                             for t in all_test_suites]
  else:
    # out/(Debug|Release)/$SUITE_apk/$SUITE-debug.apk
    qualified_test_suites = [os.path.join(test_suite_dir,
                                          t + '_apk',
                                          t + '-debug.apk')
                             for t in all_test_suites]
  for t, q in zip(all_test_suites, qualified_test_suites):
    if not os.path.exists(q):
      raise Exception('Test suite %s not found in %s.\n'
                      'Supported test suites:\n %s\n'
                      'Ensure it has been built.\n' %
                      (t, q, gtest_config.STABLE_TEST_SUITES))
  return zip(all_test_suites, qualified_test_suites)

def _RunATestSuite(options, suite_name):
  """Run a single test suite.

  Helper for Dispatch() to allow stop/restart of the emulator across
  test bundles.  If using the emulator, we start it on entry and stop
  it on exit.

  Args:
    options: options for running the tests.
    suite_name: name of the test suite being run.

  Returns:
    0 if successful, number of failing tests otherwise.
  """
  step_name = os.path.basename(options.test_suite).replace('-debug.apk', '')
  attached_devices = []
  buildbot_emulators = []

  if options.use_emulator:
    buildbot_emulators = emulator.LaunchEmulators(options.emulator_count,
                                                  wait_for_boot=True)
    attached_devices = [e.device for e in buildbot_emulators]
  elif options.test_device:
    attached_devices = [options.test_device]
  else:
    attached_devices = android_commands.GetAttachedDevices()

  if not attached_devices:
    logging.critical('A device must be attached and online.')
    return 1

  # Reset the test port allocation. It's important to do it before starting
  # to dispatch any tests.
  if not ports.ResetTestServerPortAllocation():
    raise Exception('Failed to reset test server port.')

  if options.gtest_filter:
    logging.warning('Sharding is not possible with these configurations.')
    attached_devices = [attached_devices[0]]

  sharder = test_sharder.TestSharder(
      attached_devices,
      options.test_suite,
      options.gtest_filter,
      options.test_arguments,
      options.timeout,
      options.cleanup_test_files,
      options.tool,
      options.build_type,
      options.webkit)

  test_results = sharder.RunShardedTests()
  test_results.LogFull(
      test_type='Unit test',
      test_package=suite_name,
      build_type=options.build_type,
      flakiness_server=options.flakiness_dashboard_server)
  test_results.PrintAnnotation()

  for buildbot_emulator in buildbot_emulators:
    buildbot_emulator.Shutdown()

  return len(test_results.GetAllBroken())

def _ListTestSuites():
  """Display a list of available test suites."""
  print 'Available test suites are:'
  for test_suite in gtest_config.STABLE_TEST_SUITES:
    print test_suite

def Dispatch(options):
  """Dispatches the tests, sharding if possible.

  If options.use_emulator is True, all tests will be run in new emulator
  instance.

  Args:
    options: options for running the tests.

  Returns:
    0 if successful, number of failing tests otherwise.
  """
  if options.test_suite == 'help':
    _ListTestSuites()
    return 0

  if options.use_xvfb:
    framebuffer = xvfb.Xvfb()
    framebuffer.Start()

  all_test_suites = _FullyQualifiedTestSuites(options.exe, options.test_suite,
                                             options.build_type)
  failures = 0
  for suite_name, suite_path in all_test_suites:
    # Give each test suite its own copy of options.
    test_options = copy.deepcopy(options)
    test_options.test_suite = suite_path
    failures += _RunATestSuite(test_options, suite_name)

  if options.use_xvfb:
    framebuffer.Stop()
  return failures


text:
package org.flywaydb.core.internal.sqlscript;

import org.flywaydb.core.internal.sqlscript.SqlStatement;
import org.flywaydb.core.internal.util.CloseableIterator;

public interface SqlStatementIterator extends CloseableIterator<SqlStatement> {
    @Override
    void close();
}