text:
package com.adamg.materialtemplate.cloud.module;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.adamg.materialtemplate.cloud.R;
import com.adamg.materialtemplate.cloud.network.converter.JacksonConverter;
import com.adamg.materialtemplate.cloud.network.error.CloudErrorHandler;
import com.squareup.okhttp.OkHttpClient;

import java.net.MalformedURLException;
import java.net.URL;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import retrofit.Endpoint;
import retrofit.Endpoints;
import retrofit.RestAdapter;
import retrofit.client.Client;
import retrofit.client.OkClient;

/**
 * Class that provides the Retrofit API client. It is here that it is configured and made to run
 * making the appropriate calls as need be.
 *
 * @author Adam Greenberg
 * @version 1 on 6/27/15
 *          All code under The MIT License (MIT) unless otherwise noted.
 */
@Module(
        includes = {
                ApiServiceModule.class
        },
        complete = false,
        library = true
)
public class RestApiModule {

    private static final String TAG = RestApiModule.class.getSimpleName();

    /**
     * Integer that defines the basic server
     */
    private static final int DEFAULT_SERVER = 0;

    /**
     * Injectable Client which will supply the {@link OkHttpClient}.
     *
     * @param client the {@link OkHttpClient} defined in
     *               {@link OkHttpModule} or a testable module.
     * @return an instance of the transportation layer used for REST calls.
     */
    @Provides
    Client provideClient(final OkHttpClient client) {
        return new OkClient(client);
    }

    /**
     * Module that provides the basic patterned {@link RestAdapter} for use in our REST
     * requests.
     * This module will weave together the basic pieces that allow us to make a signed call, handle
     * default
     * errors, and append the correct endpoint for each call.
     *
     * @param endpoint     URL endpoint of each call being made
     * @param client       the REST client
     * @param converter    the Jackson converter that manages the JSON conversion
     * @param errorHandler common error handler piece
     * @return a {@link RestAdapter} that has been stitched together via the pieces passed
     * in.
     */
    @Provides
    RestAdapter provideRestAdapter(final Endpoint endpoint, final Client client, final JacksonConverter converter,
                                   final CloudErrorHandler errorHandler) {
        return new RestAdapter.Builder()
                // Add OkHttp as the client
                .setClient(client)
                        // Set the Jackson converter
                .setConverter(converter)
                        // Set the endpoints for the call
                .setEndpoint(endpoint)
                        // Set the error handler
                .setErrorHandler(errorHandler)
                        // Set the Logger to show all pieces of the request and response bodies
                .setLogLevel(RestAdapter.LogLevel.FULL)
                        // Build the client
                .build();
    }

    /**
     * Provides the default implementation for the Jackson converter
     *
     * @return the Jackson converter for the JSON conversion
     */
    @Provides
    JacksonConverter provideJacksonConverter() {
        return new JacksonConverter();
    }

    /**
     * Provides the default implementation for the {@link retrofit.ErrorHandler} for handling the errors
     * that occur on the network
     *
     * @return a new implemented class that allows us to have a coomon error handler
     */
    @Provides
    @Singleton
    CloudErrorHandler provideCloudErrorHandler() {
        return new CloudErrorHandler();
    }

    /**
     * Module which provides the base URL for APIs
     *
     * @param ctx the client's Context
     * @return an Endpoint constructed for the base URL in use with Retrofit
     */
    @Provides
    Endpoint providesEndpoint(@CloudLibModule.ClientApplication Context ctx) {
        // Get the current server
        final int server = ctx.getResources().getInteger(R.integer.current_server);

        // Server protocol
        final String protocol = getProtocol(ctx, server);

        // Server host
        final String serverHost = getHost(ctx, server);

        // Server port
        final int serverPort = getPort(ctx, server);

        return getEndpoint(protocol, serverHost, serverPort);
    }

    /**
     * Obtains the protocol piece of the endpoint based on the current server selected
     */
    private String getProtocol(final Context ctx, final int server) {
        String protocol = null;

        // Switch on the Server type
        switch (server) {
            case DEFAULT_SERVER:
                protocol = ctx.getString(R.string.default_server_protocol).trim();
                break;

            default:
                throwIfNullOrEmpty(null, "default_server_protocol");
        }

        // Ensure valid
        throwIfNullOrEmpty(protocol, "default_server_protocol");

        return protocol;
    }

    /**
     * Obtains the host piece of the endpoint based on the current server selected
     */
    private String getHost(Context ctx, final int server) {
        String serverHost = null;

        // Switch on the Server type
        switch (server) {
            case DEFAULT_SERVER:
                serverHost = ctx.getString(R.string.default_server_host_develop).trim();
                break;

            default:
                throwIfNullOrEmpty(null, "default_server_host_develop");
        }

        // Ensure valid
        throwIfNullOrEmpty(serverHost, "default_server_host_develop");

        return serverHost;
    }

    /**
     * Obtains the port piece of the endpoint based on the current server selected
     */
    private int getPort(final Context ctx, final int server) {
        int serverPort = 0;

        // Switch on the Server type
        switch (server) {
            case DEFAULT_SERVER:
                serverPort = ctx.getResources().getInteger(R.integer.default_server_port);
                break;

            default:
                throw new IllegalStateException(
                        "You must define a integer resource for default_server_port that represents a valid port address.");
        }

        if (serverPort < 0) {
            throw new IllegalStateException(
                    "You must define a integer resource for default_server_port that represents a valid port address.");
        }

        return serverPort;
    }

    /**
     * Constructs a new {@link Endpoint} from the config.xml parameters
     *
     * @param protocol   the name of the protocol to use.
     * @param serverHost the name of the host.
     * @param serverPort the port number on the host.
     * @return new constructed {@link Endpoint}
     */
    private Endpoint getEndpoint(final String protocol, final String serverHost, final int serverPort) {
        // Build the endpoint using URL so we catch any malformed exceptions, etc
        try {
            final URL url = new URL(protocol, serverHost, serverPort, "");
            Log.v(TAG, "Base URl is: " + url.toString());
            return Endpoints.newFixedEndpoint(url.toString());
        } catch (final MalformedURLException e) {
            Log.e(TAG, Log.getStackTraceString(e));
        }

        throw new IllegalArgumentException("Could not construct the base endpoint.");
    }

    /**
     * Check to see if the resource we obtain at initialization are valid and
     * contain data
     *
     * @param reference the string from the XML config resource
     * @param name      the name of the resource
     */
    public static void throwIfNullOrEmpty(final String reference, final String name) {
        if (TextUtils.isEmpty(reference)) {
            throw new IllegalStateException("The user must define a value in the config.xml file for: " + name);
        }
    }
}


text:
package com.eldhelm.samsung.iap;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;

import com.adobe.fre.FREContext;
import com.adobe.fre.FREFunction;
import com.adobe.fre.FREObject;
import com.eldhelm.samsung.iap.function.GetItemListFunction;
import com.eldhelm.samsung.iap.function.GetItemsInboxFunction;
import com.eldhelm.samsung.iap.function.GetPurchaseResultFunction;
import com.eldhelm.samsung.iap.function.InitFunction;
import com.eldhelm.samsung.iap.function.InitializeExtensionFunction;
import com.eldhelm.samsung.iap.function.PurchaseFunction;
import com.sec.android.iap.IAPConnector;

public class InAppExtensionContext extends FREContext {

	public static int mMode = 1;
	static final int IAP_SIGNATURE_HASHCODE = 0x7a7eaf4b;
	static final int FLAG_INCLUDE_STOPPED_PACKAGES = 32;

	public IAPConnector mIAPConnector;
	public ServiceConnection mServiceConn;

	public String purchaseData;
	public String itemId;
	public int statusCode;
	public String errorString;

	@Override
	public void dispose() {
		unbind();
	}

	@Override
	public Map<String, FREFunction> getFunctions() {
		Map<String, FREFunction> functions = new HashMap<String, FREFunction>();
		functions.put("initializeExtension", new InitializeExtensionFunction());
		functions.put("init", new InitFunction());
		functions.put("getItemList", new GetItemListFunction());
		functions.put("getItemsInbox", new GetItemsInboxFunction());
		functions.put("purchase", new PurchaseFunction());
		functions.put("getPurchaseResult", new GetPurchaseResultFunction());
		return functions;
	}

	public boolean isInstalledIapPackage() {
		PackageManager pm = getActivity().getPackageManager();
		try {
			pm.getApplicationInfo("com.sec.android.iap",
					PackageManager.GET_META_DATA);
			return true;
		} catch (NameNotFoundException e) {
			sendException(e);
			return false;
		}
	}

	public void iapPackageInstalled() {
		if (false == isValidIAPPackage()) {
			new AlertDialog.Builder(getActivity())
					.setTitle(R.string.in_app_purchase)
					.setMessage(R.string.invalid_iap_package)
					.setPositiveButton(android.R.string.ok,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
									getActivity().finish();
								}
							}).show();
		} else {
			sendWarning("Loging in");

			try {
				Intent startActivityIntent = new Intent(getActivity()
						.getApplicationContext(), InAppAccountActivity.class);
				getActivity().startActivity(startActivityIntent);
			} catch (Exception e) {
				sendException(e);
			}
		}
	}

	public boolean isValidIAPPackage() {
		boolean result = true;
		try {
			Signature[] signs = getActivity().getPackageManager()
					.getPackageInfo("com.sec.android.iap",
							PackageManager.GET_SIGNATURES).signatures;
			if (signs[0].hashCode() != IAP_SIGNATURE_HASHCODE) {
				result = false;
			}
		} catch (Exception e) {
			sendException(e);
			result = false;
		}
		return result;
	}

	public void iapPackageNotInstalled() {
		sendWarning("The com.sec.android.iap is not installed");

		try {
			Intent intent = new Intent();
			intent.setData(Uri
					.parse("samsungapps://ProductDetail/com.sec.android.iap"));
			if (Build.VERSION.SDK_INT >= 12) {
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
						| Intent.FLAG_ACTIVITY_CLEAR_TOP
						| FLAG_INCLUDE_STOPPED_PACKAGES);
			} else {
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
						| Intent.FLAG_ACTIVITY_CLEAR_TOP);
			}
			getActivity().startActivity(intent);
		} catch (Exception e) {
			sendException(e);
		}
	}

	public void bind() {
		if (mServiceConn != null)
			return;

		sendWarning("binding");
		mServiceConn = new ServiceConnection() {
			@Override
			public void onServiceDisconnected(ComponentName name) {
				mIAPConnector = null;
			}

			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				try {
					mIAPConnector = IAPConnector.Stub.asInterface(service);
					onBind();
				} catch (Exception e) {
					sendException(e);
				}
			}
		};

		try {
			Intent serviceIntent = new Intent(
					"com.sec.android.iap.service.iapService");
			getActivity().bindService(serviceIntent, mServiceConn,
					Context.BIND_AUTO_CREATE);
		} catch (Exception e) {
			sendException(e);
		}
	}

	public void unbind() {
		if (mServiceConn == null)
			return;

		getActivity().unbindService(mServiceConn);
		mServiceConn = null;
	}

	public void updatePakcage(Bundle bundle) {
		String errorString = bundle.getString("ERROR_STRING");
		final String extraString = bundle.getString("IAP_UPGRADE_URL");

		new AlertDialog.Builder(getActivity())
				.setTitle("IAP Upgrade")
				.setMessage(errorString)
				.setPositiveButton(android.R.string.ok,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								Intent intent = new Intent();
								intent.setData(Uri.parse(extraString));
								intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								try {
									getActivity().startActivity(intent);
								} catch (ActivityNotFoundException e) {
									e.printStackTrace();
								}
							}
						}).show();
	}

	public void accountCertificationSuccessfull() {
		bind();
	}

	public void onBind() {
		dispatchStatusEventAsync("Login successfull", "ready");
	}

	public void initSuccessfull() {
		dispatchStatusEventAsync("Init successfull", "init");
	}

	public void paymentFailed() {
		dispatchStatusEventAsync("payment_failed", "result");
	}

	public void paymentCanceled() {
		dispatchStatusEventAsync("payment_canceled", "result");
	}

	public void paymentCompleted(String itemId, String purchaseData,
			int statusCode, String errorString) {

		this.itemId = itemId;
		this.purchaseData = purchaseData;
		this.statusCode = statusCode;
		this.errorString = errorString;

		dispatchStatusEventAsync("payment_completed", "result");
	}

	public void sendException(Exception e) {
		sendException(e, "");
	}

	public void sendException(Exception e, String id) {
		StringWriter sw = new StringWriter();
		e.printStackTrace(new PrintWriter(sw));
		String err = sw.toString();
		try {
			setActionScriptData(FREObject.newObject(err));
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		dispatchStatusEventAsync("Extension exception: " + id, "exception");
	}

	public void sendWarning(String msg) {
		dispatchStatusEventAsync(msg, "warning");
	}

	public void sendError(String msg) {
		dispatchStatusEventAsync(msg, "error");
	}

}

