text:
package com.github.gagu.web.util;

import com.github.gagu.core.util.Assert;
import com.github.gagu.core.util.LinkedMultiValueMap;
import com.github.gagu.core.util.MultiValueMap;
import com.github.gagu.core.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Enumeration;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;

/**
 * Miscellaneous utilities for web applications.
 * Used by various framework classes.
 *
 * Author: yong.han
 * Date: 14-7-21
 * Time: 下午10:58
 *
 * @author hanyosh
 */
public abstract class WebUtils {
	/**
	 * Standard Servlet 2.3+ spec request attributes for include URI and paths.
	 *
If included via a RequestDispatcher, the current resource will see the
	 * originating request. Its own URI and paths are exposed as request attributes.
	 */
	public static final String INCLUDE_REQUEST_URI_ATTRIBUTE = "javax.servlet.include.request_uri";
	public static final String INCLUDE_CONTEXT_PATH_ATTRIBUTE = "javax.servlet.include.context_path";
	public static final String INCLUDE_SERVLET_PATH_ATTRIBUTE = "javax.servlet.include.servlet_path";
	public static final String INCLUDE_PATH_INFO_ATTRIBUTE = "javax.servlet.include.path_info";
	public static final String INCLUDE_QUERY_STRING_ATTRIBUTE = "javax.servlet.include.query_string";

	/**
	 * Standard Servlet 2.4+ spec request attributes for forward URI and paths.
	 *
If forwarded to via a RequestDispatcher, the current resource will see its
	 * own URI and paths. The originating URI and paths are exposed as request attributes.
	 */
	public static final String FORWARD_REQUEST_URI_ATTRIBUTE = "javax.servlet.forward.request_uri";
	public static final String FORWARD_CONTEXT_PATH_ATTRIBUTE = "javax.servlet.forward.context_path";
	public static final String FORWARD_SERVLET_PATH_ATTRIBUTE = "javax.servlet.forward.servlet_path";
	public static final String FORWARD_PATH_INFO_ATTRIBUTE = "javax.servlet.forward.path_info";
	public static final String FORWARD_QUERY_STRING_ATTRIBUTE = "javax.servlet.forward.query_string";

	/**
	 * Standard Servlet 2.3+ spec request attributes for error pages.
	 *
To be exposed to JSPs that are marked as error pages, when forwarding
	 * to them directly rather than through the servlet container's error page
	 * resolution mechanism.
	 */
	public static final String ERROR_STATUS_CODE_ATTRIBUTE = "javax.servlet.error.status_code";
	public static final String ERROR_EXCEPTION_TYPE_ATTRIBUTE = "javax.servlet.error.exception_type";
	public static final String ERROR_MESSAGE_ATTRIBUTE = "javax.servlet.error.message";
	public static final String ERROR_EXCEPTION_ATTRIBUTE = "javax.servlet.error.exception";
	public static final String ERROR_REQUEST_URI_ATTRIBUTE = "javax.servlet.error.request_uri";
	public static final String ERROR_SERVLET_NAME_ATTRIBUTE = "javax.servlet.error.servlet_name";

	/**
	 * Prefix of the charset clause in a content type String: ";charset="
	 */
	public static final String CONTENT_TYPE_CHARSET_PREFIX = ";charset=";

	/**
	 * Default character encoding to use when {@code request.getCharacterEncoding}
	 * returns {@code null}, according to the Servlet spec.
	 * @see ServletRequest#getCharacterEncoding
	 */
	public static final String DEFAULT_CHARACTER_ENCODING = "ISO-8859-1";

	/**
	 * Standard Servlet spec context attribute that specifies a temporary
	 * directory for the current web application, of type {@code java.io.File}.
	 */
	public static final String TEMP_DIR_CONTEXT_ATTRIBUTE = "javax.servlet.context.tempdir";

	/**
	 * HTML escape parameter at the servlet context level
	 * (i.e. a context-param in {@code web.xml}): "defaultHtmlEscape".
	 */
	public static final String HTML_ESCAPE_CONTEXT_PARAM = "defaultHtmlEscape";

	/**
	 * Web app root key parameter at the servlet context level
	 * (i.e. a context-param in {@code web.xml}): "webAppRootKey".
	 */
	public static final String WEB_APP_ROOT_KEY_PARAM = "webAppRootKey";

	/** Default web app root key: "webapp.root" */
	public static final String DEFAULT_WEB_APP_ROOT_KEY = "webapp.root";

	/** Name suffixes in case of image buttons */
	public static final String[] SUBMIT_IMAGE_SUFFIXES = {".x", ".y"};

	/** Key for the mutex session attribute */
	public static final String SESSION_MUTEX_ATTRIBUTE = WebUtils.class.getName() + ".MUTEX";

	/**
	 * Set a system property to the web application root directory.
	 * The key of the system property can be defined with the "webAppRootKey"
	 * context-param in {@code web.xml}. Default is "webapp.root".
	 *
Can be used for tools that support substition with {@code System.getProperty}
	 * values, like log4j's "${key}" syntax within log file locations.
	 * @param servletContext the servlet context of the web application
	 * @throws IllegalStateException if the system property is already set,
	 * or if the WAR file is not expanded
	 * @see #WEB_APP_ROOT_KEY_PARAM
	 * @see #DEFAULT_WEB_APP_ROOT_KEY
	 * @see WebAppRootListener
	 * @see Log4jWebConfigurer
	 */
	public static void setWebAppRootSystemProperty(ServletContext servletContext) throws IllegalStateException {
		Assert.notNull(servletContext, "ServletContext must not be null");
		String root = servletContext.getRealPath("/");
		if (root == null) {
			throw new IllegalStateException(
					"Cannot set web app root system property when WAR file is not expanded");
		}
		String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM);
		String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY);
		String oldValue = System.getProperty(key);
		if (oldValue != null && !StringUtils.pathEquals(oldValue, root)) {
			throw new IllegalStateException(
					"Web app root system property already set to different value: '" +
							key + "' = [" + oldValue + "] instead of [" + root + "] - " +
							"Choose unique values for the 'webAppRootKey' context-param in your web.xml files!");
		}
		System.setProperty(key, root);
		servletContext.log("Set web app root system property: '" + key + "' = [" + root + "]");
	}

	/**
	 * Remove the system property that points to the web app root directory.
	 * To be called on shutdown of the web application.
	 * @param servletContext the servlet context of the web application
	 * @see #setWebAppRootSystemProperty
	 */
	public static void removeWebAppRootSystemProperty(ServletContext servletContext) {
		Assert.notNull(servletContext, "ServletContext must not be null");
		String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM);
		String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY);
		System.getProperties().remove(key);
	}

	/**
	 * Return whether default HTML escaping is enabled for the web application,
	 * i.e. the value of the "defaultHtmlEscape" context-param in {@code web.xml}
	 * (if any). Falls back to {@code false} in case of no explicit default given.
	 * @param servletContext the servlet context of the web application
	 * @return whether default HTML escaping is enabled (default is false)
	 */
	public static boolean isDefaultHtmlEscape(ServletContext servletContext) {
		if (servletContext == null) {
			return false;
		}
		String param = servletContext.getInitParameter(HTML_ESCAPE_CONTEXT_PARAM);
		return Boolean.valueOf(param);
	}

	/**
	 * Return whether default HTML escaping is enabled for the web application,
	 * i.e. the value of the "defaultHtmlEscape" context-param in {@code web.xml}
	 * (if any).
	 *
This method differentiates between no param specified at all and
	 * an actual boolean value specified, allowing to have a context-specific
	 * default in case of no setting at the global level.
	 * @param servletContext the servlet context of the web application
	 * @return whether default HTML escaping is enabled (null = no explicit default)
	 */
	public static Boolean getDefaultHtmlEscape(ServletContext servletContext) {
		if (servletContext == null) {
			return null;
		}
		String param = servletContext.getInitParameter(HTML_ESCAPE_CONTEXT_PARAM);
		return (StringUtils.hasText(param)? Boolean.valueOf(param) : null);
	}

	/**
	 * Return the temporary directory for the current web application,
	 * as provided by the servlet container.
	 * @param servletContext the servlet context of the web application
	 * @return the File representing the temporary directory
	 */
	public static File getTempDir(ServletContext servletContext) {
		Assert.notNull(servletContext, "ServletContext must not be null");
		return (File) servletContext.getAttribute(TEMP_DIR_CONTEXT_ATTRIBUTE);
	}

	/**
	 * Return the real path of the given path within the web application,
	 * as provided by the servlet container.
	 *
Prepends a slash if the path does not already start with a slash,
	 * and throws a FileNotFoundException if the path cannot be resolved to
	 * a resource (in contrast to ServletContext's {@code getRealPath},
	 * which returns null).
	 * @param servletContext the servlet context of the web application
	 * @param path the path within the web application
	 * @return the corresponding real path
	 * @throws java.io.FileNotFoundException if the path cannot be resolved to a resource
	 * @see javax.servlet.ServletContext#getRealPath
	 */
	public static String getRealPath(ServletContext servletContext, String path) throws FileNotFoundException {
		Assert.notNull(servletContext, "ServletContext must not be null");
		// Interpret location as relative to the web application root directory.
		if (!path.startsWith("/")) {
			path = "/" + path;
		}
		String realPath = servletContext.getRealPath(path);
		if (realPath == null) {
			throw new FileNotFoundException(
					"ServletContext resource [" + path + "] cannot be resolved to absolute file path - " +
							"web application archive not expanded?");
		}
		return realPath;
	}

	/**
	 * Determine the session id of the given request, if any.
	 * @param request current HTTP request
	 * @return the session id, or {@code null} if none
	 */
	public static String getSessionId(HttpServletRequest request) {
		Assert.notNull(request, "Request must not be null");
		HttpSession session = request.getSession(false);
		return (session != null ? session.getId() : null);
	}

	/**
	 * Check the given request for a session attribute of the given name.
	 * Returns null if there is no session or if the session has no such attribute.
	 * Does not create a new session if none has existed before!
	 * @param request current HTTP request
	 * @param name the name of the session attribute
	 * @return the value of the session attribute, or {@code null} if not found
	 */
	public static Object getSessionAttribute(HttpServletRequest request, String name) {
		Assert.notNull(request, "Request must not be null");
		HttpSession session = request.getSession(false);
		return (session != null ? session.getAttribute(name) : null);
	}

	/**
	 * Check the given request for a session attribute of the given name.
	 * Throws an exception if there is no session or if the session has no such
	 * attribute. Does not create a new session if none has existed before!
	 * @param request current HTTP request
	 * @param name the name of the session attribute
	 * @return the value of the session attribute, or {@code null} if not found
	 * @throws IllegalStateException if the session attribute could not be found
	 */
	public static Object getRequiredSessionAttribute(HttpServletRequest request, String name)
			throws IllegalStateException {

		Object attr = getSessionAttribute(request, name);
		if (attr == null) {
			throw new IllegalStateException("No session attribute '" + name + "' found");
		}
		return attr;
	}

	/**
	 * Set the session attribute with the given name to the given value.
	 * Removes the session attribute if value is null, if a session existed at all.
	 * Does not create a new session if not necessary!
	 * @param request current HTTP request
	 * @param name the name of the session attribute
	 * @param value the value of the session attribute
	 */
	public static void setSessionAttribute(HttpServletRequest request, String name, Object value) {
		Assert.notNull(request, "Request must not be null");
		if (value != null) {
			request.getSession().setAttribute(name, value);
		}
		else {
			HttpSession session = request.getSession(false);
			if (session != null) {
				session.removeAttribute(name);
			}
		}
	}

	/**
	 * Get the specified session attribute, creating and setting a new attribute if
	 * no existing found. The given class needs to have a public no-arg constructor.
	 * Useful for on-demand state objects in a web tier, like shopping carts.
	 * @param session current HTTP session
	 * @param name the name of the session attribute
	 * @param clazz the class to instantiate for a new attribute
	 * @return the value of the session attribute, newly created if not found
	 * @throws IllegalArgumentException if the session attribute could not be instantiated
	 */
	public static Object getOrCreateSessionAttribute(HttpSession session, String name, Class<?> clazz)
			throws IllegalArgumentException {

		Assert.notNull(session, "Session must not be null");
		Object sessionObject = session.getAttribute(name);
		if (sessionObject == null) {
			try {
				sessionObject = clazz.newInstance();
			}
			catch (InstantiationException ex) {
				throw new IllegalArgumentException(
						"Could not instantiate class [" + clazz.getName() +
								"] for session attribute '" + name + "': " + ex.getMessage());
			}
			catch (IllegalAccessException ex) {
				throw new IllegalArgumentException(
						"Could not access default constructor of class [" + clazz.getName() +
								"] for session attribute '" + name + "': " + ex.getMessage());
			}
			session.setAttribute(name, sessionObject);
		}
		return sessionObject;
	}

	/**
	 * Return the best available mutex for the given session:
	 * that is, an object to synchronize on for the given session.
	 *
Returns the session mutex attribute if available; usually,
	 * this means that the HttpSessionMutexListener needs to be defined
	 * in {@code web.xml}. Falls back to the HttpSession itself
	 * if no mutex attribute found.
	 *
The session mutex is guaranteed to be the same object during
	 * the entire lifetime of the session, available under the key defined
	 * by the {@code SESSION_MUTEX_ATTRIBUTE} constant. It serves as a
	 * safe reference to synchronize on for locking on the current session.
	 *
In many cases, the HttpSession reference itself is a safe mutex
	 * as well, since it will always be the same object reference for the
	 * same active logical session. However, this is not guaranteed across
	 * different servlet containers; the only 100% safe way is a session mutex.
	 * @param session the HttpSession to find a mutex for
	 * @return the mutex object (never {@code null})
	 * @see #SESSION_MUTEX_ATTRIBUTE
	 * @see HttpSessionMutexListener
	 */
	public static Object getSessionMutex(HttpSession session) {
		Assert.notNull(session, "Session must not be null");
		Object mutex = session.getAttribute(SESSION_MUTEX_ATTRIBUTE);
		if (mutex == null) {
			mutex = session;
		}
		return mutex;
	}

	/**
	 * Return an appropriate request object of the specified type, if available,
	 * unwrapping the given request as far as necessary.
	 * @param request the servlet request to introspect
	 * @param requiredType the desired type of request object
	 * @return the matching request object, or {@code null} if none
	 * of that type is available
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getNativeRequest(ServletRequest request, Class<T> requiredType) {
		if (requiredType != null) {
			if (requiredType.isInstance(request)) {
				return (T) request;
			}
			else if (request instanceof ServletRequestWrapper) {
				return getNativeRequest(((ServletRequestWrapper) request).getRequest(), requiredType);
			}
		}
		return null;
	}

	/**
	 * Return an appropriate response object of the specified type, if available,
	 * unwrapping the given response as far as necessary.
	 * @param response the servlet response to introspect
	 * @param requiredType the desired type of response object
	 * @return the matching response object, or {@code null} if none
	 * of that type is available
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getNativeResponse(ServletResponse response, Class<T> requiredType) {
		if (requiredType != null) {
			if (requiredType.isInstance(response)) {
				return (T) response;
			}
			else if (response instanceof ServletResponseWrapper) {
				return getNativeResponse(((ServletResponseWrapper) response).getResponse(), requiredType);
			}
		}
		return null;
	}

	/**
	 * Determine whether the given request is an include request,
	 * that is, not a top-level HTTP request coming in from the outside.
	 *
Checks the presence of the "javax.servlet.include.request_uri"
	 * request attribute. Could check any request attribute that is only
	 * present in an include request.
	 * @param request current servlet request
	 * @return whether the given request is an include request
	 */
	public static boolean isIncludeRequest(ServletRequest request) {
		return (request.getAttribute(INCLUDE_REQUEST_URI_ATTRIBUTE) != null);
	}

	/**
	 * Expose the Servlet spec's error attributes as {@link javax.servlet.http.HttpServletRequest}
	 * attributes under the keys defined in the Servlet 2.3 specification, for error pages that
	 * are rendered directly rather than through the Servlet container's error page resolution:
	 * {@code javax.servlet.error.status_code},
	 * {@code javax.servlet.error.exception_type},
	 * {@code javax.servlet.error.message},
	 * {@code javax.servlet.error.exception},
	 * {@code javax.servlet.error.request_uri},
	 * {@code javax.servlet.error.servlet_name}.
	 *
Does not override values if already present, to respect attribute values
	 * that have been exposed explicitly before.
	 *
Exposes status code 200 by default. Set the "javax.servlet.error.status_code"
	 * attribute explicitly (before or after) in order to expose a different status code.
	 * @param request current servlet request
	 * @param ex the exception encountered
	 * @param servletName the name of the offending servlet
	 */
	public static void exposeErrorRequestAttributes(HttpServletRequest request, Throwable ex, String servletName) {
		exposeRequestAttributeIfNotPresent(request, ERROR_STATUS_CODE_ATTRIBUTE, HttpServletResponse.SC_OK);
		exposeRequestAttributeIfNotPresent(request, ERROR_EXCEPTION_TYPE_ATTRIBUTE, ex.getClass());
		exposeRequestAttributeIfNotPresent(request, ERROR_MESSAGE_ATTRIBUTE, ex.getMessage());
		exposeRequestAttributeIfNotPresent(request, ERROR_EXCEPTION_ATTRIBUTE, ex);
		exposeRequestAttributeIfNotPresent(request, ERROR_REQUEST_URI_ATTRIBUTE, request.getRequestURI());
		exposeRequestAttributeIfNotPresent(request, ERROR_SERVLET_NAME_ATTRIBUTE, servletName);
	}

	/**
	 * Expose the specified request attribute if not already present.
	 * @param request current servlet request
	 * @param name the name of the attribute
	 * @param value the suggested value of the attribute
	 */
	private static void exposeRequestAttributeIfNotPresent(ServletRequest request, String name, Object value) {
		if (request.getAttribute(name) == null) {
			request.setAttribute(name, value);
		}
	}

	/**
	 * Clear the Servlet spec's error attributes as {@link javax.servlet.http.HttpServletRequest}
	 * attributes under the keys defined in the Servlet 2.3 specification:
	 * {@code javax.servlet.error.status_code},
	 * {@code javax.servlet.error.exception_type},
	 * {@code javax.servlet.error.message},
	 * {@code javax.servlet.error.exception},
	 * {@code javax.servlet.error.request_uri},
	 * {@code javax.servlet.error.servlet_name}.
	 * @param request current servlet request
	 */
	public static void clearErrorRequestAttributes(HttpServletRequest request) {
		request.removeAttribute(ERROR_STATUS_CODE_ATTRIBUTE);
		request.removeAttribute(ERROR_EXCEPTION_TYPE_ATTRIBUTE);
		request.removeAttribute(ERROR_MESSAGE_ATTRIBUTE);
		request.removeAttribute(ERROR_EXCEPTION_ATTRIBUTE);
		request.removeAttribute(ERROR_REQUEST_URI_ATTRIBUTE);
		request.removeAttribute(ERROR_SERVLET_NAME_ATTRIBUTE);
	}

	/**
	 * Expose the given Map as request attributes, using the keys as attribute names
	 * and the values as corresponding attribute values. Keys need to be Strings.
	 * @param request current HTTP request
	 * @param attributes the attributes Map
	 */
	public static void exposeRequestAttributes(ServletRequest request, Map<String, ?> attributes) {
		Assert.notNull(request, "Request must not be null");
		Assert.notNull(attributes, "Attributes Map must not be null");
		for (Map.Entry<String, ?> entry : attributes.entrySet()) {
			request.setAttribute(entry.getKey(), entry.getValue());
		}
	}

	/**
	 * Retrieve the first cookie with the given name. Note that multiple
	 * cookies can have the same name but different paths or domains.
	 * @param request current servlet request
	 * @param name cookie name
	 * @return the first cookie with the given name, or {@code null} if none is found
	 */
	public static Cookie getCookie(HttpServletRequest request, String name) {
		Assert.notNull(request, "Request must not be null");
		Cookie cookies[] = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (name.equals(cookie.getName())) {
					return cookie;
				}
			}
		}
		return null;
	}

	/**
	 * Check if a specific input type="submit" parameter was sent in the request,
	 * either via a button (directly with name) or via an image (name + ".x" or
	 * name + ".y").
	 * @param request current HTTP request
	 * @param name name of the parameter
	 * @return if the parameter was sent
	 * @see #SUBMIT_IMAGE_SUFFIXES
	 */
	public static boolean hasSubmitParameter(ServletRequest request, String name) {
		Assert.notNull(request, "Request must not be null");
		if (request.getParameter(name) != null) {
			return true;
		}
		for (String suffix : SUBMIT_IMAGE_SUFFIXES) {
			if (request.getParameter(name + suffix) != null) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Obtain a named parameter from the given request parameters.
	 *
See {@link #findParameterValue(java.util.Map, String)}
	 * for a description of the lookup algorithm.
	 * @param request current HTTP request
	 * @param name the logical name of the request parameter
	 * @return the value of the parameter, or {@code null}
	 * if the parameter does not exist in given request
	 */
	public static String findParameterValue(ServletRequest request, String name) {
		return findParameterValue(request.getParameterMap(), name);
	}

	/**
	 * Obtain a named parameter from the given request parameters.
	 *
This method will try to obtain a parameter value using the
	 * following algorithm:
	 *

	 *
Try to get the parameter value using just the given logical name.
	 * This handles parameters of the form <tt>logicalName = value</tt>. For normal
	 * parameters, e.g. submitted using a hidden HTML form field, this will return
	 * the requested value.

	 *
Try to obtain the parameter value from the parameter name, where the
	 * parameter name in the request is of the form <tt>logicalName_value = xyz</tt>
	 * with "_" being the configured delimiter. This deals with parameter values
	 * submitted using an HTML form submit button.

	 *
If the value obtained in the previous step has a ".x" or ".y" suffix,
	 * remove that. This handles cases where the value was submitted using an
	 * HTML form image button. In this case the parameter in the request would
	 * actually be of the form <tt>logicalName_value.x = 123</tt>.

	 *

	 * @param parameters the available parameter map
	 * @param name the logical name of the request parameter
	 * @return the value of the parameter, or {@code null}
	 * if the parameter does not exist in given request
	 */
	public static String findParameterValue(Map<String, ?> parameters, String name) {
		// First try to get it as a normal name=value parameter
		Object value = parameters.get(name);
		if (value instanceof String[]) {
			String[] values = (String[]) value;
			return (values.length > 0 ? values[0] : null);
		}
		else if (value != null) {
			return value.toString();
		}
		// If no value yet, try to get it as a name_value=xyz parameter
		String prefix = name + "_";
		for (String paramName : parameters.keySet()) {
			if (paramName.startsWith(prefix)) {
				// Support images buttons, which would submit parameters as name_value.x=123
				for (String suffix : SUBMIT_IMAGE_SUFFIXES) {
					if (paramName.endsWith(suffix)) {
						return paramName.substring(prefix.length(), paramName.length() - suffix.length());
					}
				}
				return paramName.substring(prefix.length());
			}
		}
		// We couldn't find the parameter value...
		return null;
	}

	/**
	 * Return a map containing all parameters with the given prefix.
	 * Maps single values to String and multiple values to String array.
	 *
For example, with a prefix of "spring_", "spring_param1" and
	 * "spring_param2" result in a Map with "param1" and "param2" as keys.
	 * @param request HTTP request in which to look for parameters
	 * @param prefix the beginning of parameter names
	 * (if this is null or the empty string, all parameters will match)
	 * @return map containing request parameters without the prefix,
	 * containing either a String or a String array as values
	 * @see javax.servlet.ServletRequest#getParameterNames
	 * @see javax.servlet.ServletRequest#getParameterValues
	 * @see javax.servlet.ServletRequest#getParameterMap
	 */
	public static Map<String, Object> getParametersStartingWith(ServletRequest request, String prefix) {
		Assert.notNull(request, "Request must not be null");
		Enumeration<String> paramNames = request.getParameterNames();
		Map<String, Object> params = new TreeMap<String, Object>();
		if (prefix == null) {
			prefix = "";
		}
		while (paramNames != null && paramNames.hasMoreElements()) {
			String paramName = paramNames.nextElement();
			if ("".equals(prefix) || paramName.startsWith(prefix)) {
				String unprefixed = paramName.substring(prefix.length());
				String[] values = request.getParameterValues(paramName);
				if (values == null || values.length == 0) {
					// Do nothing, no values found at all.
				}
				else if (values.length > 1) {
					params.put(unprefixed, values);
				}
				else {
					params.put(unprefixed, values[0]);
				}
			}
		}
		return params;
	}

	/**
	 * Return the target page specified in the request.
	 * @param request current servlet request
	 * @param paramPrefix the parameter prefix to check for
	 * (e.g. "_target" for parameters like "_target1" or "_target2")
	 * @param currentPage the current page, to be returned as fallback
	 * if no target page specified
	 * @return the page specified in the request, or current page if not found
	 */
	public static int getTargetPage(ServletRequest request, String paramPrefix, int currentPage) {
		Enumeration<String> paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = paramNames.nextElement();
			if (paramName.startsWith(paramPrefix)) {
				for (int i = 0; i < WebUtils.SUBMIT_IMAGE_SUFFIXES.length; i++) {
					String suffix = WebUtils.SUBMIT_IMAGE_SUFFIXES[i];
					if (paramName.endsWith(suffix)) {
						paramName = paramName.substring(0, paramName.length() - suffix.length());
					}
				}
				return Integer.parseInt(paramName.substring(paramPrefix.length()));
			}
		}
		return currentPage;
	}

	/**
	 * Extract the URL filename from the given request URL path.
	 * Correctly resolves nested paths such as "/products/view.html" as well.
	 * @param urlPath the request URL path (e.g. "/index.html")
	 * @return the extracted URI filename (e.g. "index")
	 */
	public static String extractFilenameFromUrlPath(String urlPath) {
		String filename = extractFullFilenameFromUrlPath(urlPath);
		int dotIndex = filename.lastIndexOf('.');
		if (dotIndex != -1) {
			filename = filename.substring(0, dotIndex);
		}
		return filename;
	}

	/**
	 * Extract the full URL filename (including file extension) from the given request URL path.
	 * Correctly resolves nested paths such as "/products/view.html" as well.
	 * @param urlPath the request URL path (e.g. "/products/index.html")
	 * @return the extracted URI filename (e.g. "index.html")
	 */
	public static String extractFullFilenameFromUrlPath(String urlPath) {
		int end = urlPath.indexOf(';');
		if (end == -1) {
			end = urlPath.indexOf('?');
			if (end == -1) {
				end = urlPath.length();
			}
		}
		int begin = urlPath.lastIndexOf('/', end) + 1;
		return urlPath.substring(begin, end);
	}

	/**
	 * Parse the given string with matrix variables. An example string would look
	 * like this {@code "q1=a;q1=b;q2=a,b,c"}. The resulting map would contain
	 * keys {@code "q1"} and {@code "q2"} with values {@code ["a","b"]} and
	 * {@code ["a","b","c"]} respectively.
	 *
	 * @param matrixVariables the unparsed matrix variables string
	 * @return a map with matrix variable names and values, never {@code null}
	 */
	public static MultiValueMap<String, String> parseMatrixVariables(String matrixVariables) {
		MultiValueMap<String, String> result = new LinkedMultiValueMap<String, String>();
		if (!StringUtils.hasText(matrixVariables)) {
			return result;
		}
		StringTokenizer pairs = new StringTokenizer(matrixVariables, ";");
		while (pairs.hasMoreTokens()) {
			String pair = pairs.nextToken();
			int index = pair.indexOf('=');
			if (index != -1) {
				String name = pair.substring(0, index);
				String rawValue = pair.substring(index + 1);
				for (String value : StringUtils.commaDelimitedListToStringArray(rawValue)) {
					result.add(name, value);
				}
			}
			else {
				result.add(pair, "");
			}
		}
		return result;
	}
}


text:
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.

Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.UseConditionalExpression
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax

Namespace Microsoft.CodeAnalysis.VisualBasic.UseConditionalExpression
    <DiagnosticAnalyzer(LanguageNames.VisualBasic)>
    Friend Class VisualBasicUseConditionalExpressionForReturnDiagnosticAnalyzer
        Inherits AbstractUseConditionalExpressionForReturnDiagnosticAnalyzer(Of MultiLineIfBlockSyntax)

        Public Sub New()
            MyBase.New(New LocalizableResourceString(NameOf(VBFeaturesResources.If_statement_can_be_simplified), VBFeaturesResources.ResourceManager, GetType(VBFeaturesResources)))
        End Sub

        Protected Overrides Function GetSyntaxFactsService() As ISyntaxFactsService
            Return VisualBasicSyntaxFactsService.Instance
        End Function
    End Class
End Namespace

redpajama_set_name: RedPajamaGithub


text:
{{ 'PANEL.BACKGROUND.TITLE' | translate }}

		<button class="panel-close-button" mat-icon-button matTooltip="{{ 'PANEL.CLOSE' | translate }}" (click)="close()">
			<mat-icon>close</mat-icon>
		</button>

{{ 'PANEL.BACKGROUND.BLURRED_SECTION' | translate }}

				<button
					*ngFor="let effect of noEffectAndBlurredBackground"
					mat-icon-button
					class="effect-button"
					[class.active-effect-btn]="backgroundSelectedId === effect.id"
					(click)="applyBackground(effect)"
				>
					<mat-icon
						[matTooltip]="
							effect.type === effectType.NONE
								? ('PANEL.BACKGROUND.NO_EFFECTS' | translate)
								: ('PANEL.BACKGROUND.BLURRED_EFFECT' | translate)
						"
						>{{ effect.thumbnail }}</mat-icon
					>
				</button>

{{ 'PANEL.BACKGROUND.IMAGES_SECTION' | translate }}


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

<title>org.apache.jmeter.report.processor (Apache JMeter API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Apache JMeter

Prev Package

Next Package

Frames

No Frames

All Classes

Package org.apache.jmeter.report.processor

This package contains the components used for computing the data used by javascript graphs.

See: Description

Interface Summary

Interface
Description

Aggregator

The interface Aggregator represents an aggregator used by graph consumers.

AggregatorFactory

A factory for creating Aggregator objects.

ResultData

The interface ResultData represents a result from samples processing.

ResultDataVisitor<TVisit>

The interface ResultDataVisitor represents a visitor for result data from
 samples processing.

SampleConsumer

Defines a sample consumer

 A sample consumer is meant to consume samples in order to process them.

SampleIndexer<TIndex>

The classes that implement interface SampleIndexer have to calculate an index
 from a sample.

SampleProcessor

Defines a sample processor.

SampleProducer

Defines a sample producer

 A sample producer is able to produce sample on different channels.

SampleSource

The interface SampleSource represents a source of samples for sample consumers.

ThresholdSelector

The interface ThresholdSelector represents a projection from the samplers
 with the same name to APDEX threshold information.

Class Summary

Class
Description

AbstractAggregatorFactory

 A factory for creating AbstractAggregator objects.

AbstractSampleConsumer

Base class for sample consumer implementations.

AbstractSampleProcessor

Base for sample processor implementations

 Implements basic logic for setting sample context and handling channel
 attributes.

AbstractSampleSource

AbstractSummaryConsumer<TData>

The class AbstractSummaryConsumer provides a base class for data of the
 dashboard page.

AggregateConsumer

The Class AggregateConsumer provides a consumer that can aggregate samples to
 provide a result

ApdexSummaryConsumer

 The class ApdexSummaryConsumer provides a consumer that calculates Apdex for
 each sample name.

ApdexSummaryData

The class ApdexSummaryData provides information for ApdexSummaryConsumer.

ApdexThresholdsInfo

The class ApdexThresholdsInfo provides a container for APDEX threshold
 information.

ChannelContext

Define a context associated to a sample consumer/producer channel

CsvFileSampleSource

Read a csv source file and write its rows (samples) all the registered
 SampleConsumers.

ErrorsSummaryConsumer

 The class ErrorSummaryConsumer provides a consumer that calculates error
 statistics.

ExternalSampleSorter

R-way external sample sorter.

FieldSampleComparator

FilterConsumer

 The class FilterConsumer provides a way to discard samples in a consumer
 chain.

ListResultData

The class ListResultData provides a list of results from sample processing.

MapResultData

The class MapResultData provides a hash map of results from samples
 processing.

MaxAggregator

The class MaxAggregator is used to get maximum from samples.

MeanAggregator

The class MeanAggregator is used to get mean from samples.

MeanAggregatorFactory

A factory for creating MeanAggregator objects.

MedianAggregatorFactory

A factory for creating PercentileAggregator with index of percentile fixed to
 value 50.

MinAggregator

The class MinAggregator is used to get minimum from samples.

NormalizerSampleConsumer

Consume samples using the JMeter timestamp property (defaulting to SampleSaveConfiguration.MILLISECONDS) and reproduce them as a long
 value (for faster treatment later in the consuming chain).

PercentileAggregator

The class PercentileAggregator is used to get percentile from samples.

PercentileAggregatorFactory

A factory for creating PercentileAggregator objects.

RequestsSummaryConsumer

 The class GrapherConsumer provides a consumer that count succeeded and failed
 samples.

SampleContext

Defines the context in which SampleConsumer, SampleProducer
 will operate

SampleWriterConsumer

Sample consumed byt this consumer are written to a file

StatisticsSummaryConsumer

 The class ErrorSummaryConsumer provides a consumer that calculates error
 statistics.

StatisticsSummaryData

The class ApdexSummaryData provides information for
 StatisticsSummaryConsumer.

SumAggregator

The class SumAggregator is used to get sum from samples.

SumAggregatorFactory

A factory for creating SumAggregator objects.

TaggerConsumer<TIndex>

The Class TimeCountConsumer adds a data field to the samples it consumes.

TimeRateAggregator

The class TimeRateAggregator is used to get samples rate by second.

TimeRateAggregatorFactory

A factory for creating TimeRateAggregator objects.

ValueResultData

The class ValueResultData provides a value result from samples processing.

Package org.apache.jmeter.report.processor Description

This package contains the components used for computing the data used by javascript graphs.

Overview

Package

Class

Tree

Deprecated

Index

Help

Apache JMeter

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright © 1998-2016 Apache Software Foundation. All Rights Reserved.


text:
pyexcel.iget\_array
===================

.. currentmodule:: pyexcel

.. autofunction:: iget_array


text:
import java.io.{FileOutputStream, OutputStreamWriter, BufferedWriter}
import MapDifferentLast._

object BufferWriter {
  def writeToFile(path: String, solutions: Iterator[Long]) = {
    val writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path)))
    mapDifferentLast(solutions.map(String.valueOf))(_ + "\n")(identity)
      .foreach(writer.write)
    writer.close()
  }
}