redpajama_set_name: RedPajamaGithub


text:
  Molti aspetti di una compilazione sono sensibili al tempo, per cui se l'orologio della macchina
  su cui è eseguito Jenkins e quello dello slave differiscono in modo significativo possono
  verificarsi problemi oscuri. Si prenda in considerazione l'ipotesi di sincronizzare gli
  orologi delle macchine con NTP.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.maltparser.core.feature.spec.reader (MaltParser 1.8)</title>
<meta name="date" content="2014-05-05">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

org.maltparser.core.feature.spec.reader

Interfaces

FeatureSpecReader

Classes

ParReader

XmlReader

Enums

ParReader.ColumnNames

ParReader.DataStructures


text:
package com.smartdevicelink.proxy.rpc;

import androidx.annotation.NonNull;

import com.smartdevicelink.protocol.enums.FunctionID;
import com.smartdevicelink.proxy.RPCResponse;
import com.smartdevicelink.proxy.rpc.enums.Result;

import java.util.Hashtable;

/**
 * Create Interaction ChoiceSet Response is sent, when CreateInteractionChoiceSet
 * has been called
 *
 * @since SmartDeviceLink 1.0
 */
public class CreateInteractionChoiceSetResponse extends RPCResponse {
    /**
     * Constructs a new CreateInteractionChoiceSetResponse object
     */

    public CreateInteractionChoiceSetResponse() {
        super(FunctionID.CREATE_INTERACTION_CHOICE_SET.toString());
    }

    public CreateInteractionChoiceSetResponse(Hashtable<String, Object> hash) {
        super(hash);
    }

    /**
     * Constructs a new CreateInteractionChoiceSetResponse object
     *
     * @param success    whether the request is successfully processed
     * @param resultCode whether the request is successfully processed
     */
    public CreateInteractionChoiceSetResponse(@NonNull Boolean success, @NonNull Result resultCode) {
        this();
        setSuccess(success);
        setResultCode(resultCode);
    }
}


text:
package com.mapsindoors.stdapp.helpers;

import android.content.Context;
import android.content.SharedPreferences;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.HashSet;
import java.util.Set;

public class SharedPrefsHelper {
    /**
     * An initial value is given
     */
    private static final String SETTINGS_PREFS_BASE_FILE_NAME = "stdappPrefs";

    private static final String SETTINGS_PREFS_KEY_VENUES_FIRST_SHOWN = "VenuesFirstShown";
    private static final String SETTINGS_PREFS_KEY_APP_VERSION = "AppVersion";
    private static final String SETTINGS_PREFS_KEY_CURRENT_VENUE_ID = "CurrentVenueID";
    private static final String SETTINGS_PREFS_KEY_AVOID_STAIRS = "OptAvoidStairs";
    private static final String SETTINGS_PREFS_KEY_USER_CHOSEN_VENUE = "ChosenVenue";
    private static final String SETTINGS_PREFS_KEY_USER_CHOSEN_TRAVEL_MODE = "TravelMode";
    private static final String SETTINGS_PREFS_KEY_SHOW_ZOOM_BUTTON = "zoomForDetailsButtonVisibility";
    private static final String SETTINGS_PREFS_KEY_SOLUTION_ALIAS_KEY = "solutionAlias";
    private static final String SETTINGS_PREFS_KEY_SELECTED_USER_ROLES = "SelUserRoles";
    private static final String SETTINGS_PREFS_KEY_API_KEY_VALIDITY = "apiKeyValidity";

    private static String settingsPrefsBaseFileName;

    /**
     * Sets the Shared prefs filename's prefix by using the given MapsIndoors API Key value
     *
     * @param context           The app's main activity context
     * @param mapsIndoorsAPIKey The current solution's MapsIndoors API Key
     * @since 3.5.0
     */
    public static void setMapsIndoorsAPIKey(@NonNull String mapsIndoorsAPIKey) {
        settingsPrefsBaseFileName = SETTINGS_PREFS_BASE_FILE_NAME + "." + mapsIndoorsAPIKey;
    }

    public static boolean hasUserChosenAVenue(@NonNull Context context) {
        final SharedPreferences sp = context.getSharedPreferences(settingsPrefsBaseFileName, Context.MODE_PRIVATE);
        return sp.getBoolean(SharedPrefsHelper.SETTINGS_PREFS_KEY_USER_CHOSEN_VENUE, false);
    }

    public static void setUserHasChosenVenue(@NonNull Context context, boolean state) {
        final SharedPreferences sp = context.getSharedPreferences(settingsPrefsBaseFileName, Context.MODE_PRIVATE);

        final SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean(SharedPrefsHelper.SETTINGS_PREFS_KEY_USER_CHOSEN_VENUE, state);
        editor.apply();
    }

    public static void setAppVersionName(@NonNull Context context, @NonNull String appVersionName) {
        final SharedPreferences sp = context.getSharedPreferences(settingsPrefsBaseFileName, Context.MODE_PRIVATE);
        final SharedPreferences.Editor editor = sp.edit();
        editor.putString(SharedPrefsHelper.SETTINGS_PREFS_KEY_APP_VERSION, appVersionName);
        editor.apply();
    }

    @NonNull
    public static String getAppVersionName(@NonNull Context context) {
        final SharedPreferences sp = context.getSharedPreferences(settingsPrefsBaseFileName, Context.MODE_PRIVATE);

        return sp.getString(SharedPrefsHelper.SETTINGS_PREFS_KEY_APP_VERSION, "");
    }

    public static void setUserTravelingMode(@NonNull Context context, @MapsIndoorsHelper.Vehicle int travelingMode) {
        final SharedPreferences sp = context.getSharedPreferences(settingsPrefsBaseFileName, Context.MODE_PRIVATE);
        final SharedPreferences.Editor editor = sp.edit();
        editor.putInt(SharedPrefsHelper.SETTINGS_PREFS_KEY_USER_CHOSEN_TRAVEL_MODE, travelingMode);
        editor.apply();
    }

    @MapsIndoorsHelper.Vehicle
    public static int getUserTravelingMode(@NonNull Context context) {
        final SharedPreferences sp = context.getSharedPreferences(settingsPrefsBaseFileName, Context.MODE_PRIVATE);

        return sp.getInt(SharedPrefsHelper.SETTINGS_PREFS_KEY_USER_CHOSEN_TRAVEL_MODE, MapsIndoorsHelper.VEHICLE_NONE);
    }

    /**
     * Stores the given venue id
     *
     * @param context
     * @param venueId
     */
    public static void setCurrentVenueId(@NonNull Context context, @NonNull String venueId) {
        final SharedPreferences sp = context.getSharedPreferences(settingsPrefsBaseFileName, Context.MODE_PRIVATE);
        final SharedPreferences.Editor editor = sp.edit();
        editor.putString(SharedPrefsHelper.SETTINGS_PREFS_KEY_CURRENT_VENUE_ID, venueId);
        editor.apply();
    }

    /**
     * @param context
     * @return The last venue id set by the user, empty string if nothing has been saved yet
     */
    @NonNull
    public static String getCurrentVenueId(@NonNull Context context) {
        final SharedPreferences sp = context.getSharedPreferences(settingsPrefsBaseFileName, Context.MODE_PRIVATE);

        return sp.getString(SharedPrefsHelper.SETTINGS_PREFS_KEY_CURRENT_VENUE_ID, "");
    }

    public static void setAvoidStairs(@NonNull Context context, boolean avoidStairs) {
        final SharedPreferences sp = context.getSharedPreferences(settingsPrefsBaseFileName, Context.MODE_PRIVATE);
        final SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean(SharedPrefsHelper.SETTINGS_PREFS_KEY_AVOID_STAIRS, avoidStairs);
        editor.apply();
    }

    public static boolean getAvoidStairs(@NonNull Context context) {
        final SharedPreferences sp = context.getSharedPreferences(settingsPrefsBaseFileName, Context.MODE_PRIVATE);

        return sp.getBoolean(SharedPrefsHelper.SETTINGS_PREFS_KEY_AVOID_STAIRS, false);
    }

    public static void setZoomForDetailButtonToShow(@NonNull Context context, boolean buttonToShow) {
        final SharedPreferences sp = context.getSharedPreferences(settingsPrefsBaseFileName, Context.MODE_PRIVATE);
        final SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean(SharedPrefsHelper.SETTINGS_PREFS_KEY_SHOW_ZOOM_BUTTON, buttonToShow);
        editor.apply();
    }

    public static boolean isZoomForDetailButtonToShow(@NonNull Context context) {
        final SharedPreferences sp = context.getSharedPreferences(settingsPrefsBaseFileName, Context.MODE_PRIVATE);
        return sp.getBoolean(SharedPrefsHelper.SETTINGS_PREFS_KEY_SHOW_ZOOM_BUTTON, true);
    }

    public static void setApiKeyValidity(@NonNull Context context, boolean keyValidity) {
        final SharedPreferences sp = context.getSharedPreferences(settingsPrefsBaseFileName, Context.MODE_PRIVATE);
        final SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean(SharedPrefsHelper.SETTINGS_PREFS_KEY_API_KEY_VALIDITY, keyValidity);
        editor.apply();
    }

    public static boolean getApiKeyValidity(@NonNull Context context) {
        final SharedPreferences sp = context.getSharedPreferences(settingsPrefsBaseFileName, Context.MODE_PRIVATE);

        return sp.getBoolean(SharedPrefsHelper.SETTINGS_PREFS_KEY_API_KEY_VALIDITY, true);
    }

    /**
     * Note that this is stored in a separate file (not tied to an api key as the others)
     *
     * @param context
     * @param solutionAlias A valid MapsIndoors API Key / solution alias
     */
    public static void setSolutionKeyAlias(@NonNull Context context, @NonNull String solutionAlias) {
        final SharedPreferences sp = context.getSharedPreferences(SETTINGS_PREFS_BASE_FILE_NAME, Context.MODE_PRIVATE);
        final SharedPreferences.Editor editor = sp.edit();
        editor.putString(SharedPrefsHelper.SETTINGS_PREFS_KEY_SOLUTION_ALIAS_KEY, solutionAlias);
        editor.apply();
    }

    /**
     * Note that this is stored in a separate file (not tied to an api key as the others)
     *
     * @param context
     * @return The last stored MapsIndoors API Key, {@code null} otherwise
     */
    @Nullable
    public static String getSolutionKeyAlias(@NonNull Context context) {
        final SharedPreferences sp = context.getSharedPreferences(SETTINGS_PREFS_BASE_FILE_NAME, Context.MODE_PRIVATE);

        return sp.getString(SharedPrefsHelper.SETTINGS_PREFS_KEY_SOLUTION_ALIAS_KEY, null);
    }

    public static void clearSolutionKeyAlias(@NonNull Context context) {
        final SharedPreferences sp = context.getSharedPreferences(SETTINGS_PREFS_BASE_FILE_NAME, Context.MODE_PRIVATE);
        final SharedPreferences.Editor editor = sp.edit();
        editor.remove(SharedPrefsHelper.SETTINGS_PREFS_KEY_SOLUTION_ALIAS_KEY);
        editor.apply();
    }

    public static void setSelectedUserRoles(@NonNull Context context, @NonNull Set<String> userRoleIds) {
        final SharedPreferences sp = context.getSharedPreferences( settingsPrefsBaseFileName, Context.MODE_PRIVATE );
        final SharedPreferences.Editor editor = sp.edit();

        editor.remove(SharedPrefsHelper.SETTINGS_PREFS_KEY_SELECTED_USER_ROLES);
        editor.apply();

        final Set<String> values = new HashSet<>( userRoleIds );
        final SharedPreferences.Editor editor1 = context.getSharedPreferences(settingsPrefsBaseFileName, context.MODE_PRIVATE).edit();

        editor1.putStringSet( SharedPrefsHelper.SETTINGS_PREFS_KEY_SELECTED_USER_ROLES, values );
        editor1.apply();
    }

    @NonNull
    public static Set<String> getSelectedUserRoles(@NonNull Context context) {
        final SharedPreferences sp = context.getSharedPreferences(settingsPrefsBaseFileName, Context.MODE_PRIVATE);
        final Set<String> values = sp.getStringSet(SharedPrefsHelper.SETTINGS_PREFS_KEY_SELECTED_USER_ROLES, new HashSet<>(0));
        return values;
    }