text:
define(["models/time_span","moment","serializers/time_span_serializer"], function(TimeSpan, moment, TimeSpanSerializer){
  describe("TimeSpanSerializer", function(){
    var time_span;
    beforeEach(function(){
      time_span = TimeSpan.create();
      var start = moment("2013-05-28 15:20");
      time_span.start(start);
    });

      describe("fully populated", function(){
        beforeEach(function(){
          time_span.end(time_span.start().clone().add(1, "days"));
        });
        it("produces valid json of complete time_span", function(){
          var json_output = TimeSpanSerializer.serialize(time_span);
          var object = JSON.parse(json_output);
          expect(object.time_span).toBeDefined();
        });

        it("formats time stamps correctly", function(){
          var json_output = TimeSpanSerializer.serialize(time_span);
          var object = JSON.parse(json_output);

          expect(object.time_span.start).toEqual("2013-05-28T13:20:00.000Z");
          expect(object.time_span.end).toEqual("2013-05-29T13:20:00.000Z");
        });

        describe("when converting to object", function(){
          var obj;
          beforeEach(function(){
            obj = TimeSpanSerializer.to_obj(time_span);
          });

          it("creates a time span object", function(){
            expect(obj.time_span).toBeDefined();
          });

          it("stores start date", function(){
            expect(obj.time_span.start).toEqual("2013-05-28T13:20:00.000Z");
          });

          it("stores end date", function(){
            expect(obj.time_span.end).toEqual("2013-05-29T13:20:00.000Z");
          });
        });//END to_obj

      });//END full

      describe("when serialing with only start", function(){
        it("produces valid json", function(){
          var json_output = TimeSpanSerializer.serialize(time_span);
          var object = JSON.parse(json_output);
          expect(object.time_span).toBeDefined();
        });

      });//END only start
  });//END TimeSpanSerializer

});


text:
import json
from pkg_resources import resource_string
from pedsnetcdms.sa_makers import make_models, Base

DECLARATIVE_MODELS = json.loads(resource_string('pedsnetcdms.pcornetcdm',
                                                'models.json'))

for model in make_models(DECLARATIVE_MODELS, (Base,)):
    globals()[model.__name__] = model


text:
<!DOCTYPE html>
<html>
  <head>
    <title>
      audionode-disconnect.html
    </title>
    <script src="/resources/testharness.js"></script>
    <script src="/resources/testharnessreport.js"></script>
    <script src="/webaudio/resources/audit-util.js"></script>
    <script src="/webaudio/resources/audit.js"></script>
  </head>
  <body>
    <script id="layout-test-code">
      let audit = Audit.createTaskRunner();

      // Task 1: test disconnect() method.
      audit.define('disconnect()', (task, should) => {

        // Connect a source to multiple gain nodes, each connected to the
        // destination. Then disconnect the source. The expected output should
        // be all zeros since the source was disconnected.
        let context = new OfflineAudioContext(1, 128, 44100);
        let source = context.createBufferSource();
        let buffer1ch = createConstantBuffer(context, 128, [1]);
        let gain1 = context.createGain();
        let gain2 = context.createGain();
        let gain3 = context.createGain();

        source.buffer = buffer1ch;

        source.connect(gain1);
        source.connect(gain2);
        source.connect(gain3);
        gain1.connect(context.destination);
        gain2.connect(context.destination);
        gain3.connect(context.destination);
        source.start();

        // This disconnects everything.
        source.disconnect();

        context.startRendering()
            .then(function(buffer) {

              // With everything disconnected, the result should be zero.
              should(buffer.getChannelData(0), 'Channel #0')
                  .beConstantValueOf(0);

            })
            .then(() => task.done());
      });

      // Task 2: test disconnect(output) method.
      audit.define('disconnect(output)', (task, should) => {

        // Create multiple connections from each output of a ChannelSplitter
        // to a gain node. Then test if disconnecting a single output of
        // splitter is actually disconnected.
        let context = new OfflineAudioContext(1, 128, 44100);
        let source = context.createBufferSource();
        let buffer3ch = createConstantBuffer(context, 128, [1, 2, 3]);
        let splitter = context.createChannelSplitter(3);
        let sum = context.createGain();

        source.buffer = buffer3ch;

        source.connect(splitter);
        splitter.connect(sum, 0);
        splitter.connect(sum, 1);
        splitter.connect(sum, 2);
        sum.connect(context.destination);
        source.start();

        // This disconnects the second output.
        splitter.disconnect(1);

        context.startRendering()
            .then(function(buffer) {

              // The rendered channel should contain 4. (= 1 + 0 + 3)
              should(buffer.getChannelData(0), 'Channel #0')
                  .beConstantValueOf(4);

            })
            .then(() => task.done());
      });

      // Task 3: test disconnect(AudioNode) method.
      audit.define('disconnect(AudioNode)', (task, should) => {

        // Connect a source to multiple gain nodes. Then test if disconnecting a
        // single destination selectively works correctly.
        let context = new OfflineAudioContext(1, 128, 44100);
        let source = context.createBufferSource();
        let buffer1ch = createConstantBuffer(context, 128, [1]);
        let gain1 = context.createGain();
        let gain2 = context.createGain();
        let gain3 = context.createGain();
        let orphan = context.createGain();

        source.buffer = buffer1ch;

        source.connect(gain1);
        source.connect(gain2);
        source.connect(gain3);
        gain1.connect(context.destination);
        gain2.connect(context.destination);
        gain3.connect(context.destination);
        source.start();

        source.disconnect(gain2);

        context.startRendering()
            .then(function(buffer) {

              // The |sum| gain node should produce value 2. (1 + 0 + 1 = 2)
              should(buffer.getChannelData(0), 'Channel #0')
                  .beConstantValueOf(2);

            })
            .then(() => task.done());
      });

      // Task 4: test disconnect(AudioNode, output) method.
      audit.define('disconnect(AudioNode, output)', (task, should) => {

        // Connect a buffer with 2 channels with each containing 1 and 2
        // respectively to a ChannelSplitter, then connect the splitter to 2
        // gain nodes as shown below:
        //   (1) splitter#0 => gain1
        //   (2) splitter#0 => gain2
        //   (3) splitter#1 => gain2
        // Then disconnect (2) and verify if the selective disconnection on a
        // specified output of the destination node works correctly.
        let context = new OfflineAudioContext(1, 128, 44100);
        let source = context.createBufferSource();
        let buffer2ch = createConstantBuffer(context, 128, [1, 2]);
        let splitter = context.createChannelSplitter(2);
        let gain1 = context.createGain();
        let gain2 = context.createGain();

        source.buffer = buffer2ch;

        source.connect(splitter);
        splitter.connect(gain1, 0);  // gain1 gets channel 0.
        splitter.connect(gain2, 0);  // gain2 sums channel 0 and 1.
        splitter.connect(gain2, 1);
        gain1.connect(context.destination);
        gain2.connect(context.destination);
        source.start();

        splitter.disconnect(gain2, 0);  // Now gain2 gets [2]

        context.startRendering()
            .then(function(buffer) {

              // The sum of gain1 and gain2 should produce value 3. (= 1 + 2)
              should(buffer.getChannelData(0), 'Channel #0')
                  .beConstantValueOf(3);

            })
            .then(() => task.done());
      });

      // Task 5: test disconnect(AudioNode, output, input) method.
      audit.define('disconnect(AudioNode, output, input)', (task, should) => {

        // Create a 3-channel buffer with [1, 2, 3] in each channel and then
        // pass it through a splitter and a merger. Each input/output of the
        // splitter and the merger is connected in a sequential order as shown
        // below.
        //   (1) splitter#0 => merger#0
        //   (2) splitter#1 => merger#1
        //   (3) splitter#2 => merger#2
        // Then disconnect (3) and verify if each channel contains [1] and [2]
        // respectively.
        let context = new OfflineAudioContext(3, 128, 44100);
        let source = context.createBufferSource();
        let buffer3ch = createConstantBuffer(context, 128, [1, 2, 3]);
        let splitter = context.createChannelSplitter(3);
        let merger = context.createChannelMerger(3);

        source.buffer = buffer3ch;

        source.connect(splitter);
        splitter.connect(merger, 0, 0);
        splitter.connect(merger, 1, 1);
        splitter.connect(merger, 2, 2);
        merger.connect(context.destination);
        source.start();

        splitter.disconnect(merger, 2, 2);

        context.startRendering()
            .then(function(buffer) {

              // Each channel should have 1, 2, and 0 respectively.
              should(buffer.getChannelData(0), 'Channel #0')
                  .beConstantValueOf(1);
              should(buffer.getChannelData(1), 'Channel #1')
                  .beConstantValueOf(2);
              should(buffer.getChannelData(2), 'Channel #2')
                  .beConstantValueOf(0);

            })
            .then(() => task.done());
      });

      // Task 6: exception checks.
      audit.define('exceptions', (task, should) => {
        let context = new OfflineAudioContext(2, 128, 44100);
        let gain1 = context.createGain();
        let splitter = context.createChannelSplitter(2);
        let merger = context.createChannelMerger(2);
        let gain2 = context.createGain();
        let gain3 = context.createGain();

        // Connect a splitter to gain nodes and merger so we can test the
        // possible ways of disconnecting the nodes to verify that appropriate
        // exceptions are thrown.
        gain1.connect(splitter);
        splitter.connect(gain2, 0);
        splitter.connect(gain3, 1);
        splitter.connect(merger, 0, 0);
        splitter.connect(merger, 1, 1);
        gain2.connect(gain3);
        gain3.connect(context.destination);
        merger.connect(context.destination);

        // There is no output #2. An exception should be thrown.
        should(function() {
          splitter.disconnect(2);
        }, 'splitter.disconnect(2)').throw(DOMException, 'IndexSizeError');

        // Disconnecting the output already disconnected should not throw.
        should(function() {
          splitter.disconnect(1);
          splitter.disconnect(1);
        }, 'Disconnecting a connection twice').notThrow();

        // gain1 is not connected gain2. An exception should be thrown.
        should(function() {
          gain1.disconnect(gain2);
        }, 'gain1.disconnect(gain2)').throw(DOMException, 'InvalidAccessError');

        // gain1 and gain3 are not connected. An exception should be thrown.
        should(function() {
          gain1.disconnect(gain3);
        }, 'gain1.disconnect(gain3)').throw(DOMException, 'InvalidAccessError');

        // There is no output #2 in the splitter. An exception should be thrown.
        should(function() {
          splitter.disconnect(gain2, 2);
        }, 'splitter.disconnect(gain2, 2)').throw(DOMException, 'IndexSizeError');

        // The splitter and gain1 are not connected. An exception should be
        // thrown.
        should(function() {
          splitter.disconnect(gain1, 0);
        }, 'splitter.disconnect(gain1, 0)').throw(DOMException, 'InvalidAccessError');

        // The splitter output #0 and the gain3 output #0 are not connected. An
        // exception should be thrown.
        should(function() {
          splitter.disconnect(gain3, 0, 0);
        }, 'splitter.disconnect(gain3, 0, 0)').throw(DOMException, 'InvalidAccessError');

        // The output index is out of bound. An exception should be thrown.
        should(function() {
          splitter.disconnect(merger, 3, 0);
        }, 'splitter.disconnect(merger, 3, 0)').throw(DOMException, 'IndexSizeError');

        task.done();
      });

      audit.define('disabled-outputs', (task, should) => {
        // See crbug.com/656652
        let context = new OfflineAudioContext(2, 1024, 44100);
        let g1 = context.createGain();
        let g2 = context.createGain();
        g1.connect(g2);
        g1.disconnect(g2);
        let g3 = context.createGain();
        g2.connect(g3);
        g1.connect(g2);
        context.startRendering()
            .then(function() {
              // If we make it here, we passed.
              should(true, 'Disabled outputs handled')
                  .message('correctly', 'inccorrectly');
            })
            .then(() => task.done());
      });

      audit.run();
    </script>
  </body>