    public static void clearSharedPref(@NonNull Context context) {
        final SharedPreferences settings = context.getSharedPreferences(settingsPrefsBaseFileName, Context.MODE_PRIVATE);
        settings.edit().clear().apply();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <LinearLayout
        android:id="@+id/linearlayout_quiz_dialog_wrapper"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="vertical"
        android:layout_margin="20dp"
        android:background="@drawable/xhdpi_normal_button">

    <TextView
        android:id="@+id/textview_quiz_dialog_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/button_start_quiz"
        android:textSize="24sp"
        android:gravity="center"
        android:paddingBottom="20dp" />

    <Button
        android:id="@+id/button_start_quiz"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24dp"
        android:textColor="@color/yellow"
        android:background="@null" />

    </LinearLayout>

</LinearLayout>


text:
import _plotly_utils.basevalidators

class ZValidator(_plotly_utils.basevalidators.CompoundValidator):
    def __init__(self, plotly_name="z", parent_name="surface.contours", **kwargs):
        super(ZValidator, self).__init__(
            plotly_name=plotly_name,
            parent_name=parent_name,
            data_class_str=kwargs.pop("data_class_str", "Z"),
            data_docs=kwargs.pop(
                "data_docs",
                """
            color
                Sets the color of the contour lines.
            end
                Sets the end contour level value. Must be more
                than `contours.start`
            highlight
                Determines whether or not contour lines about
                the z dimension are highlighted on hover.
            highlightcolor
                Sets the color of the highlighted contour
                lines.
            highlightwidth
                Sets the width of the highlighted contour
                lines.
            project
                :class:`plotly.graph_objects.surface.contours.z
                .Project` instance or dict with compatible
                properties
            show
                Determines whether or not contour lines about
                the z dimension are drawn.
            size
                Sets the step between each contour level. Must
                be positive.
            start
                Sets the starting contour level value. Must be
                less than `contours.end`
            usecolormap
                An alternate to "color". Determines whether or
                not the contour lines are colored using the
                trace "colorscale".
            width
                Sets the width of the contour lines.
""",
            ),
            **kwargs
        )


text:
.class Lcom/samsung/android/settings/lockappshortcut/AppShortcutInfo;
.super Ljava/lang/Object;
.source "AppShortcutInfo.java"

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/samsung/android/settings/lockappshortcut/AppShortcutInfo$AppInfo;,
        Lcom/samsung/android/settings/lockappshortcut/AppShortcutInfo$AppListItem;
    }
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method public static getApplicationInfo(Landroid/content/Context;ILcom/samsung/android/settings/lockappshortcut/AppShortcutInfo$AppInfo;)Lcom/samsung/android/settings/lockappshortcut/AppShortcutInfo$AppInfo;
    .locals 16