</html>


text:
from datetime import datetime, date
import psutil
import sys
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('direction', type=str,
                    choices=['left', 'right'])
args = parser.parse_args()

status = ''

deadlines = {
    # 'ICLR': date(2022, 9, 28),
}

if args.direction == 'left':
    status = '<fc=#B27AEB><fn=2>❤</fn></fc>'
elif args.direction == 'right':
    battery = psutil.sensors_battery()
    if not battery.power_plugged:
        status += f'<fc=#D43737><fn=1></fn>{int(battery.percent)}%</fc> '

    today_date = datetime.now().date()
    for tag,tag_date in deadlines.items():
        n_days = (tag_date-today_date).days
        day_str = 'day' if n_days == 1 else 'days'
        status += f'<fc=#ABABAB>{tag}: {n_days} {day_str} | </fc>'

    now = datetime.now()
    time_str = now.strftime('%Y.%m.%d %-I:%M%p')
    status += f'<fc=#ABABAB>{time_str}</fc>'

print(status)


text:
from dataclasses import dataclass
from typing import Any, Callable

from anki import hooks

@dataclass
class AnkiHookManager:
    hooks: Any = hooks

    def hook(self, hook_name: str, handler: Callable):
        self.hooks.addHook(hook_name, handler)

    def unhook(self, hook_name: str, handler: Callable):
        self.hooks.remHook(hook_name, handler)


text:
package com.suzhou.carmanager.ui.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.TResult;
import com.suzhou.carmanager.Constants;
import com.suzhou.carmanager.R;
import com.suzhou.carmanager.adapter.JobActionAdapter;
import com.suzhou.carmanager.base.BaseActivity;
import com.suzhou.carmanager.entity.DeliverAddress;
import com.suzhou.carmanager.entity.FileInfo;
import com.suzhou.carmanager.entity.NetMessageVO;
import com.suzhou.carmanager.entity.Order;
import com.suzhou.carmanager.entity.PickGoodsAddress;
import com.suzhou.carmanager.entity.Task;
import com.suzhou.carmanager.location.BLocationManager;
import com.suzhou.carmanager.location.Location;
import com.suzhou.carmanager.manager.UploadManager;
import com.suzhou.carmanager.network.CarApiManager;
import com.suzhou.carmanager.network.HttpData;
import com.suzhou.carmanager.network.RxJava.MySubscriber;
import com.suzhou.carmanager.utils.ParseJsonUtils;
import com.suzhou.carmanager.utils.UIUtils;
import com.suzhou.carmanager.view.DividerItemDecoration;
import com.suzhou.carmanager.view.NavigationTopBar;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by v-jibfen on 2017/9/11.
 */

public class JobActionActivity extends BaseActivity{
    private static final String TAG = JobActionActivity.class.getSimpleName();
    private Context _context;
    private RecyclerView _orderRecycler;
    private JobActionAdapter _jobActionAdapter;
    private CheckBox _checkBoxAll;
    private UploadManager _uploadManager;
    private ProgressDialog _progressDialog;
    private TextView _jobActionView;
    private TextView _orderCountsView;

    private String _assignId;
    private String _formJobAction;
    private String _arriveName;
    private List<Order> _orders;
    private String _groupKey;

    private String _currentSelectedOrderCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_job_action);
        _context = JobActionActivity.this;
        _uploadManager = new UploadManager();
        _navigationTopBar = (NavigationTopBar) getSupportFragmentManager().findFragmentByTag(NavigationTopBar.class.getSimpleName());
        _navigationTopBar.setViewVisibility(NavigationTopBar.NAVIGATION_VIEWS.RIGHT, View.INVISIBLE);
        _navigationTopBar.setViewVisibility(NavigationTopBar.NAVIGATION_VIEWS.RIGHT_BARGE_TEXT, View.INVISIBLE);
        _navigationTopBar.setViewVisibility(NavigationTopBar.NAVIGATION_VIEWS.LEFT, View.VISIBLE);

        _navigationTopBar.setClickListener(NavigationTopBar.NAVIGATION_VIEWS.LEFT, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        _orderCountsView = (TextView) findViewById(R.id.order_counts);
        _jobActionView = (TextView) findViewById(R.id.job_action);

        _jobActionView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (TextUtils.isEmpty(getCheckedOrderId())) {

                    UIUtils.showToastMessage(_context, "请选择订单!");
                    return;
                }
                final Location location = BLocationManager.getInstance().getLatestLocation();

                switch (_formJobAction) {
                    case Constants.FROM_PICK_GOODS:
                        UIUtils.showPromptDialog(_context, "提示", "确定完成提货?", "确定", "取消",
                                null,
                                new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        sendRequestForFinishPickGoods(_assignId, getCheckedOrderId(), location.getLatitude(), location.getLongitude());
                                    }
                                }, true);

                        break;

                    case Constants.FROM_ARRIVE_DELIVERY:
                        UIUtils.showPromptDialog(_context, "提示", "确定完成送货?", "确定", "取消",
                                null,
                                new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        sendRequestForCompleted(_assignId, getCheckedOrderId(), location.getLatitude(), location.getLongitude());
                                    }
                                }, true);

                        break;
                }
            }
        });
        initView();
        initOrderList();

    }

    private void initView() {
        _assignId = getIntent().getStringExtra(Constants.ASSIGN_ID);
        _formJobAction = getIntent().getStringExtra("job_action_from");
        _arriveName = getIntent().getStringExtra("arrive_name");
        _groupKey = getIntent().getStringExtra("group_key");

        ((TextView) findViewById(R.id.address_name)).setText(_arriveName);
        switch (_formJobAction) {
            case Constants.FROM_PICK_GOODS:
                _jobActionView.setText("完成提货");
                _navigationTopBar.setText(NavigationTopBar.NAVIGATION_VIEWS.TITLE, R.string.action_title_get_thing);
                break;

            case Constants.FROM_ARRIVE_DELIVERY:
                _jobActionView.setText("完成送货");
                _navigationTopBar.setText(NavigationTopBar.NAVIGATION_VIEWS.TITLE, R.string.action_title);
                break;
        }
    }

    private void initOrderList() {

        _orders = (List<Order>) getIntent().getSerializableExtra("order_list");
        _orderRecycler = (RecyclerView) findViewById(R.id.order_recyclerview);
        _orderRecycler.setLayoutManager(new LinearLayoutManager(_context));
        DividerItemDecoration itemDecoration = new DividerItemDecoration(_context, LinearLayoutManager.VERTICAL, R.drawable.recycle_item_divider_12);
        _orderRecycler.addItemDecoration(itemDecoration);
        _jobActionAdapter = new JobActionAdapter(_context, _formJobAction);
        _orderRecycler.setAdapter(_jobActionAdapter);

        _jobActionAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                Order order = (Order) adapter.getData().get(position);
                Intent intent = new Intent(_context, OrderDetailActivity.class);
                intent.putExtra(Constants.ASSIGN_ID, _assignId);
                intent.putExtra(Constants.ORDER_NO, order.getOrderCode());
                startActivity(intent);
            }
        });

        _jobActionAdapter.setJobActionListener(new JobActionAdapter.JobActionListener() {
            @Override
            public void onCheckFiles(Order order) {
                Intent intent = new Intent();
                intent.setClass(_context, FileListActivity.class);
                intent.putExtra(Constants.ASSIGN_ID, _assignId);
                intent.putExtra(Constants.ORDER_NO, order.getOrderCode());
//                intent.putExtra(Constants.FILE_LIST, (Serializable) fileInfos);
                startActivity(intent);
            }

            @Override
            public void onPostException(Order order) {
                Intent intent = new Intent();
                intent.setClass(_context, ExceptionPostActivity.class);
                intent.putExtra(Constants.EXCEPTION_ID, _assignId);
                intent.putExtra(Constants.EXCEPTION_NO, order.getOrderCode());
                intent.putExtra(Constants.EXCEPTION_TYPE, 2);
                startActivityForResult(intent, Constants.POST_EXCEPTION_CODE);
            }

            @Override
            public void onPostBrokenException(Order order) {

                String operate_type = "";
                switch (_formJobAction) {
                    case Constants.FROM_PICK_GOODS:
                        operate_type = "FINISH_PICKUP_GOODS_OK";
                        break;

                    case Constants.FROM_ARRIVE_DELIVERY:
                        operate_type = "HAS_COMPLETED_GOODS_OK";
                        break;
                }

                Intent intent = new Intent(_context, ExceptionPostActivity.class);
                intent.putExtra(Constants.EXCEPTION_ID, _assignId);
                intent.putExtra(Constants.EXCEPTION_NO, order.getOrderCode());
                intent.putExtra(Constants.EXCEPTION_DETAIL, "CARGO_BROKEN");
                intent.putExtra(Constants.EXCEPTION_TYPE, 2);
                intent.putExtra(Constants.EXCEPTION_OPERATE_TYPE, operate_type);
                startActivityForResult(intent, Constants.POST_EXCEPTION_CODE);
            }

            @Override
            public void onUploadQSD(Order order) {
                _currentSelectedOrderCode = order.getOrderCode();
                File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
                Uri imageUri = Uri.fromFile(file);
                CompressConfig compressConfig = new CompressConfig.Builder().setMaxSize(50 * 1024).setMaxPixel(800).create();
                getTakePhoto().onEnableCompress(compressConfig, true);
                getTakePhoto().onPickFromCapture(imageUri);
            }

            @Override
            public void onCheckBoxClick() {
                updateOrderCountsView(_jobActionAdapter.getOrderCodes().size());
            }
        });

        _checkBoxAll = (CheckBox) findViewById(R.id.checkbox_all);
        _checkBoxAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (_checkBoxAll.isChecked()) {
                    _jobActionAdapter.checkAll();

                } else {
                    _jobActionAdapter.unCheckAll();

                }
                if (_jobActionAdapter.isSelectAll()) {
                    _checkBoxAll.setChecked(true);
                } else {
                    _checkBoxAll.setChecked(false);
                }
                updateOrderCountsView(_jobActionAdapter.getOrderCodes().size());
            }
        });

        _jobActionAdapter.setNewData(_orders);
//        initData();
    }

    private void updateOrderCountsView(final int counts) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                if (_jobActionAdapter.isSelectAll()) {
                    _checkBoxAll.setChecked(true);
                } else {
                    _checkBoxAll.setChecked(false);
                }
                _orderCountsView.setText(String.valueOf(counts));
            }
        });
    }

    private String getCheckedOrderId() {

        List<String> orderIds = _jobActionAdapter.getOrderCodes();
        String ids = "";

        for (int i = 0; i < orderIds.size(); i ++) {
            if (i == orderIds.size() - 1) {
                ids = ids + orderIds.get(i);
            } else {
                ids = ids + orderIds.get(i) + ",";
            }
        }
        Log.d("FilesGetActivity", "ids---->" + ids);

        return ids;
    }

    private void initData() {
        List<Order> orders = new ArrayList<>();
        for (int i = 0; i < 3; i ++) {
            Order order = new Order();
            order.setCustomerNu("sdasd");
            orders.add(order);
        }
        _jobActionAdapter.setNewData(orders);
    }

    @Override
    protected int getContentViewId() {
        return 0;
    }

    @Override
    protected int getFragmentContentId() {
        return 0;
    }

    @Override
    public void takeSuccess(TResult result) {
        Log.i(TAG,"takeSuccess:" + result.getImage().getCompressPath());
        uploadImagesToServer(result.getImage().getCompressPath());
    }

    @Override
    public void takeFail(TResult result, String msg) {
        Log.i(TAG, "takeFail:" + msg);
    }

    @Override
    public void takeCancel() {
        Log.i(TAG, getResources().getString(com.jph.takephoto.R.string.msg_operation_canceled));
    }

    private void uploadImagesToServer(String path) {
        _uploadManager.clearUploadData();

        _uploadManager.sendRequestForUpload(new File(path), new UploadManager.UploadCallBack() {
            @Override
            public void onSuccess(String fileId) {

                //上传签收单接口

                sendRequestForUploadQSD(Long.valueOf(_assignId), _currentSelectedOrderCode, Long.valueOf(fileId));
            }

            @Override
            public void onError() {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        UIUtils.showToastMessage(_context, "签收单上传失败!");
                        dismissProgressDialog();
                    }
                });

            }
        });
        _uploadManager.addImage(path);
        showProgressDialog();
    }

    private void showProgressDialog() {
        _progressDialog = ProgressDialog.show(_context, null, "正在上传照片", false, false);
    }

    private void dismissProgressDialog() {
        _progressDialog.dismiss();
    }

    private void sendRequestForUploadQSD(long assignId, String orderCode, long fileId) {
        MySubscriber<NetMessageVO> ss = new MySubscriber<NetMessageVO>() {
            @Override
            public void onNext(NetMessageVO o) {
                dismissProgressDialog();
//                _jobActionAdapter.getData().contains()
                UIUtils.showToastMessage(_context, "签收单上传成功!");
                refreshPage(false);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        UIUtils.showToastMessage(_context, "签收单上传失败!");
                    }
                });

            }
        };

        CarApiManager.getInstance().sendRequest(HttpData.InterfacesURL.ASSIGN_OPERATE_UPLOAD_QSADN, ss,
                HttpData.getOperateUploadQSDData(assignId, orderCode, fileId));
    }

    private void sendRequestForFinishPickGoods(String assignId, String orderCodes, double lat, double lng) {
        MySubscriber<NetMessageVO> ss = new MySubscriber<NetMessageVO>() {
            @Override
            public void onNext(NetMessageVO o) {

                UIUtils.showToastMessage(_context, "操作成功!");
                refreshPage(true);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        UIUtils.showToastMessage(_context, "操作失败!");
                    }
                });

            }
        };

        CarApiManager.getInstance().sendRequest(HttpData.InterfacesURL.ASSIGN_OPERATE_FINISH_PICK_GOODS, ss,
                HttpData.getOperateFinishPickGoodsData(assignId, orderCodes, lat, lng));
    }

    private void sendRequestForCompleted(String assignId, String orderCodes, double lat, double lng) {
        MySubscriber<NetMessageVO> ss = new MySubscriber<NetMessageVO>() {
            @Override
            public void onNext(NetMessageVO o) {

                UIUtils.showToastMessage(_context, "操作成功!");
                refreshPage(true);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        UIUtils.showToastMessage(_context, "操作失败!");
                    }
                });

            }
        };

        CarApiManager.getInstance().sendRequest(HttpData.InterfacesURL.ASSIGN_OPERATE_COMPLETED, ss,
                HttpData.getOperateCompletedData(assignId, orderCodes, lat, lng));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        refreshPage(false);
    }

    private void refreshPage(boolean isNeedHandlerExit) {
        switch (_formJobAction) {
            case Constants.FROM_PICK_GOODS:
                sendRequestForPickGoods(isNeedHandlerExit);
                break;

            case Constants.FROM_ARRIVE_DELIVERY:
                sendRequestForFinishDeliver(isNeedHandlerExit);
                break;
        }
    }

    private void sendRequestForPickGoods(final boolean isNeedHandlerExit) {
        MySubscriber<NetMessageVO> ss = new MySubscriber<NetMessageVO>() {
            @Override
            public void onNext(NetMessageVO o) {
                _orders.clear();
                Task task = ParseJsonUtils.getObjectFromJson(o.data, Task.class);

                List<PickGoodsAddress> pickGoodsAddresses = task.getPickupGoodsAddressGroupList();

                if (pickGoodsAddresses != null && pickGoodsAddresses.size() > 0) {
                    for (int i = 0; i < pickGoodsAddresses.size(); i ++) {
                        if (_groupKey.equals(pickGoodsAddresses.get(i).getGroupKey())) {
                            _orders = pickGoodsAddresses.get(i).getPickupGoodsOrderList();
                        }
                    }
                    if (_orders != null && _orders.size() > 0 ) {
                        _jobActionAdapter.setNewData(_orders);

                    } else {
                        if (isNeedHandlerExit) {
                            finish();
                        }
                        _jobActionAdapter.setNewData(null);
                        _jobActionAdapter.setEmptyView(R.layout.layout_empty_data, (ViewGroup) _orderRecycler.getParent());
                    }
                } else {
                    if (isNeedHandlerExit) {
                        Intent intent = new Intent();
                        intent.putExtra("isNeedHandlerExit", isNeedHandlerExit);
                        setResult(20001, intent);

                        finish();

                        return;
                    }
                    _jobActionAdapter.setNewData(null);
                    _jobActionAdapter.setEmptyView(R.layout.layout_empty_data, (ViewGroup) _orderRecycler.getParent());
                }

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                if (e.toString().contains("4003")) {
                    if (isNeedHandlerExit) {
                        Intent intent = new Intent();
                        intent.putExtra("isNeedHandlerExit", isNeedHandlerExit);
                        setResult(20001, intent);

                        finish();

                        return;
                    }
                }
            }
        };

        CarApiManager.getInstance().sendRequest(HttpData.InterfacesURL.ASSIGN_PICK_GOODS_ORDER_LIST, ss,
                HttpData.getEmptyData());
    }

    private void sendRequestForFinishDeliver(final boolean isNeedHandlerExit) {
        MySubscriber<NetMessageVO> ss = new MySubscriber<NetMessageVO>() {
            @Override
            public void onNext(NetMessageVO o) {
                _orders.clear();
                Task task = ParseJsonUtils.getObjectFromJson(o.data, Task.class);
                List<DeliverAddress> deliverAddresses = task.getDeliverAddressGroupList();

                if (deliverAddresses != null && deliverAddresses.size() > 0) {
                    for (int i = 0; i < deliverAddresses.size(); i ++) {
                        if (_groupKey.equals(deliverAddresses.get(i).getGroupKey())) {
                            _orders = deliverAddresses.get(i).getDeliverOrderList();
                        }
                    }

                    if (_orders != null && _orders.size() > 0 ) {
                        _jobActionAdapter.setNewData(_orders);

                    } else {
                        if (isNeedHandlerExit) {
                            finish();
                        }
                        _jobActionAdapter.setNewData(null);
                        _jobActionAdapter.setEmptyView(R.layout.layout_empty_data, (ViewGroup) _orderRecycler.getParent());
                    }
                } else {
                    if (isNeedHandlerExit) {
                        Intent intent = new Intent();
                        intent.putExtra("isNeedHandlerExit", isNeedHandlerExit);
                        setResult(20001, intent);

                        finish();

                        return;
                    }
                    _jobActionAdapter.setNewData(null);
                    _jobActionAdapter.setEmptyView(R.layout.layout_empty_data, (ViewGroup) _orderRecycler.getParent());
                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);

                if (e.toString().contains("4003")) {
                    if (isNeedHandlerExit) {
                        Intent intent = new Intent();
                        intent.putExtra("isNeedHandlerExit", isNeedHandlerExit);
                        setResult(20001, intent);

                        finish();

                        return;
                    }
                }
            }
        };

        CarApiManager.getInstance().sendRequest(HttpData.InterfacesURL.ASSIGN_DELIVER_ORDER_LIST, ss,
                HttpData.getEmptyData());
    }
}