    invoke-virtual/range {p0 .. p0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v13

    const-string/jumbo v14, "lock_application_shortcut"

    invoke-static {v13, v14}, Landroid/provider/Settings$System;->getString(Landroid/content/ContentResolver;Ljava/lang/String;)Ljava/lang/String;

    move-result-object v2

    if-eqz v2, :cond_0

    const-string/jumbo v13, ""

    invoke-virtual {v13, v2}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v13

    if-eqz v13, :cond_1

    :cond_0
    const/4 v13, 0x0

    return-object v13

    :cond_1
    const-string/jumbo v13, ";"

    invoke-virtual {v2, v13}, Ljava/lang/String;->split(Ljava/lang/String;)[Ljava/lang/String;

    move-result-object v12

    aget-object v3, v12, p1

    if-eqz v3, :cond_2

    const-string/jumbo v13, ""

    invoke-virtual {v13, v3}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v13

    if-eqz v13, :cond_3

    :cond_2
    const/4 v13, 0x0

    return-object v13

    :cond_3
    const/16 v13, 0x2f

    const/4 v14, 0x0

    invoke-virtual {v3, v13, v14}, Ljava/lang/String;->indexOf(II)I

    move-result v10

    const/4 v13, 0x0

    invoke-virtual {v3, v13, v10}, Ljava/lang/String;->substring(II)Ljava/lang/String;

    move-result-object v11

    add-int/lit8 v13, v10, 0x1

    invoke-virtual {v3}, Ljava/lang/String;->length()I

    move-result v14

    invoke-virtual {v3, v13, v14}, Ljava/lang/String;->substring(II)Ljava/lang/String;

    move-result-object v1

    const/4 v8, 0x0

    const/4 v9, 0x0

    :try_start_0
    invoke-virtual/range {p0 .. p0}, Landroid/content/Context;->getPackageManager()Landroid/content/pm/PackageManager;

    move-result-object v13

    new-instance v14, Landroid/content/ComponentName;

    invoke-direct {v14, v11, v1}, Landroid/content/ComponentName;-><init>(Ljava/lang/String;Ljava/lang/String;)V

    const/16 v15, 0x200

    invoke-virtual {v13, v14, v15}, Landroid/content/pm/PackageManager;->getActivityInfo(Landroid/content/ComponentName;I)Landroid/content/pm/ActivityInfo;

    move-result-object v8

    invoke-virtual/range {p0 .. p0}, Landroid/content/Context;->getPackageManager()Landroid/content/pm/PackageManager;

    move-result-object v13

    invoke-virtual {v8, v13}, Landroid/content/pm/ActivityInfo;->loadLabel(Landroid/content/pm/PackageManager;)Ljava/lang/CharSequence;

    move-result-object v13

    check-cast v13, Ljava/lang/String;

    move-object/from16 v0, p2

    iput-object v13, v0, Lcom/samsung/android/settings/lockappshortcut/AppShortcutInfo$AppInfo;->mLabel:Ljava/lang/String;

    move-object/from16 v0, p0

    invoke-static {v0, v11}, Lcom/android/settings/Utils;->isEnabledPkg(Landroid/content/Context;Ljava/lang/String;)Z

    move-result v13

    move-object/from16 v0, p2

    iput-boolean v13, v0, Lcom/samsung/android/settings/lockappshortcut/AppShortcutInfo$AppInfo;->isActive:Z

    invoke-virtual/range {p0 .. p0}, Landroid/content/Context;->getPackageManager()Landroid/content/pm/PackageManager;

    move-result-object v13

    const/4 v14, 0x1

    const/4 v15, 0x1

    invoke-virtual {v8, v13, v14, v15}, Landroid/content/pm/ActivityInfo;->loadIcon(Landroid/content/pm/PackageManager;ZI)Landroid/graphics/drawable/Drawable;

    move-result-object v13

    move-object/from16 v0, p2

    iput-object v13, v0, Lcom/samsung/android/settings/lockappshortcut/AppShortcutInfo$AppInfo;->mIcon:Landroid/graphics/drawable/Drawable;
    :try_end_0
    .catch Landroid/content/pm/PackageManager$NameNotFoundException; {:try_start_0 .. :try_end_0} :catch_1
    .catch Ljava/lang/ClassCastException; {:try_start_0 .. :try_end_0} :catch_0

    :goto_0
    if-nez v9, :cond_4

    :try_start_1
    invoke-virtual/range {p0 .. p0}, Landroid/content/Context;->getPackageManager()Landroid/content/pm/PackageManager;

    move-result-object v13

    new-instance v14, Landroid/content/ComponentName;

    invoke-direct {v14, v11, v1}, Landroid/content/ComponentName;-><init>(Ljava/lang/String;Ljava/lang/String;)V

    const/16 v15, 0x80

    invoke-virtual {v13, v14, v15}, Landroid/content/pm/PackageManager;->getActivityInfo(Landroid/content/ComponentName;I)Landroid/content/pm/ActivityInfo;

    move-result-object v8

    invoke-virtual/range {p0 .. p0}, Landroid/content/Context;->getPackageManager()Landroid/content/pm/PackageManager;

    move-result-object v13

    invoke-virtual {v8, v13}, Landroid/content/pm/ActivityInfo;->loadLabel(Landroid/content/pm/PackageManager;)Ljava/lang/CharSequence;

    move-result-object v13

    check-cast v13, Ljava/lang/String;

    move-object/from16 v0, p2

    iput-object v13, v0, Lcom/samsung/android/settings/lockappshortcut/AppShortcutInfo$AppInfo;->mLabel:Ljava/lang/String;

    move-object/from16 v0, p0

    invoke-static {v0, v11}, Lcom/android/settings/Utils;->isEnabledPkg(Landroid/content/Context;Ljava/lang/String;)Z

    move-result v13

    move-object/from16 v0, p2

    iput-boolean v13, v0, Lcom/samsung/android/settings/lockappshortcut/AppShortcutInfo$AppInfo;->isActive:Z

    invoke-virtual/range {p0 .. p0}, Landroid/content/Context;->getPackageManager()Landroid/content/pm/PackageManager;

    move-result-object v13

    const/4 v14, 0x1

    const/4 v15, 0x1

    invoke-virtual {v8, v13, v14, v15}, Landroid/content/pm/ActivityInfo;->loadIcon(Landroid/content/pm/PackageManager;ZI)Landroid/graphics/drawable/Drawable;

    move-result-object v13

    move-object/from16 v0, p2

    iput-object v13, v0, Lcom/samsung/android/settings/lockappshortcut/AppShortcutInfo$AppInfo;->mIcon:Landroid/graphics/drawable/Drawable;
    :try_end_1
    .catch Landroid/content/pm/PackageManager$NameNotFoundException; {:try_start_1 .. :try_end_1} :catch_3
    .catch Ljava/lang/ClassCastException; {:try_start_1 .. :try_end_1} :catch_2

    :cond_4
    :goto_1
    return-object p2

    :catch_0
    move-exception v5

    invoke-virtual {v5}, Ljava/lang/ClassCastException;->printStackTrace()V

    const-string/jumbo v13, "AppShortcutInfo"

    const-string/jumbo v14, "ClassCastException occured"

    invoke-static {v13, v14}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    goto :goto_0

    :catch_1
    move-exception v4

    const-string/jumbo v13, "AppShortcutInfo"

    const-string/jumbo v14, "cannot find app name !"

    invoke-static {v13, v14}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    const/4 v9, 0x1

    goto :goto_0

    :catch_2
    move-exception v7

    invoke-virtual {v7}, Ljava/lang/ClassCastException;->printStackTrace()V

    const-string/jumbo v13, "AppShortcutInfo"

    const-string/jumbo v14, "ClassCastException occured"

    invoke-static {v13, v14}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    goto :goto_1

    :catch_3
    move-exception v6

    const-string/jumbo v13, "AppShortcutInfo"

    const-string/jumbo v14, "cannot find app name !"

    invoke-static {v13, v14}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    move-object/from16 v0, p2

    iget-boolean v13, v0, Lcom/samsung/android/settings/lockappshortcut/AppShortcutInfo$AppInfo;->isActive:Z

    if-eqz v13, :cond_4

    const/16 p2, 0x0

    goto :goto_1
.end method

.method protected static getApplicationInfo(Landroid/content/Context;I)Ljava/lang/String;
    .locals 4

    const/4 v2, 0x0

    if-nez p0, :cond_0

    return-object v2

    :cond_0
    invoke-virtual {p0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v2

    const-string/jumbo v3, "lock_application_shortcut"

    invoke-static {v2, v3}, Landroid/provider/Settings$System;->getString(Landroid/content/ContentResolver;Ljava/lang/String;)Ljava/lang/String;

    move-result-object v0

    const-string/jumbo v2, ";"

    invoke-virtual {v0, v2}, Ljava/lang/String;->split(Ljava/lang/String;)[Ljava/lang/String;

    move-result-object v1

    aget-object v2, v1, p1

    return-object v2
.end method

.method protected static getShortcutStatus(Landroid/content/Context;I)Z
    .locals 4

    invoke-virtual {p0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v2

    const-string/jumbo v3, "lock_application_shortcut"

    invoke-static {v2, v3}, Landroid/provider/Settings$System;->getString(Landroid/content/ContentResolver;Ljava/lang/String;)Ljava/lang/String;

    move-result-object v0

    const-string/jumbo v2, ";"

    invoke-virtual {v0, v2}, Ljava/lang/String;->split(Ljava/lang/String;)[Ljava/lang/String;

    move-result-object v1

    aget-object v2, v1, p1

    const-string/jumbo v3, "1"

    invoke-virtual {v2, v3}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v2

    if-eqz v2, :cond_0

    const/4 v2, 0x1

    :goto_0
    return v2

    :cond_0
    const/4 v2, 0x0

    goto :goto_0
.end method

.method protected static saveApplicationData(Landroid/content/Context;ILjava/lang/String;)V
    .locals 7

    invoke-virtual {p0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v3

    const-string/jumbo v4, "lock_application_shortcut"

    invoke-static {v3, v4}, Landroid/provider/Settings$System;->getString(Landroid/content/ContentResolver;Ljava/lang/String;)Ljava/lang/String;

    move-result-object v0

    const-string/jumbo v3, ";"

    invoke-virtual {v0, v3}, Ljava/lang/String;->split(Ljava/lang/String;)[Ljava/lang/String;

    move-result-object v2

    aput-object p2, v2, p1

    const-string/jumbo v0, ""

    const/4 v3, 0x0

    array-length v4, v2

    :goto_0
    if-ge v3, v4, :cond_0

    aget-object v1, v2, v3

    new-instance v5, Ljava/lang/StringBuilder;

    invoke-direct {v5}, Ljava/lang/StringBuilder;-><init>()V

    invoke-virtual {v5, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v5

    invoke-virtual {v5, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v5

    const-string/jumbo v6, ";"

    invoke-virtual {v5, v6}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v5

    invoke-virtual {v5}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    add-int/lit8 v3, v3, 0x1

    goto :goto_0

    :cond_0
    invoke-virtual {p0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v3

    const-string/jumbo v4, "lock_application_shortcut"

    invoke-static {v3, v4, v0}, Landroid/provider/Settings$System;->putString(Landroid/content/ContentResolver;Ljava/lang/String;Ljava/lang/String;)Z

    return-void
.end method


text:
#ifndef MULTINOMIAL_VERTEX_SET_HPP
#define MULTINOMIAL_VERTEX_SET_HPP

#include <string>

#include <graphlab/graph/graph.hpp>
#include <graphlab/parallel/pthread_tools.hpp>
#include <graphlab/util/fast_multinomial.hpp>
#include <graphlab/schedulers/set_scheduler/set_generic_typedefs.hpp>
#include <graphlab/schedulers/set_scheduler/ivertex_set.hpp>
namespace graphlab {

  /**
     A vertex set built around the bitmagic bitvector
  */
  template<typename Graph>
  class multinomial_vertex_set :
    public ivertex_set<Graph> {
  public:

  public:
    typedef Graph graph_type;
    typedef typename graph_type::vertex_data_type vertex_data_type;
    typedef ivertex_set<Graph> base;
    typedef set_scheduler<Graph> set_scheduler_type;
    typedef iscope<Graph> iscope_type;

    using base::trigger_all_insert;
    using base::trigger_all_erase;
    using base::trigger_all_modify_vertex;
    using base::trigger_all_modify_edge;
    using base::trigger_all_rebuild;

    /**
       double priority_function(vertexid, vertexblob)
       This is a user provided function which returns the priority of the vertex
    */
    typedef boost::function2<double, vertex_id_t, const vertex_data_type&>
    priority_function_type;

    multinomial_vertex_set(priority_function_type p) {
      pfunction = p;
      vset = NULL;
    }

    multinomial_vertex_set(double (*p)(vertex_id_t, const vertex_data_type&)) {
      pfunction = p;
      vset = NULL;
    };

    ~multinomial_vertex_set() {
      if (vset) delete vset;
    }

    void init(Graph *g_,
              base *src,
              set_scheduler_type *sched,
              size_t ncpus_) {
      g = g_;
      // register this set with the source
      if (src) src->add_event_target(this);
      // set the bitset to be the same size as the graph
      vset = new fast_multinomial(g->num_vertices(), sched->num_cpus());
      // build the lockset
      locks.resize(g->num_vertices());
    }

    /** v will be inserted into this set when this event is triggered */
    void insert(base* parent, vertex_id_t v) {
      locks[v].lock();
      if (!has_vertex(v)) {
        vset->set(v, get_priority(v));
        trigger_all_insert(v);
      }
      locks[v].unlock();
    }

    /** v will be erased from this set when this event is triggered */
    void erase(base* parent, vertex_id_t v) {
      locks[v].lock();
      if (has_vertex(v)) {
        vset->zero(v);
        trigger_all_erase(v);
      }
      locks[v].unlock();
    }

    /** pass through if this set contains this vertex */
    void modify_vertex(base* parent, vertex_id_t v) {
      locks[v].lock();
      // test the vertex
      double pr = get_priority(v);
      bool hasv = has_vertex(v);
      if (hasv && pr == 0) {
        // if priority is 0, and we currently have the vertex, this is a deletion
        vset->zero(v);
        trigger_all_erase(v);
      } else if (!hasv && pr > 0) {
        // if priority is non zero, and we currently do not have the vertex,
        // this is an insertion
        vset->set(v, pr);
        trigger_all_insert(v);
      } else if (hasv && pr > 0) {
        // if priority is non zero, but we already have the vertex, this is
        // a modification
        vset->set(v, pr);
        trigger_all_modify_vertex(v);
      }
      locks[v].unlock();
    }

    /** pass through */
    void modify_edge(base* parent, edge_id_t e) {
      // send the modification only if source/target is here
      vertex_id_t v = g->target(e);
      locks[v].lock();
      if (has_vertex(v)) trigger_all_modify_edge(e);
      locks[v].unlock();
    }

    /**reconstructs this set from rebuildset */
    void rebuild(base* parent, const ss_set_type &rebuildset) {
      logger(LOG_INFO, "Rebuild on %s", name().c_str());
      ss_set_type_iterator i = begin(rebuildset);
      ss_set_type_iterator iend = end(rebuildset);
      ss_set_type newrebuildset;
      vset->clear();
      while (i != iend) {
        double pr = get_priority(*i);
        if (pr > 0) {
          vset->set(*i, get_priority(*i));
          ss_insert(newrebuildset, *i);
        }
        i++;
      }
      trigger_all_rebuild(newrebuildset);
    }

    size_t size() const {
      return vset->positive_support();
    }

    /// Returns true if this set has vertex vertexid
    bool has_vertex(const vertex_id_t &vertexid) const {
      return vset->has_support(vertexid);
    }

    /// Returns this set as a bitvector
    ss_set_type get() const {
      // TODO:
      ss_set_type ret;
      for(size_t i = 0;i < g->num_vertices(); ++i) {
        if (vset->has_support(i)) ss_insert(ret, i);
      }
      return ret;
    }

    std::string name(void) const{
      return "Multinomial Priority";
    }

    bool first(vertex_id_t &i, size_t cpuid) {
      return this->next(i, cpuid);
    }
    /// Returns the next vertex in the set (in increasing value), looping around
    /// when we reach the last vertex. Returns false if there are no elements
    /// in the set
    bool next(vertex_id_t &i, size_t cpuid) {
      size_t s = 0;
      bool ret = vset->sample(s, cpuid);
      i = vertex_id_t(s);
      return ret;
    }

    size_t supported_events() {
      return INSERT_EVENT | ERASE_EVENT | MODIFY_VERTEX_EVENT;
    }

  private:
    Graph *g;
    fast_multinomial *vset;
    priority_function_type pfunction;
    std::vector<spinlock> locks;

    double get_priority(vertex_id_t v) {
      return pfunction(v, g->vertex_data(v));
    }
  };

};

#endif


text:
package org.jetbrains.plugins.scala
package codeInspection.typeChecking

import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.testFramework.EditorTestUtil
import org.jetbrains.plugins.scala.codeInspection.{InspectionBundle, ScalaInspectionTestBase}

/**
 * Nikolay.Tropin
 * 9/26/13
 */
class ComparingUnrelatedTypesInspectionTest extends ScalaInspectionTestBase {

  import EditorTestUtil.{SELECTION_END_TAG => END, SELECTION_START_TAG => START}

  override protected val classOfInspection: Class[_ <: LocalInspectionTool] =
    classOf[ComparingUnrelatedTypesInspection]

  override protected val description: String =
    ComparingUnrelatedTypesInspection.inspectionName

  def testWeakConformance() {
    val text1 = s"""val a = 0
                 |val b: Short = 1
                 |${START}b == a$END"""
    checkTextHasNoUnrelatedTypeErrors(text1)

    val text2 = s"""val a = 0
                  |val b = 1.0
                  |${START}b != a$END"""
    checkTextHasNoUnrelatedTypeErrors(text2)

    val text3 = s"""val a = 0.0
                  |val b: Byte = 100
                  |${START}a == b$END"""
    checkTextHasNoUnrelatedTypeErrors(text3)

    val text4 = s"${START}1 == 1.0$END"
    checkTextHasNoUnrelatedTypeErrors(text4)
  }

  def testValueTypes() {
    val text1 = s"""val a = true
                 |val b = 1
                 |${START}b == a$END"""
    checkTextHasError(text1, errorDescriptionForTypes("Int", "Boolean"))

    val text2 = s"""val a = true
                 |val b = 0.0
                 |${START}a != b$END"""
    checkTextHasError(text2, errorDescriptionForTypes("Boolean", "Double"))

    val text3 = s"${START}true != 0$END"
    checkTextHasError(text3, errorDescriptionForTypes("Boolean", "Int"))

    val text4: String = s"${START}1.isInstanceOf[Boolean]$END"
    checkTextHasError(text4, errorDescriptionForTypes("Int", "Boolean"))

  }

  def testString() {
    val text1 = s"""val a = "a"
                 |val b = Array('a')
                 |${START}b == a$END"""
    checkTextHasError(text1, errorDescriptionForTypes("Array[Char]", "String"))

    val text2 = s"""val a = "0"
                 |val b = 0
                 |${START}a == b$END"""
    checkTextHasError(text2, errorDescriptionForTypes("String", "Int"))

    val text3 = s"""val s = "s"
                  |${START}s == 's'$END"""
    checkTextHasError(text3, errorDescriptionForTypes("String", "Char"))

    val text4 = s"""val a = "a"
                  |val b: CharSequence = null
                  |${START}b != a$END"""
    checkTextHasNoUnrelatedTypeErrors(text4)
  }

  def testInheritors() {
    val text1 = s"""val a = scala.collection.Iterable(1)
                 |val b = List(0)
                 |${START}b == a$END"""
    checkTextHasNoUnrelatedTypeErrors(text1)

    val text2 = s"""case class A(i: Int)
                   |final class B extends A(1)
                   |val a: A = A(0)
                   |val b: B = new B
                   |${START}a == b$END"""
    checkTextHasNoUnrelatedTypeErrors(text2)

    val text3 = """trait A
                  |object B extends A
                  |B.isInstanceOf[A]"""
    checkTextHasNoUnrelatedTypeErrors(text3)
  }

  def testFinal() {
    val text1 = s"""case class A(i: Int)
                   |class B extends A(1)
                   |val a: A = A(0)
                   |val b: B = new B
                   |${START}a == b$END"""
    checkTextHasNoUnrelatedTypeErrors(text1)

    val text2 = s"""final class A extends Serializable
                  |final class B extends Serializable
                  |val a: A = new A
                  |val b: B = new B
                  |${START}a == b$END"""
    checkTextHasError(text2, errorDescriptionForTypes("A", "B"))

    val text3 = s"""final class A extends Serializable
                   |final class B extends Serializable
                   |val a: A = new A
                   |${START}a.isInstanceOf[B]$END"""
    checkTextHasError(text3, errorDescriptionForTypes("A", "B"))
  }

  def testTraits() {
    val text1 = s"""trait A
                  |trait B
                  |val a: A = _
                  |val b: B = _
                  |${START}a == b$END"""
    checkTextHasNoUnrelatedTypeErrors(text1)
  }

  def testObject() {
    val text1 = s"""trait A
                  |object B extends A
                  |val a: A = _
                  |${START}a == B$END"""
    checkTextHasNoUnrelatedTypeErrors(text1)

    val text2 = s"""trait A
                  |object B extends A
                  |class C extends A
                  |val c = new C
                  |${START}c == B$END"""
    checkTextHasError(text2, errorDescriptionForTypes("C", "B.type"))

    val text3 = s"""trait A
                  |object B extends A
                  |class C extends A
                  |val c: A = new C
                  |${START}c != B$END"""
    checkTextHasNoUnrelatedTypeErrors(text3)
  }

  def testBoxedTypes() {
    val text1 = """val i = new java.lang.Integer(0)
                  |i == 100"""
    checkTextHasNoUnrelatedTypeErrors(text1)

    val text2 = """val b = new java.lang.Boolean(false)
                  |b equals true"""
    checkTextHasNoUnrelatedTypeErrors(text2)

    val text3 = "def test(i: Integer) = if (i == null) \"foo\" else \"bar\""
    checkTextHasNoUnrelatedTypeErrors(text3)
  }

  def testExistential(): Unit = {
    checkTextHasNoUnrelatedTypeErrors("Seq(1).isInstanceOf[List[_])")
    checkTextHasError(s"${START}Some(1).isInstanceOf[List[_]]$END", errorDescriptionForTypes("Some[Int]", "List[_]"))
    checkTextHasNoUnrelatedTypeErrors("def foo(x: Some[_]) { x == Some(1) }")
    checkTextHasError(s"def foo(x: Some[_]) { ${START}x == Seq(1)$END }", errorDescriptionForTypes("Some[_]", "Seq[Int]"))
  }

  def testNumeric(): Unit = {
    checkTextHasNoUnrelatedTypeErrors("BigInt(1) == 1")
    checkTextHasNoUnrelatedTypeErrors("BigInt(1) == 1L")
    checkTextHasNoUnrelatedTypeErrors("BigInt(1) == new java.lang.Integer(1)")
    checkTextHasError(s"${START}BigInt(1) == true$END", errorDescriptionForTypes("BigInt", "Boolean"))
    checkTextHasError(s"${START}BigInt(1) == 1.toString$END", errorDescriptionForTypes("BigInt", "String"))
  }

  def testTypeAlias(): Unit = {
    checkTextHasNoUnrelatedTypeErrors(
      """
        |object A {
        |  type Coord = Float
        |  def isZero(n: Coord): Boolean = {
        |    n == 0
        |  }
        |}
      """.stripMargin)

    checkTextHasError(
      s"""
        |object A {
        |  type Coord = String
        |  def isZero(n: Coord): Boolean = {
        |    ${START}n == 0$END
        |  }
        |}
      """.stripMargin, errorDescriptionForTypes("A.Coord", "Int"))

    checkTextHasNoUnrelatedTypeErrors(
      """
        |trait A {
        |  type Coord
        |
        |  def isZero(n: Coord): Boolean = {
        |    n == 0
        |  }
        |}
      """.stripMargin)
  }

  def testOverridenMethods(): Unit = {
    checkTextHasNoUnrelatedTypeErrors(
      """
        |case class Dummy(v: Int) {
        |  def ==(value: Int): String = v + " == " + value
        |  def !=(value: Int): Boolean = v != value
        |}
        |
        |object Test {
        |  val a: String = Dummy(5) == 10
        |  val b: Boolean = Dummy(5) != 10
        |}""".stripMargin)

    checkTextHasError(
      s"""
        |case class Dummy(v: Int) {
        |  def ==(value: Int): String = v + " == " + value
        |  def !=(value: Int): Boolean = v != value
        |}
        |
        |object Test {
        |  val b: Boolean = ${START}Dummy(5) eq 10$END
        |}""".stripMargin, errorDescriptionForTypes("Dummy", "Int"))

  }

  def testOverridenWithImplicitParam(): Unit = {
    checkTextHasError(
      s"""
        |class Store(val foo: Int, val bar: String)
        |trait Binder[T] {
        |  def get(implicit store: Store): T
        |  def ==(other: Binder[T])(implicit store: Store) = get == other.get
        |  def ==(other: T)(implicit store: Store) = get == other
        |}
        |class FooBinder extends Binder[Int] {
        |  def get(implicit store: Store) = store.foo
        |}
        |class BarBinder extends Binder[String] {
        |  def get(implicit store: Store) = store.bar
        |}
        |
        |val fooBinder = new FooBinder
        |val barBinder = new BarBinder
        |
        |{
        |  implicit val store = new Store(12, ":)")
        |  (fooBinder == 12, fooBinder == 3, ${START}fooBinder == ":)"$END, barBinder == ":)") // (true, false, false, true)
        |}
      """.stripMargin, errorDescriptionForTypes("FooBinder", "String")
    )

  }

  def testOverridenEquals(): Unit = {
    checkTextHasError(
      s"""
         |case class Dummy(v: Int) {
         |  override def equals(other: Any): Boolean = other match {
         |    case Dummy(o) => o == v
         |    case _ => false
         |  }
         |}
         |
         |object Test {
         |  val b: Boolean = ${START}Dummy(5) equals 10$END
         |}""".stripMargin, errorDescriptionForTypes("Dummy", "Int"))

    checkTextHasError(
      s"""
         |case class Dummy(v: Int) {
         |  override def equals(other: Any): Boolean = other match {
         |    case Dummy(o) => o == v
         |    case _ => false
         |  }
         |}
         |
           |object Test {
         |  val b: Boolean = ${START}Dummy(5) == 10$END
         |}""".stripMargin, errorDescriptionForTypes("Dummy", "Int"))
  }

  def testSameNameTypes(): Unit = {
    checkTextHasError(
      s"""
         |package abc {
         |  class Dummy
         |}
         |
         |package cde {
         |  class Dummy
         |}
         |
         |object Test {
         |  val d1 = new abc.Dummy
         |  val d2 = new cde.Dummy
         |  ${START}d1 == d2$END
         |}
       """.stripMargin, errorDescriptionForTypes("abc.Dummy", "cde.Dummy"))
  }

  private def checkTextHasNoUnrelatedTypeErrors(text: String) = {
    checkTextHasNoErrors(text,desc => desc != null && desc.toLowerCase.contains("unrelated"))
  }

  private def errorDescriptionForTypes(firstType: String, secondType: String): String = {
    InspectionBundle.message("comparing.unrelated.types.hint", firstType, secondType)
  }
}


text:
package com.facebook.buck.distributed;

import com.facebook.buck.distributed.thrift.BuckVersion;
import com.facebook.buck.distributed.thrift.BuckVersionType;
import com.facebook.buck.distributed.thrift.FileInfo;
import com.google.common.hash.Hashing;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public abstract class BuckVersionUtil {
  private BuckVersionUtil() {
    // do not instantiate
  }

  public static BuckVersion createFromGitHash(String gitHash) {
    BuckVersion buckVersion = new BuckVersion();
    buckVersion.setType(BuckVersionType.GIT);
    buckVersion.setGitHash(gitHash);
    return buckVersion;
  }

  public static BuckVersion createFromLocalBinary(Path localBuckBinary) throws IOException {
    byte[] data = Files.readAllBytes(localBuckBinary);
    String hash = Hashing.sha1().newHasher().putBytes(data).hash().toString();

    FileInfo buckBinary = new FileInfo();
    buckBinary.setContent(data);
    buckBinary.setContentHash(hash);

    BuckVersion buckVersion = new BuckVersion();
    buckVersion.setType(BuckVersionType.DEVELOPMENT);
    buckVersion.setDevelopmentVersion(buckBinary);
    return buckVersion;
  }
}


text:
namespace content {

enum DownloadInterruptReason {
  DOWNLOAD_INTERRUPT_REASON_NONE = 0,

#define INTERRUPT_REASON(name, value)  DOWNLOAD_INTERRUPT_REASON_##name = value,

#include "content/public/browser/download_interrupt_reason_values.h"

#undef INTERRUPT_REASON
};

std::string CONTENT_EXPORT InterruptReasonDebugString(
    DownloadInterruptReason error);

}  // namespace content

#endif  // CONTENT_PUBLIC_BROWSER_DOWNLOAD_INTERRUPT_REASONS_H_


text:
<!DOCTYPE html>

    <title>Movement Concierge</title>
    <meta http-equiv="X-UA-Compatible" content="IE=8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0" />
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <base target="_top" />

    <link rel="stylesheet" type="text/css" href="css/widget.min.css?1459395021" />

Let's rap.


text:
package martin.common;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Logger;

public class MyConnection {
	private String user;
	private String pass;
	private String host;
	private int port;
	private String schema;
	private Logger logger;
	private Connection conn;
	private final int RECONNECT_SLEEP_TIME = 10000;

	public MyConnection(String user, String pass, String host, int port, String schema, Logger logger) {
		this.user = user;
		this.pass = pass;
		this.host = host;
		this.port = port;
		this.schema = schema;
		this.logger = logger;
	}

	public Connection getConn() {
		try {
			if (conn == null || conn.isClosed()){
				boolean retry = true;
				boolean sleep = false;

				while (retry){
					try{
						if (sleep)
							Thread.sleep(RECONNECT_SLEEP_TIME);

						if (logger != null)
							logger.info("%t: Connecting to MySQL database " + schema
									+ " at " + user + "@" + host + ":" + port + "... ");

						Class.forName("com.mysql.jdbc.Driver").newInstance();

						conn = DriverManager.getConnection("jdbc:mysql://"
								+ host + ":" + port + "/" + schema + "?autoReconnect=true&user=" + user
								+ "&password=" + pass  + "&netTimeoutForStreamingResults=3600");

						if (logger != null)
							logger.info("%t: Done, connected to SQL server.\n");

						retry=false;

					} catch (Exception e){
						logger.warning("%t: SQL connection failed (" + e.toString() + "). Trying again in " + RECONNECT_SLEEP_TIME + " ms...");
						sleep=true;
					}
				}
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}

		return conn;
	}

	public Connection reconnect(){
		try{
			conn.close();
		} catch (Exception e){
		}

		conn = null;

		return getConn();
	}
}


text:
/* p2 - ƒƒjƒ…[ƒJƒeƒSƒŠ'ÌŠJ•Â'Ì'½'ß'ÌJavaScript */

var gHideClassName = 'itas_hide';

if (document.getElementById) {
	document.writeln('<style type="text/css" media="all">');
	document.writeln('<!--');
	document.writeln('.' + gHideClassName + '{ display:none; }');
	document.writeln('-->');
	document.writeln('</style>');
}

function showHide(id) {

	var obj = document.getElementById(id);

	if (!obj) {
		return false;
	}

	if (obj.style.display == 'block') {
		obj.style.display = "none";
	} else if(obj.style.display == 'none') {
		obj.style.display = "block";
	} else {
		if (obj.className != gHideClassName) {
			obj.style.display = "none";
		} else {
			obj.style.display = "block";
		}
	}
	return false;
}


text:
#import "MDCSliderColorThemer.h"
#import "MaterialPalettes.h"

static const CGFloat kSliderThemerLightAlpha = 0.26f;
static const CGFloat kSliderThemerDarkAlpha = 0.3f;
static const CGFloat kSliderBaselineDisabledFillAlpha = 0.32f;
static const CGFloat kSliderBaselineEnabledBackgroundAlpha = 0.24f;
static const CGFloat kSliderBaselineDisabledBackgroundAlpha = 0.12f;
static const CGFloat kSliderBaselineEnabledTicksAlpha = 0.54f;
static const CGFloat kSliderBaselineDisabledTicksAlpha = 0.12f;

@implementation MDCSliderColorThemer

+ (void)applySemanticColorScheme:(nonnull id<MDCColorScheming>)colorScheme
                        toSlider:(nonnull MDCSlider *)slider {
  UIColor *disabledFillColor =
      [colorScheme.onSurfaceColor colorWithAlphaComponent:kSliderBaselineDisabledFillAlpha];
  UIColor *enabledBackgroundColor =
      [colorScheme.primaryColor colorWithAlphaComponent:kSliderBaselineEnabledBackgroundAlpha];

  if (slider.statefulAPIEnabled) {
    [slider setTrackFillColor:colorScheme.primaryColor forState:UIControlStateNormal];
    [slider setTrackFillColor:disabledFillColor forState:UIControlStateDisabled];
    [slider setTrackBackgroundColor:enabledBackgroundColor forState:UIControlStateNormal];
    UIColor *disabledBackgroundColor =
        [colorScheme.onSurfaceColor colorWithAlphaComponent:kSliderBaselineDisabledBackgroundAlpha];
    [slider setTrackBackgroundColor:disabledBackgroundColor forState:UIControlStateDisabled];
    UIColor *enabledTickFillColor =
        [colorScheme.onPrimaryColor colorWithAlphaComponent:kSliderBaselineEnabledTicksAlpha];
    [slider setFilledTrackTickColor:enabledTickFillColor forState:UIControlStateNormal];
    UIColor *disabledTickFillColor =
        [colorScheme.onPrimaryColor colorWithAlphaComponent:kSliderBaselineDisabledTicksAlpha];
    [slider setFilledTrackTickColor:disabledTickFillColor forState:UIControlStateDisabled];
    UIColor *enabledTickBackgroundColor =
        [colorScheme.primaryColor colorWithAlphaComponent:kSliderBaselineEnabledTicksAlpha];
    [slider setBackgroundTrackTickColor:enabledTickBackgroundColor forState:UIControlStateNormal];
    UIColor *disabledTickBackgroundColor =
        [colorScheme.onSurfaceColor colorWithAlphaComponent:kSliderBaselineDisabledTicksAlpha];
    [slider setBackgroundTrackTickColor:disabledTickBackgroundColor
                               forState:UIControlStateDisabled];
    [slider setThumbColor:colorScheme.primaryColor forState:UIControlStateNormal];
    [slider setThumbColor:disabledFillColor forState:UIControlStateDisabled];
  } else {
    slider.color = colorScheme.primaryColor;
    slider.disabledColor = disabledFillColor;
    slider.trackBackgroundColor = enabledBackgroundColor;
  }

  slider.valueLabelTextColor = colorScheme.onPrimaryColor;
  slider.valueLabelBackgroundColor = colorScheme.primaryColor;
}

+ (void)applyColorScheme:(id<MDCColorScheme>)colorScheme
                toSlider:(MDCSlider *)slider {
  if ([colorScheme respondsToSelector:@selector(primaryLightColor)]) {
    slider.trackBackgroundColor = colorScheme.primaryLightColor;
  }
  slider.color = colorScheme.primaryColor;
  if ([colorScheme respondsToSelector:@selector(primaryDarkColor)]) {
    slider.disabledColor = colorScheme.primaryDarkColor;
  }
}

#pragma mark - Default color schemes

+ (MDCBasicColorScheme *)defaultSliderLightColorScheme {
  UIColor *lightTrackOffColor =
      [[UIColor blackColor] colorWithAlphaComponent:kSliderThemerLightAlpha];
  UIColor *lightDisabledColor =
      [[UIColor blackColor] colorWithAlphaComponent:kSliderThemerLightAlpha];

  MDCBasicColorScheme *lightScheme =
      [[MDCBasicColorScheme alloc] initWithPrimaryColor:MDCPalette.bluePalette.tint500
                                      primaryLightColor:lightTrackOffColor
                                       primaryDarkColor:lightDisabledColor];
  return lightScheme;
}

+ (MDCBasicColorScheme *)defaultSliderDarkColorScheme {
  UIColor *darkTrackOffColor =
      [[UIColor whiteColor] colorWithAlphaComponent:kSliderThemerDarkAlpha];
  UIColor *darkDisabledColor =
      [[UIColor whiteColor] colorWithAlphaComponent:kSliderThemerDarkAlpha];

  MDCBasicColorScheme *darkScheme =
      [[MDCBasicColorScheme alloc] initWithPrimaryColor:MDCPalette.bluePalette.tint500
                                      primaryLightColor:darkTrackOffColor
                                       primaryDarkColor:darkDisabledColor];
  return darkScheme;
}

@end


text:
import importlib
import os

from oslo_config import cfg
from oslo_log import log as logging
from six.moves import configparser as ConfigParser

LOG = logging.getLogger(__name__)

class NeutronModules(object):

    MODULES = {
        'neutron_fwaas': {
            'alembic-name': 'fwaas',
        },
        'neutron_lbaas': {
            'alembic-name': 'lbaas',
        },
        'neutron_vpnaas': {
            'alembic-name': 'vpnaas',
        },
    }

    def __init__(self):
        self.repos = {}
        for repo in self.MODULES:
            self.repos[repo] = {}
            self.repos[repo]['mod'] = self._import_or_none(repo)
            self.repos[repo]['ini'] = None

    def _import_or_none(self, module):
            try:
                return importlib.import_module(module)
            except ImportError:
                return None

    def installed_list(self):
        z = filter(lambda k: self.repos[k]['mod'] is not None, self.repos)
        LOG.debug("NeutronModules related repos installed = %s", z)
        return z

    def module(self, module):
        return self.repos[module]['mod']

    def alembic_name(self, module):
        return self.MODULES[module]['alembic-name']

    # Return an INI parser for the child module. oslo.config is a bit too
    # magical in its INI loading, and in one notable case, we need to merge
    # together the [service_providers] section across at least four
    # repositories.
    def ini(self, module):
        if self.repos[module]['ini'] is None:
            neutron_dir = None
            try:
                neutron_dir = cfg.CONF.config_dir
            except cfg.NoSuchOptError:
                pass

            if neutron_dir is None:
                neutron_dir = '/etc/neutron'

            ini = ConfigParser.SafeConfigParser()
            ini_path = os.path.join(neutron_dir, '%s.conf' % module)
            if os.path.exists(ini_path):
                ini.read(ini_path)

            self.repos[module]['ini'] = ini

        return self.repos[module]['ini']

    def service_providers(self, module):
        ini = self.ini(module)

        sp = []
        try:
            for name, value in ini.items('service_providers'):
                if name == 'service_provider':
                    sp.append(value)
        except ConfigParser.NoSectionError:
            pass

        return sp


text:
package com.communote.server.web.fe.portal.user.validator;

import org.apache.commons.lang.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.communote.common.validation.EmailValidator;
import com.communote.server.web.fe.portal.user.forms.ForgottenPWForm;

/**
 * Validator for the forgotten password use case.
 *
 * @author Communote GmbH - http://www.communote.com/
 */
public class ForgottenPWValidator implements Validator {

    /**
     * {@inheritDoc}
     *
     * @see org.springframework.validation.Validator#supports(Class)
     */
    @Override
    public boolean supports(Class clazz) {
        return ForgottenPWForm.class.equals(clazz);
    }

    /**
     * {@inheritDoc}
     *
     * @see org.springframework.validation.Validator#validate(Object,
     *      org.springframework.validation.Errors)
     */
    @Override
    public void validate(Object target, Errors errors) {
        ForgottenPWForm form = (ForgottenPWForm) target;
        if (StringUtils.equals(ForgottenPWForm.SEND_PW_LINK, form.getAction())) {
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "error.valueEmpty");
            if (!errors.hasFieldErrors("email")
                    && !EmailValidator.validateEmailAddressByRegex(form.getEmail())) {
                errors.rejectValue("email", "error.email.not.valid",
                        "The entered email address is not valid!");
            }
        } else if (StringUtils.equals(ForgottenPWForm.CONFIRM_NEW_PASSWORD, form.getAction())) {
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "error.valueEmpty");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password2", "error.valueEmpty");
            if (!errors.hasErrors() && !StringUtils.equals(form.getPassword(), form.getPassword2())) {
                errors.rejectValue("password", "user.forgotten.password.changing.error",
                        "Password changing error");
                form.setPassword("");
                form.setPassword2("");
            }
            // TODO see RegisterUserValidator
            if (!errors.hasFieldErrors("password") && form.getPassword().length() < 6) {
                errors.rejectValue("password", "error.password.must.have.at.least.6.characters",
                        "The password is too short!");
                form.setPassword("");
                form.setPassword2("");
            }
        }

    }

}


text:
{% assign logic_date_format = "%Y-%m-%d" %}

{% assign first_date = event.time | first %}
{% assign first_date_dtstart = first_date.dtstart | date: logic_date_format %}
{% assign first_date_dtend = first_date.dtend | date: logic_date_format %}
{% assign event_date_start = first_date_dtstart %}

{% assign last_date = event.time | last %}
{% assign last_date_dtstart = last_date.dtstart | date: logic_date_format %}
{% assign last_date_dtend = last_date.dtend | date: logic_date_format %}
{% if last_date_dtend %}
    {% assign event_date_end = last_date_dtend %}
{% else %}
    {% assign event_date_end = last_date_dtstart %}
{% endif %}

{% assign date_format = "%b %-d" %}
{% assign date_format_truncated = "%-d" %}

{% if event_date_start != event_date_end %}
    {% assign event_date_start_month_string = event_date_start | date: "%b" %}
    {% assign event_date_end_month_string = event_date_end | date: "%b" %}
    {% if event_date_start_month_string != event_date_end_month_string %}
        {% capture event_date_text %}
            {{ event_date_start | date: date_format }} - {{ event_date_end | date: date_format }}
        {% endcapture %}
    {% else %}
        {% capture event_date_text %}
            {{ event_date_start | date: date_format }}-{{ event_date_end | date: date_format_truncated }}
        {% endcapture %}
    {% endif %}
{% else %}
    {% capture event_date_text %}
        {{ event_date_start | date: date_format }}
    {% endcapture %}
{% endif %}

{{ event_date_text }}


text:
"""
External mechanism for computing feature distinctiveness

DEPRICATE

stores some set of vectors which lose their association with
their parent.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import utool as ut
import numpy as np
from six.moves import map
import six  # NOQA
from ibeis import constants as const
from ibeis.init import sysres
from ibeis.algo.hots import hstypes
print, rrr, profile = ut.inject2(__name__)

DCVS_DEFAULT = ut.ParamInfoList('distinctivness', [
    ut.ParamInfo('dcvs_power', 1.0, 'p',    varyvals=[.5, 1.0, 1.5, 2.0]),
    ut.ParamInfo('dcvs_min_clip', .2, 'mn', varyvals=[.2, .02, .03][0:1]),
    ut.ParamInfo('dcvs_max_clip', .5, 'mx', varyvals=[.05, .3, .4, .45, .5, 1.0][1:4]),
    ut.ParamInfo('dcvs_K', 5, 'dcvsK',      varyvals=[5, 7, 15][0:1]),
])

DISTINCTIVENESS_NORMALIZER_CACHE = {}
BASELINE_DISTINCTIVNESS_URLS = {
    # TODO: Populate
    'zebra_grevys': const.ZIPPED_URLS.GZ_DISTINCTIVE,
    'zebra_plains': const.ZIPPED_URLS.PZ_DISTINCTIVE,
}
PUBLISH_DIR = ut.unixpath('~/Dropbox/IBEIS')

def testdata_distinctiveness():
    """
    Example:
        >>> # SLOW_DOCTEST
        >>> from ibeis.algo.hots.distinctiveness_normalizer import *  # NOQA
        >>> dstcnvs_normer, qreq_ = testdata_distinctiveness()
    """
    import ibeis
    # build test data
    db = ut.get_argval('--db', str, 'testdb1')
    species = ut.get_argval('--species', str, None)
    aid = ut.get_argval('--aid', int, None)
    ibs = ibeis.opendb(db)
    if aid is not None:
        species = ibs.get_annot_species_texts(aid)
    if species is None:
        if db == 'testdb1':
            species = ibeis.const.TEST_SPECIES.ZEB_PLAIN
    daids = ibs.get_valid_aids(species=species)
    qaids = [aid] if aid is not None else daids
    qreq_ = ibs.new_query_request(qaids, daids)
    dstcnvs_normer = request_ibeis_distinctiveness_normalizer(qreq_)
    return dstcnvs_normer, qreq_

#@six.add_metaclass(ut.ReloadingMetaclass)
class DistinctivnessNormalizer(ut.Cachable):
    ext    = '.cPkl'
    prefix = 'distinctivness'

    def __init__(dstcnvs_normer, species, cachedir=None):
        """ cfgstring should be the species trained on """
        dstcnvs_normer.vecs = None
        dstcnvs_normer.max_distance = hstypes.VEC_PSEUDO_MAX_DISTANCE
        dstcnvs_normer.max_distance_sqrd = dstcnvs_normer.max_distance ** 2
        dstcnvs_normer.cachedir = cachedir
        dstcnvs_normer.species = species
        dstcnvs_normer.flann_params = {
            'algorithm': 'kdtree',
            'trees': 8,
            'checks': 800}
        dstcnvs_normer.checks = dstcnvs_normer.flann_params.get('checks')
        dstcnvs_normer.cores  = dstcnvs_normer.flann_params.get('cores', 0)

    def get_prefix(dstcnvs_normer):
        return DistinctivnessNormalizer.prefix + '_'

    def get_cfgstr(dstcnvs_normer):
        assert dstcnvs_normer.species is not None
        cfgstr = dstcnvs_normer.species
        return cfgstr

    def add_support(dstcnvs_normer, new_vecs):
        """
        """
        raise NotImplementedError()
        pass

    def archive(dstcnvs_normer, cachedir=None, overwrite=False):
        cachedir      = dstcnvs_normer.cachedir if cachedir is None else cachedir
        data_fpath    = dstcnvs_normer.get_fpath(cachedir)
        #flann_fpath   = dstcnvs_normer.get_flann_fpath(cachedir)
        archive_fpath = dstcnvs_normer.get_fpath(cachedir, ext='.zip')
        fpath_list = [
            data_fpath,
            #flann_fpath
        ]
        ut.archive_files(archive_fpath, fpath_list, overwrite=overwrite)
        return archive_fpath

    def publish(dstcnvs_normer, cachedir=None):
        """
        Sets this as the default normalizer available for download
        ONLY DEVELOPERS CAN PERFORM THIS OPERATION

        Args:
            cachedir (str):

        CommandLine:
            python -m ibeis.algo.hots.distinctiveness_normalizer --test-publish

        Example:
            >>> # DISABLE_DOCTEST
            >>> from ibeis.algo.hots.distinctiveness_normalizer import *  # NOQA
            >>> dstcnvs_normer = testdata_distinctiveness()[0]
            >>> dstcnvs_normer.rebuild()
            >>> dstcnvs_normer.save()
            >>> result = dstcnvs_normer.publish(cachedir)
            >>> # verify results
            >>> print(result)
        """
        from os.path import basename, join
        assert ut.is_developer(), 'ONLY DEVELOPERS CAN PERFORM THIS OPERATION'
        cachedir      = dstcnvs_normer.cachedir if cachedir is None else cachedir
        archive_fpath = dstcnvs_normer.archive(cachedir, overwrite=True)
        archive_fname = basename(archive_fpath)
        publish_dpath = PUBLISH_DIR
        publish_fpath = join(publish_dpath, archive_fname)
        if ut.checkpath(publish_fpath, verbose=True):
            print('Overwriting model')
            print('old nBytes(publish_fpath) = %s' %
                  (ut.get_file_nBytes_str(publish_fpath),))
            print('new nBytes(archive_fpath) = %s' %
                  (ut.get_file_nBytes_str(archive_fpath),))
        else:
            print('Publishing model')
        print('publish_fpath = %r' % (publish_fpath,))
        ut.copy(archive_fpath, publish_fpath)

    def get_flann_fpath(dstcnvs_normer, cachedir):
        flann_fpath = dstcnvs_normer.get_fpath(cachedir, ext='.flann')
        return flann_fpath

    def exists(dstcnvs_normer, cachedir=None, verbose=True, need_flann=False,
               *args, **kwargs):
        r"""
        Args:
            cachedir (str): cache directory
            verbose (bool):  verbosity flag

        Returns:
            flag: load_success

        CommandLine:
            python -m ibeis.algo.hots.distinctiveness_normalizer --test-exists

        Example:
            >>> # SLOW_DOCTEST
            >>> from ibeis.algo.hots.distinctiveness_normalizer import *  # NOQA
            >>> # build test data
            >>> dstcnvs_normer = testdata_distinctiveness()[0]
            >>> assert dstcnvs_normer.exists()
        """
        from os.path import exists
        cachedir = dstcnvs_normer.cachedir if cachedir is None else cachedir
        cpkl_fpath = dstcnvs_normer.get_fpath(cachedir)
        flann_fpath = dstcnvs_normer.get_flann_fpath(cachedir)
        fpath_list = [cpkl_fpath]
        if need_flann:
            fpath_list.append(flann_fpath)
        flag = all([exists(fpath) for fpath in fpath_list])
        return flag

    def load(dstcnvs_normer, cachedir=None, verbose=True, *args, **kwargs):
        # Inherited method
        cachedir = dstcnvs_normer.cachedir if cachedir is None else cachedir
        kwargs['ignore_keys'] = ['flann']
        super(DistinctivnessNormalizer, dstcnvs_normer).load(cachedir, *args,
                                                             **kwargs)
        dstcnvs_normer.load_or_build_flann(cachedir, verbose, *args, **kwargs)
        ## Load Flann
        #if ut.VERBOSE:
        #    print('[nnindex] load_success = %r' % (load_success,))

    def load_or_build_flann(dstcnvs_normer, cachedir=None, verbose=True, *args,
                            **kwargs):
        from vtool_ibeis._pyflann_backend import pyflann as pyflann
        flann_fpath = dstcnvs_normer.get_flann_fpath(cachedir)
        if ut.checkpath(flann_fpath, verbose=ut.VERBOSE):
            try:
                dstcnvs_normer.flann = pyflann.FLANN()
                dstcnvs_normer.flann.load_index(flann_fpath, dstcnvs_normer.vecs)
                assert dstcnvs_normer.flann._FLANN__curindex is not None
                #load_success = True
            except Exception as ex:
                ut.printex(ex, '... cannot load distinctiveness flann',
                           iswarning=True)
                dstcnvs_normer.rebuild(cachedir)
        else:
            dstcnvs_normer.ensure_flann(cachedir)
            #raise IOError('cannot load distinctiveness flann')
        #return load_success

    def save(dstcnvs_normer, cachedir=None, verbose=True, *args, **kwargs):
        """
        args = tuple()
        kwargs = {}
        """
        cachedir = dstcnvs_normer.cachedir if cachedir is None else cachedir
        # Inherited method
        kwargs['ignore_keys'] = ['flann']
        # Save everything but flann
        super(DistinctivnessNormalizer, dstcnvs_normer).save(cachedir, *args,
                                                             **kwargs)
        # Save flann
        if dstcnvs_normer.flann is not None:
            dstcnvs_normer.save_flann(cachedir, verbose=verbose)

    def save_flann(dstcnvs_normer, cachedir=None, verbose=True):
        cachedir = dstcnvs_normer.cachedir if cachedir is None else cachedir
        flann_fpath = dstcnvs_normer.get_flann_fpath(cachedir)
        if verbose:
            print('flann.save_index(%r)' % ut.path_ndir_split(flann_fpath, n=5))
        dstcnvs_normer.flann.save_index(flann_fpath)

    def init_support(dstcnvs_normer, vecs, verbose=True):
        dstcnvs_normer.vecs = vecs
        dstcnvs_normer.rebuild(verbose=verbose)

    def rebuild(dstcnvs_normer, verbose=True, quiet=False):
        # dstcnvs_normer.flann = vt.build_flann_index(
        #     dstcnvs_normer.vecs, dstcnvs_normer.flann_params, verbose=verbose)
        if dstcnvs_normer.vecs.dtype == hstypes.VEC_TYPE:
            dstcnvs_normer.max_distance = hstypes.VEC_PSEUDO_MAX_DISTANCE
            dstcnvs_normer.max_distance_sqrd = dstcnvs_normer.max_distance ** 2

    def ensure_flann(dstcnvs_normer, cachedir=None):
        if not ut.checkpath(dstcnvs_normer.get_flann_fpath(cachedir)):
            dstcnvs_normer.rebuild(cachedir)
            dstcnvs_normer.save_flann(cachedir)

    def get_distinctiveness(dstcnvs_normer, qfx2_vec, dcvs_K=2, dcvs_power=1.0,
                            dcvs_max_clip=1.0, dcvs_min_clip=0.0):
        r"""
        Args:
            qfx2_vec (ndarray):  mapping from query feature index to vec

        CommandLine:
            python -m ibeis.algo.hots.distinctiveness_normalizer --test-get_distinctiveness --show
            python -m ibeis.algo.hots.distinctiveness_normalizer --test-get_distinctiveness --db GZ_ALL --show
            python -m ibeis.algo.hots.distinctiveness_normalizer --test-get_distinctiveness --show --dcvs_power .25
            python -m ibeis.algo.hots.distinctiveness_normalizer --test-get_distinctiveness --show --dcvs_power .5
            python -m ibeis.algo.hots.distinctiveness_normalizer --test-get_distinctiveness --show --dcvs_power .1
            python -m ibeis.algo.hots.distinctiveness_normalizer --test-get_distinctiveness --show --dcvs_K 1&
            python -m ibeis.algo.hots.distinctiveness_normalizer --test-get_distinctiveness --show --dcvs_K 2&
            python -m ibeis.algo.hots.distinctiveness_normalizer --test-get_distinctiveness --show --dcvs_K 3&

        Example:
            >>> # SLOW_DOCTEST
            >>> from ibeis.algo.hots.distinctiveness_normalizer import *  # NOQA
            >>> dstcnvs_normer, qreq_ = testdata_distinctiveness()
            >>> qaid = qreq_.qaids[0]
            >>> qfx2_vec = qreq_.ibs.get_annot_vecs(qaid, config2_=qreq_.qparams)
            >>> default_dict = {'dcvs_power': .25, 'dcvs_K': 5, 'dcvs_max_clip': .5}
            >>> kwargs = ut.argparse_dict(default_dict)
            >>> qfx2_dstncvs = dstcnvs_normer.get_distinctiveness(qfx2_vec, **kwargs)
            >>> ut.assert_eq(len(qfx2_dstncvs.shape), 1)
            >>> assert np.all(qfx2_dstncvs) <= 1
            >>> assert np.all(qfx2_dstncvs) >= 0
            >>> ut.quit_if_noshow()
            >>> # Show distinctivness on an animal and a corresponding graph
            >>> import plottool_ibeis as pt
            >>> chip = qreq_.ibs.get_annot_chips(qaid)
            >>> qfx2_kpts = qreq_.ibs.get_annot_kpts(qaid, config2_=qreq_.qparams)
            >>> show_chip_distinctiveness_plot(chip, qfx2_kpts, qfx2_dstncvs)
            >>> #pt.figure(2)
            >>> #pt.show_all_colormaps()
            >>> pt.show_if_requested()

        Ignore:
            %s/\(^ *\)\(.*\)/\1>>> \2/c

        """
        #ut.embed()
        assert dcvs_K > 0 and dcvs_K < len(dstcnvs_normer.vecs), (
            'dcvs_K=%r' % (dcvs_K,))
        if len(qfx2_vec) == 0:
            #(qfx2_idx, qfx2_dist_sqrd) = dstcnvs_normer.empty_neighbors(0, dcvs_K)
            qfx2_idx  = np.empty((0, dcvs_K), dtype=np.int32)
            qfx2_dist = np.empty((0, dcvs_K), dtype=np.float64)
        else:
            # perform nearest neighbors
            (qfx2_idx, qfx2_dist_sqrd) = dstcnvs_normer.flann.nn_index(
                qfx2_vec, dcvs_K, checks=dstcnvs_normer.checks,
                cores=dstcnvs_normer.cores)
            # Ensure that distance returned are between 0 and 1
            #qfx2_dist = qfx2_dist / (dstcnvs_normer.max_distance ** 2)
            qfx2_dist = (np.sqrt(qfx2_dist_sqrd.astype(np.float64)) /
                         hstypes.VEC_PSEUDO_MAX_DISTANCE)
            #qfx2_dist32 = np.sqrt(np.divide(qfx2_dist_sqrd, dstcnvs_normer.max_distance_sqrd))
            #qfx2_dist =
            #qfx2_dist = np.sqrt(qfx2_dist) / dstcnvs_normer.max_distance
        if dcvs_K == 1:
            qfx2_dist = qfx2_dist[:, None]
        norm_dist = qfx2_dist.T[dcvs_K - 1].T
        qfx2_dstncvs = compute_distinctiveness_from_dist(norm_dist, dcvs_power,
                                                         dcvs_max_clip,
                                                         dcvs_min_clip)
        return qfx2_dstncvs

def compute_distinctiveness_from_dist(norm_dist, dcvs_power, dcvs_max_clip, dcvs_min_clip):
    """
    Compute distinctiveness from distance to dcvs_K+1 nearest neighbor

    Ignore:
        norm_dist = np.random.rand(1000)

        import numexpr

        %timeit np.divide(norm_dist, dcvs_max_clip)
        %timeit numexpr.evaluate('norm_dist / dcvs_max_clip', local_dict=dict(norm_dist=norm_dist, dcvs_max_clip=dcvs_max_clip))
        wd_cliped = np.divide(norm_dist, dcvs_max_clip)

        %timeit numexpr.evaluate('wd_cliped > 1.0', local_dict=locals())
        %timeit np.greater(wd_cliped, 1.0)

        %timeit np.power(wd_cliped, dcvs_power)
        %timeit numexpr.evaluate('wd_cliped ** dcvs_power', local_dict=locals())

        %timeit
    """
    # expondent to augment distinctiveness scores.
    # clip the distinctiveness at this fraction
    clip_range = dcvs_max_clip - dcvs_min_clip
    # apply distinctivness normalization
    _tmp = np.clip(norm_dist, dcvs_min_clip, dcvs_max_clip)
    np.subtract(_tmp, dcvs_min_clip, out=_tmp)
    np.divide(_tmp, clip_range, out=_tmp)
    np.power(_tmp, dcvs_power, out=_tmp)
    dstncvs = _tmp
    return dstncvs

def show_chip_distinctiveness_plot(chip, kpts, dstncvs, fnum=1, pnum=None):
    import plottool_ibeis as pt
    pt.figure(fnum, pnum=pnum)
    ax = pt.gca()
    divider = pt.ensure_divider(ax)
    #ax1 = divider.append_axes("left", size="50%", pad=0)
    ax1 = ax
    ax2 = divider.append_axes("bottom", size="100%", pad=0.05)
    #f, (ax1, ax2) = pt.plt.subplots(1, 2, sharex=True)
    cmapstr = 'rainbow'  # 'hot'
    color_list = pt.df2.plt.get_cmap(cmapstr)(ut.norm_zero_one(dstncvs))
    sortx = dstncvs.argsort()
    #pt.df2.plt.plot(qfx2_dstncvs[sortx], c=color_list[sortx])
    pt.plt.sca(ax1)
    pt.colorline(np.arange(len(sortx)), dstncvs[sortx],
                 cmap=pt.plt.get_cmap(cmapstr))
    pt.gca().set_xlim(0, len(sortx))
    pt.dark_background()
    pt.plt.sca(ax2)
    pt.imshow(chip, darken=.2)
    # MATPLOTLIB BUG CANNOT SHOW DIFFERENT ALPHA FOR POINTS AND KEYPOINTS AT ONCE
    #pt.draw_kpts2(kpts, pts_color=color_list, ell_color=color_list, ell_alpha=.1, ell=True, pts=True)
    #pt.draw_kpts2(kpts, color_list=color_list, pts_alpha=1.0, pts_size=1.5,
    #              ell=True, ell_alpha=.1, pts=False)
    ell = ut.get_argflag('--ell')
    pt.draw_kpts2(kpts, color_list=color_list, pts_alpha=1.0, pts_size=1.5,
                  ell=ell, ell_alpha=.3, pts=not ell)
    pt.plt.sca(ax)
    #pt.figure(fnum, pnum=pnum)

def download_baseline_distinctiveness_normalizer(cachedir, species):
    zipped_url = BASELINE_DISTINCTIVNESS_URLS[species]
    ut.grab_zipped_url(zipped_url, ensure=True, download_dir=cachedir)
    #ut.assert_eq(ut.unixpath(cachedir), dir_)

def request_ibeis_distinctiveness_normalizer(qreq_, verbose=True):
    r"""
    Args:
        qreq_ (QueryRequest):  query request object with hyper-parameters

    CommandLine:
        python -m ibeis.algo.hots.distinctiveness_normalizer --test-request_ibeis_distinctiveness_normalizer

    Example:
        >>> # SLOW_DOCTEST
        >>> from ibeis.algo.hots.distinctiveness_normalizer import *  # NOQA
        >>> import ibeis
        >>> # build test data
        >>> ibs = ibeis.opendb('testdb1')
        >>> daids = ibs.get_valid_aids(species=ibeis.const.TEST_SPECIES.ZEB_PLAIN)
        >>> qaids = ibs.get_valid_aids(species=ibeis.const.TEST_SPECIES.ZEB_PLAIN)
        >>> qreq_ = ibs.new_query_request(qaids, daids)
        >>> # execute function
        >>> dstcnvs_normer = request_ibeis_distinctiveness_normalizer(qreq_)
        >>> # verify results
        >>> assert dstcnvs_normer is not None
    """
    global DISTINCTIVENESS_NORMALIZER_CACHE
    unique_species = qreq_.get_unique_species()
    assert len(unique_species) == 1
    species = unique_species[0]
    global_distinctdir = qreq_.ibs.get_global_distinctiveness_modeldir()
    cachedir = global_distinctdir
    dstcnvs_normer = request_species_distinctiveness_normalizer(species,
                                                                cachedir,
                                                                verbose=False)
    return dstcnvs_normer

def request_species_distinctiveness_normalizer(species, cachedir=None, verbose=False):
    """
    helper function to get distinctivness model independent of IBEIS.
    """
    if species in DISTINCTIVENESS_NORMALIZER_CACHE:
        dstcnvs_normer = DISTINCTIVENESS_NORMALIZER_CACHE[species]
    else:
        if cachedir is None:
            cachedir = sysres.get_global_distinctiveness_modeldir(ensure=True)
        dstcnvs_normer = DistinctivnessNormalizer(species, cachedir=cachedir)
        if not dstcnvs_normer.exists(cachedir):
            # download normalizer if it doesn't exist
            download_baseline_distinctiveness_normalizer(cachedir, species)
        dstcnvs_normer.load(cachedir)
        print(ut.get_object_size_str(dstcnvs_normer, 'dstcnvs_normer = '))
        print('Loaded distinctivness normalizer')
        #dstcnvs_normer.ensure_flann(cachedir)
        assert dstcnvs_normer.exists(cachedir, need_flann=True), (
            'normalizer should have been downloaded, but it doesnt exist')
        DISTINCTIVENESS_NORMALIZER_CACHE[species] = dstcnvs_normer
    return dstcnvs_normer

def clear_distinctivness_cache(j):
    global_distinctdir = sysres.get_global_distinctiveness_modeldir()
    ut.remove_files_in_dir(global_distinctdir)

def list_distinctivness_cache():
    global_distinctdir = sysres.get_global_distinctiveness_modeldir()
    print(ut.repr2(ut.ls(global_distinctdir)))

def list_published_distinctivness():
    r"""
    CommandLine:
        python -m ibeis.algo.hots.distinctiveness_normalizer --test-list_published_distinctivness

    Example:
        >>> # SLOW_DOCTEST
        >>> from ibeis.algo.hots.distinctiveness_normalizer import *  # NOQA
        >>> published_fpaths = list_published_distinctivness()
        >>> print(ut.repr2(published_fpaths))
    """
    published_fpaths = ut.ls(PUBLISH_DIR)
    return published_fpaths

def view_distinctiveness_model_dir():
    r"""
    CommandLine:
        python -m ibeis.algo.hots.distinctiveness_normalizer --test-view_distinctiveness_model_dir

    Example:
        >>> # DISABLE_DOCTEST
        >>> from ibeis.algo.hots.distinctiveness_normalizer import *  # NOQA
        >>> view_distinctiveness_model_dir()
    """
    global_distinctdir = sysres.get_global_distinctiveness_modeldir()
    ut.vd(global_distinctdir)

def view_publish_dir():
    r"""
    CommandLine:
        python -m ibeis.algo.hots.distinctiveness_normalizer --test-view_publish_dir

    Example:
        >>> # DISABLE_DOCTEST
        >>> from ibeis.algo.hots.distinctiveness_normalizer import *  # NOQA
        >>> view_publish_dir()
    """
    ut.vd(PUBLISH_DIR)

def tst_single_annot_distinctiveness_params(ibs, aid):
    r"""

    CommandLine:
        python -m ibeis.algo.hots.distinctiveness_normalizer --test-test_single_annot_distinctiveness_params --show
        python -m ibeis.algo.hots.distinctiveness_normalizer --test-test_single_annot_distinctiveness_params --show --db GZ_ALL

    Example:
        >>> # DISABLE_DOCTEST
        >>> from ibeis.algo.hots.distinctiveness_normalizer import *  # NOQA
        >>> import plottool_ibeis as pt
        >>> import ibeis
        >>> # build test data
        >>> ibs = ibeis.opendb(ut.get_argval('--db', type_=str, default='PZ_MTEST'))
        >>> aid = ut.get_argval('--aid', type_=int, default=1)
        >>> # execute function
        >>> test_single_annot_distinctiveness_params(ibs, aid)
        >>> pt.show_if_requested()
    """
    ####
    # TODO: Also paramatarize the downweighting based on the keypoint size
    ####
    # HACK IN ABILITY TO SET CONFIG
    from ibeis.init.main_commands import postload_commands
    from ibeis.algo import Config
    postload_commands(ibs, None)

    import plottool_ibeis as pt

    #cfglbl_list = cfgdict_list
    #ut.all_dict_combinations_lbls(varied_dict)

    # Get info to find distinctivness of
    species_text = ibs.get_annot_species(aid)
    # FIXME; qreq_ params for config rowid
    vecs = ibs.get_annot_vecs(aid)
    kpts = ibs.get_annot_kpts(aid)
    chip = ibs.get_annot_chips(aid)

    # Paramater space to search
    # TODO: use slicing to control the params being varied
    # Use GridSearch class to modify paramaters as you go.

    varied_dict = Config.DCVS_DEFAULT.get_varydict()

    print('Varied Dict: ')
    print(ut.repr2(varied_dict))

    cfgdict_list, cfglbl_list = ut.make_constrained_cfg_and_lbl_list(varied_dict)

    # Get groundtruthish distinctivness map
    # for objective function
    # Load distinctivness normalizer
    with ut.Timer('Loading Distinctivness Normalizer for %s' % (species_text)):
        dstcvnss_normer = request_species_distinctiveness_normalizer(species_text)

    # Get distinctivness over all params
    dstncvs_list = [dstcvnss_normer.get_distinctiveness(vecs, **cfgdict)
                    for cfgdict in ut.ProgIter(cfgdict_list, lbl='get dstcvns')]

    #fgweights = ibs.get_annot_fgweights([aid])[0]
    #dstncvs_list = [x * fgweights for x in dstncvs_list]
    fnum = 1

    import functools
    show_func = functools.partial(show_chip_distinctiveness_plot, chip, kpts)

    ut.interact_gridsearch_result_images(
        show_func, cfgdict_list, cfglbl_list, dstncvs_list,
        score_list=None, fnum=fnum, figtitle='dstncvs gridsearch')

    pt.present()

def dev_train_distinctiveness(species=None):
    r"""
    Args:
        ibs (IBEISController):  ibeis controller object
        species (None):

    CommandLine:
        python -m ibeis.algo.hots.distinctiveness_normalizer --test-dev_train_distinctiveness

        alias dev_train_distinctiveness='python -m ibeis.algo.hots.distinctiveness_normalizer --test-dev_train_distinctiveness'
        # Publishing (uses cached normalizers if available)
        dev_train_distinctiveness --species GZ --publish
        dev_train_distinctiveness --species PZ --publish
        dev_train_distinctiveness --species PZ --retrain

    Example:
        >>> # DISABLE_DOCTEST
        >>> from ibeis.algo.hots.distinctiveness_normalizer import *  # NOQA
        >>> import ibeis
        >>> species = ut.get_argval('--species', str, 'zebra_grevys')
        >>> dev_train_distinctiveness(species)
    """
    import ibeis
    #if 'species' not in vars() or species is None:
    #    species = 'zebra_grevys'
    if species == 'zebra_grevys':
        dbname = 'GZ_ALL'
    elif species == 'zebra_plains':
        dbname = 'PZ_Master0'
    ibs = ibeis.opendb(dbname)
    global_distinctdir = ibs.get_global_distinctiveness_modeldir()
    cachedir = global_distinctdir
    dstcnvs_normer = DistinctivnessNormalizer(species, cachedir=cachedir)
    try:
        if ut.get_argflag('--retrain'):
            raise IOError('force cache miss')
        with ut.Timer('loading distinctiveness'):
            dstcnvs_normer.load(cachedir)
        # Cache hit
        print('distinctivness model cache hit')
    except IOError:
        print('distinctivness model cache miss')
        with ut.Timer('training distinctiveness'):
            # Need to train
            # Add one example from each name
            # TODO: add one exemplar per viewpoint for each name
            #max_vecs = 1E6
            #max_annots = 975
            max_annots = 975
            #ibs.fix_and_clean_database()
            nid_list = ibs.get_valid_nids()
            aids_list = ibs.get_name_aids(nid_list)
            # remove junk
            aids_list = ibs.unflat_map(ibs.filter_junk_annotations, aids_list)
            # remove empty
            aids_list = [aids for aids in aids_list if len(aids) > 0]
            num_annots_list = list(map(len, aids_list))
            aids_list = ut.sortedby(aids_list, num_annots_list, reverse=True)
            # take only one annot per name
            aid_list = ut.get_list_column(aids_list, 0)
            # Keep only a certain number of annots for distinctiveness mapping
            aid_list_ = ut.listclip(aid_list, max_annots)
            print('total num named annots = %r' % (sum(num_annots_list)))
            print('training distinctiveness using %d/%d singleton annots' %
                  (len(aid_list_), len(aid_list)))
            # vec
            # FIXME: qreq_ params for config rowid
            vecs_list = ibs.get_annot_vecs(aid_list_)
            num_vecs = sum(list(map(len, vecs_list)))
            print('num_vecs = %r' % (num_vecs,))
            vecs = np.vstack(vecs_list)
            print('vecs size = %r' % (ut.get_object_size_str(vecs),))
            dstcnvs_normer.init_support(vecs)
            dstcnvs_normer.save(global_distinctdir)

    if ut.get_argflag('--publish'):
        dstcnvs_normer.publish()
    #vsone_
    #inct

if __name__ == '__main__':
    """
    CommandLine:
        python -m ibeis.algo.hots.distinctiveness_normalizer
        python -m ibeis.algo.hots.distinctiveness_normalizer --allexamples
        python -m ibeis.algo.hots.distinctiveness_normalizer --allexamples --noface --nosrc
    """
    import multiprocessing
    multiprocessing.freeze_support()  # for win32
    import utool as ut  # NOQA
    ut.doctest_funcs()