text:
package org.apache.ignite.internal.processors.query.calcite.integration;

import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.rel.RelCollation;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.util.ImmutableBitSet;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.cache.QueryEntity;
import org.apache.ignite.cache.query.FieldsQueryCursor;
import org.apache.ignite.cache.query.QueryCursor;
import org.apache.ignite.cache.query.annotations.QuerySqlField;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.processors.query.QueryEngine;
import org.apache.ignite.internal.processors.query.calcite.CalciteQueryProcessor;
import org.apache.ignite.internal.processors.query.calcite.QueryChecker;
import org.apache.ignite.internal.processors.query.calcite.exec.ExecutionContext;
import org.apache.ignite.internal.processors.query.calcite.metadata.ColocationGroup;
import org.apache.ignite.internal.processors.query.calcite.rel.logical.IgniteLogicalIndexScan;
import org.apache.ignite.internal.processors.query.calcite.schema.IgniteIndex;
import org.apache.ignite.internal.processors.query.calcite.schema.IgniteTable;
import org.apache.ignite.internal.processors.query.calcite.util.Commons;
import org.apache.ignite.internal.processors.query.calcite.util.IndexConditions;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.G;
import org.apache.ignite.testframework.junits.WithSystemProperty;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.jetbrains.annotations.Nullable;

import static org.apache.ignite.testframework.GridTestUtils.assertThrowsAnyCause;
import static org.apache.ignite.testframework.GridTestUtils.waitForCondition;

/**
 *
 */
@WithSystemProperty(key = "calcite.debug", value = "false")
public class AbstractBasicIntegrationTest extends GridCommonAbstractTest {
    /** */
    protected static final String TABLE_NAME = "person";

    /** */
    protected static IgniteEx client;

    /** {@inheritDoc} */
    @Override protected void beforeTestsStarted() throws Exception {
        startGrids(nodeCount());

        client = startClientGrid("client");
    }

    /** {@inheritDoc} */
    @Override protected void afterTest() throws Exception {
        // Wait for pending queries before destroying caches. If some error occurs during query execution, client code
        // can get control earlier than query leave the running queries registry (need some time for async message
        // exchange), but eventually, all queries should be closed.
        assertTrue("Not finished queries found on client", waitForCondition(
            () -> queryProcessor(client).queryRegistry().runningQueries().isEmpty(), 1_000L));

        for (Ignite ign : G.allGrids()) {
            for (String cacheName : ign.cacheNames())
                ign.destroyCache(cacheName);

            assertEquals("Not finished queries found [ignite=" + ign.name() + ']',
                0, queryProcessor((IgniteEx)ign).queryRegistry().runningQueries().size());
        }

        awaitPartitionMapExchange();

        cleanQueryPlanCache();
    }

    /** */
    protected int nodeCount() {
        return 3;
    }

    /** */
    protected void cleanQueryPlanCache() {
        for (Ignite ign : G.allGrids()) {
            CalciteQueryProcessor qryProc = (CalciteQueryProcessor)Commons.lookupComponent(
                ((IgniteEx)ign).context(), QueryEngine.class);

            qryProc.queryPlanCache().clear();
        }
    }

    /** */
    protected QueryChecker assertQuery(String qry) {
        return assertQuery(client, qry);
    }

    /** */
    protected QueryChecker assertQuery(IgniteEx ignite, String qry) {
        return new QueryChecker(qry) {
            @Override protected QueryEngine getEngine() {
                return Commons.lookupComponent(ignite.context(), QueryEngine.class);
            }
        };
    }

    /** */
    protected List<List<?>> executeSql(String sql, Object... args) {
        CalciteQueryProcessor qryProc = Commons.lookupComponent(client.context(), CalciteQueryProcessor.class);

        List<FieldsQueryCursor<List<?>>> cur = qryProc.query(null, "PUBLIC", sql, args);

        try (QueryCursor<List<?>> srvCursor = cur.get(0)) {
            return srvCursor.getAll();
        }
    }

    /**
     * Asserts that executeSql throws an exception.
     *
     * @param sql Query.
     * @param cls Exception class.
     * @param msg Error message.
     */
    protected void assertThrows(String sql, Class<? extends Exception> cls, String msg) {
        assertThrowsAnyCause(log, () -> executeSql(sql), cls, msg);
    }

    /** */
    protected IgniteCache<Integer, Employer> createAndPopulateTable() {
        return createAndPopulateTable(2, CacheMode.PARTITIONED);
    }

    /** */
    protected IgniteCache<Integer, Employer> createAndPopulateTable(int backups, CacheMode cacheMode) {
        IgniteCache<Integer, Employer> person = client.getOrCreateCache(new CacheConfiguration<Integer, Employer>()
            .setName(TABLE_NAME)
            .setSqlSchema("PUBLIC")
            .setQueryEntities(F.asList(new QueryEntity(Integer.class, Employer.class).setTableName(TABLE_NAME)))
            .setCacheMode(cacheMode)
            .setBackups(backups)
        );

        int idx = 0;

        person.put(idx++, new Employer("Igor", 10d));
        person.put(idx++, new Employer(null, 15d));
        person.put(idx++, new Employer("Ilya", 15d));
        person.put(idx++, new Employer("Roma", 10d));
        person.put(idx++, new Employer("Roma", 10d));

        return person;
    }

    /** */
    protected CalciteQueryProcessor queryProcessor(IgniteEx ignite) {
        return Commons.lookupComponent(ignite.context(), CalciteQueryProcessor.class);
    }

    /** */
    protected List<List<?>> sql(String sql, Object... params) {
        return sql(client, sql, params);
    }

    /** */
    protected List<List<?>> sql(IgniteEx ignite, String sql, Object... params) {
        List<FieldsQueryCursor<List<?>>> cur = queryProcessor(ignite).query(null, "PUBLIC", sql, params);

        try (QueryCursor<List<?>> srvCursor = cur.get(0)) {
            return srvCursor.getAll();
        }
    }

    /** */
    public static class DelegatingIgniteIndex implements IgniteIndex {
        /** */
        protected final IgniteIndex delegate;

        /** */
        public DelegatingIgniteIndex(IgniteIndex delegate) {
            this.delegate = delegate;
        }

        /** {@inheritDoc} */
        @Override public RelCollation collation() {
            return delegate.collation();
        }

        /** {@inheritDoc} */
        @Override public String name() {
            return delegate.name();
        }

        /** {@inheritDoc} */
        @Override public IgniteTable table() {
            return delegate.table();
        }

        /** {@inheritDoc} */
        @Override public IgniteLogicalIndexScan toRel(
            RelOptCluster cluster,
            RelOptTable relOptTbl,
            @Nullable List<RexNode> proj,
            @Nullable RexNode cond,
            @Nullable ImmutableBitSet requiredColumns
        ) {
            return delegate.toRel(cluster, relOptTbl, proj, cond, requiredColumns);
        }

        /** {@inheritDoc} */
        @Override public IndexConditions toIndexCondition(
            RelOptCluster cluster,
            @Nullable RexNode cond,
            @Nullable ImmutableBitSet requiredColumns
        ) {
            return delegate.toIndexCondition(cluster, cond, requiredColumns);
        }

        /** {@inheritDoc} */
        @Override public <Row> Iterable<Row> scan(
            ExecutionContext<Row> execCtx,
            ColocationGroup grp,
            Predicate<Row> filters,
            Supplier<Row> lowerIdxConditions,
            Supplier<Row> upperIdxConditions,
            Function<Row, Row> rowTransformer,
            @Nullable ImmutableBitSet requiredColumns
        ) {
            return delegate.scan(execCtx, grp, filters, lowerIdxConditions, upperIdxConditions, rowTransformer,
                requiredColumns);
        }

        /** {@inheritDoc} */
        @Override public long count(ExecutionContext<?> ectx, ColocationGroup grp) {
            return delegate.count(ectx, grp);
        }
    }

    /** */
    public static class Employer {
        /** */
        @QuerySqlField
        public String name;

        /** */
        @QuerySqlField
        public Double salary;

        /** */
        public Employer(String name, Double salary) {
            this.name = name;
            this.salary = salary;
        }
    }
}


text:
package control

import (
	"context"

	"bazil.org/bazil/db"
	"bazil.org/bazil/peer"
	wirepeer "bazil.org/bazil/peer/wire"
	"bazil.org/bazil/server/control/wire"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

func (c controlRPC) VolumeConnect(ctx context.Context, req *wire.VolumeConnectRequest) (*wire.VolumeConnectResponse, error) {
	var pub peer.PublicKey
	if err := pub.UnmarshalBinary(req.Pub); err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "bad peer public key: %v", err)
	}

	if err := c.app.ValidateKV(req.Backend); err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "invalid backend: %q", req.Backend)
	}

	client, err := c.app.DialPeer(&pub)
	if err != nil {
		return nil, err
	}
	defer client.Close()
	presp, err := client.VolumeConnect(ctx, &wirepeer.VolumeConnectRequest{
		VolumeName: req.VolumeName,
	})
	if err != nil {
		return nil, err
	}
	var volID db.VolumeID
	if err := volID.UnmarshalBinary(presp.VolumeID); err != nil {
		return nil, err
	}

	volumeConnect := func(tx *db.Tx) error {
		sharingKey, err := tx.SharingKeys().Get(req.SharingKeyName)
		if err != nil {
			return err
		}
		v, err := tx.Volumes().Add(req.LocalVolumeName, &volID, req.Backend, sharingKey)
		if err != nil {
			return err
		}

		p, err := tx.Peers().Get(&pub)
		if err != nil {
			return err
		}
		if err := p.Volumes().Allow(v); err != nil {
			return err
		}

		return nil
	}
	if err := c.app.DB.Update(volumeConnect); err != nil {
		switch err {
		case db.ErrVolNameInvalid:
			return nil, status.Errorf(codes.InvalidArgument, "%v", err)
		case db.ErrVolNameExist:
			return nil, status.Errorf(codes.AlreadyExists, "%v", err)
		case db.ErrSharingKeyNameInvalid:
			return nil, status.Errorf(codes.InvalidArgument, "%v", err)
		case db.ErrSharingKeyNotFound:
			return nil, status.Errorf(codes.FailedPrecondition, "%v", err)
		}
		return nil, err
	}
	return &wire.VolumeConnectResponse{}, nil
}


text:
package apple.coretext.struct;

import org.moe.natj.c.StructObject;
import org.moe.natj.c.ann.Structure;
import org.moe.natj.c.ann.StructureField;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.Generated;

@Generated
@Structure()
public final class SFNTLookupSegment extends StructObject {
    private static long __natjCache;

    static {
        NatJ.register();
    }

    @Generated
    public SFNTLookupSegment() {
        super(SFNTLookupSegment.class);
    }

    @Generated
    protected SFNTLookupSegment(Pointer peer) {
        super(peer);
    }

    @Generated
    public SFNTLookupSegment(char lastGlyph, char firstGlyph, char value) {
        super(SFNTLookupSegment.class);
        setLastGlyph(lastGlyph);
        setFirstGlyph(firstGlyph);
        setValue(value);
    }

    @Generated
    @StructureField(order = 0, isGetter = true)
    public native char lastGlyph();

    @Generated
    @StructureField(order = 0, isGetter = false)
    public native void setLastGlyph(char value);

    @Generated
    @StructureField(order = 1, isGetter = true)
    public native char firstGlyph();

    @Generated
    @StructureField(order = 1, isGetter = false)
    public native void setFirstGlyph(char value);

    @Generated
    @StructureField(order = 2, isGetter = true)
    public native char value();

    @Generated
    @StructureField(order = 2, isGetter = false)
    public native void setValue(char value);
}


text:
/*jslint node:true*/
'use strict';

var util = require('../../core/util');
var mysql = require('../../core/mysql');
var router = require('express').Router();

// 1. List of All Users [/apis/user/all]
router.get('/all', util.checkAdmin, function (request, response) {
    try {
        var connection = mysql.getConnection();
        mysql.transaction([
            function(callback) {
                connection.query("SELECT * FROM `user` ORDER BY `name`", callback);
            }
        ], connection, function(error, users) {
            if(error) return response.status(500).send("Unable to fetch users.");
            return response.status(200).send(JSON.stringify(users));
        });
    } catch(exception) {
        console.log("Error occurred while fetching all users: " + exception);
        console.log("Error Stack Trace: " + exception.stack);
        return response.status(500).send("Unknown Error Occurred. Contact Technical Administrator.");
    }
});

// 2. List of Active Users [/apis/user/active]
router.get('/active', util.checkActiveUser, function (request, response) {
    try {
        var connection = mysql.getConnection();
        mysql.transaction([
            function(callback) {
                connection.query("SELECT * FROM `user` WHERE `suspended` = 0 AND `admin` = 0", callback);
            }
        ], connection, function(error, users) {
            if(error) return response.status(500).send("Unable to fetch users.");
            return response.status(200).send(JSON.stringify(users));
        });
    } catch(exception) {
        console.log("Error occurred while fetching all active users: " + exception);
        console.log("Error Stack Trace: " + exception.stack);
        return response.status(500).send("Unknown Error Occurred. Contact Technical Administrator.");
    }
});

router.get('/activeadm', util.checkAdmin, function (request, response) {
    try {
        var connection = mysql.getConnection();
        mysql.transaction([
            function(callback) {
                connection.query("SELECT * FROM `user` WHERE `suspended` = 0 AND `admin` = 0 ORDER BY `balance` DESC, `name` ASC", callback);
            }
        ], connection, function(error, users) {
            if(error) return response.status(500).send("Unable to fetch users.");
            return response.status(200).send(JSON.stringify(users));
        });
    } catch(exception) {
        console.log("Error occurred while fetching all active users: " + exception);
        console.log("Error Stack Trace: " + exception.stack);
        return response.status(500).send("Unknown Error Occurred. Contact Technical Administrator.");
    }
});

// 3. Activate User with Activation Code [Directly from mail] [/apis/user/activate/:user/:code]
router.get('/activate/:user/:code', function (request, response) {
    var message = null;
    try {
        var userId = request.params.user ? request.params.user : '';
        var code = request.params.code ? request.params.code : '';

        var connection = mysql.getConnection();
        mysql.transaction([
            function(callback) {
                connection.query("UPDATE `user` SET `suspended` = 0 WHERE `id` = ? AND `activateCode` = ?", [userId, code], callback);
            }
        ], connection, function(error) {
            if(error) return response.status(500).send("Activation Failed.");
            return response.status(200).send("User Activated");
        });
    } catch(exception) {
        if(exception !== message) {
            console.log("Error occurred while activating user via GET request: " + exception);
            console.log("Error Stack Trace: " + exception.stack);
            exception = "Unknown Error Occurred. Contact Technical Administrator.";
        }
        return response.status(500).send(exception);
    }
});

// 4. Activate User via Admin Login [/apis/user/activate]
router.post('/activate', util.checkAdmin, function (request, response) {
    var message = null;
    try {
        var data = request.body ? request.body : undefined;
        if (!data || !data.userId) {
            message = "Provide UserId";
            throw message;
        }

        var connection = mysql.getConnection();
        mysql.transaction([
            function(callback) {
                connection.query("UPDATE `user` SET `suspended` = 0 WHERE `id` = ?", data.userId, callback);
            }
        ], connection, function(error) {
            if(error) return response.status(500).send("Activation Failed.");
            return response.status(200).send("User Activated");
        });
    } catch(exception) {
        if(exception !== message) {
            console.log("Error occurred while activating user: " + exception);
            console.log("Error Stack Trace: " + exception.stack);
            exception = "Unknown Error Occurred. Contact Technical Administrator.";
        }
        return response.status(500).send(exception);
    }
});

// 5. Deactivate User via Admin Login [/apis/user/deactivate]
router.post('/deactivate', util.checkAdmin, function (request, response) {
    var message = null;
    try {
        var data = request.body ? request.body : undefined;
        if (!data || !data.userId) {
            message = "Provide UserId";
            throw message;
        }

        var connection = mysql.getConnection();
        mysql.transaction([
            function(callback) {
                connection.query("UPDATE `user` SET `suspended` = 1 WHERE `id` = ?", data.userId, callback);
            }
        ], connection, function(error) {
            if(error) return response.status(500).send("Deactivation Failed.");
            return response.status(200).send("User Deactivated");
        });
    } catch(exception) {
        if(exception !== message) {
            console.log("Error occurred while deactivating user: " + exception);
            console.log("Error Stack Trace: " + exception.stack);
            exception = "Unknown Error Occurred. Contact Technical Administrator.";
        }
        return response.status(500).send(exception);
    }
});

// 6. User Balance Over period of 'x' days
router.get('/balance/:days', util.checkUser, function (request, response) {
    var message = null;
    try {
        message = "Invalid Number of Days";
        var days = util.checkInteger(request.params.days, message);

        var date = new Date();
        var startTime = new Date(date.getFullYear(), date.getMonth(), date.getDate() - days, 5, 30, 0);
        var endTime = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1, 5, 29, 59);
        var oneDayInMs = 1 * 24 * 60 * 60 * 1000;

        var connection = mysql.getConnection();
        mysql.transaction([
            function(callback) {
                connection.query("SELECT * FROM `transaction` WHERE (`from` = ? OR `to` = ?) AND `time` >= ? AND `time` <= ? ORDER BY `time` DESC, `balanceFrom` ASC, `balanceTo` DESC", [request.user.id, request.user.id, util.getSQLDate(startTime), util.getSQLDate(endTime)], callback);
            },
            function(transactions) {
                var callback = arguments[arguments.length-1];
                var result = { x: [], y: [] };
                var x = endTime.getTime();
                transactions.forEach(transaction => {
                    if (x >= transaction.time.getTime()) {
                        var readableDate = util.getReadableFixture(new Date(x)).date;
                        result.x.push(readableDate.slice(0, readableDate.lastIndexOf('-')));
                        if (transaction.from && transaction.from === request.user.id) result.y.push(transaction.balanceFrom);
                        else result.y.push(transaction.balanceTo);
                        x -= oneDayInMs;
                    }
                });

                result.x.reverse();
                result.y.reverse();

                callback(null, result);
            }
        ], connection, function(error, result) {
            if(error) return response.status(500).send("Unable to fetch transaction history");
            return response.status(200).send(JSON.stringify(result));
        });
    } catch(exception) {
        if(exception !== message) {
            console.log("Error occurred while fetching history of balance over a period: " + exception);
            console.log("Error Stack Trace: " + exception.stack);
            exception = "Unknown Error Occurred. Contact Technical Administrator.";
        }
        return response.status(500).send(exception);
    }
});

// 7. Leading Players
router.get('/leaderboard', function(request, response) {
    try {
        var top = 3;
        var connection = mysql.getConnection();
        mysql.transaction([
            function(callback) {
                connection.query("SELECT u.`name` FROM `user` u WHERE u.`suspended` = 0 AND u.`admin` = 0 ORDER BY u.`balance` DESC LIMIT ?", top, callback);
            }
        ], connection, function(error, users) {
            if(error) return response.status(500).send("Error while fetching leaderboard: " + error);
            return response.status(200).send(JSON.stringify(users));
        });
    } catch(exception) {
        console.log("Error occurred while fetching the leaderboard: " + exception);
        console.log("Error Stack Trace: " + exception.stack);
        return response.status(500).send(exception);
    }
});

module.exports = router;