text:
module(..., package.seeall)
local itemsSelected = 0
-----------------
-- Helper function for newButton utility function below
local function newButtonHandler( self, event )

	local result = true

	local default = self[1]
	local over = self[2]

	--ADDED TOGGLE IBOBX
	local checked = self[3]
	--ADDED TOGGLE IBOBX

	-- General "onEvent" function overrides onPress and onRelease, if present
	local onEvent = self._onEvent

	local onPress = self._onPress
	local onRelease = self._onRelease

	local buttonEvent = {}
	if (self._id) then
		buttonEvent.id = self._id
	end

	local phase = event.phase
	if "began" == phase then
		if over then
			default.isVisible = false
			over.isVisible = true
		end

		--ADDED TOGGLE IBOBX
		if checked then

					if(itemsSelected < 5) then
			if self._ischecked==true then
				checked.isVisible = false
			end
		end
	end
		--ADDED TOGGLE IBOBX

		if onEvent then
			buttonEvent.phase = "press"
			result = onEvent( buttonEvent )
		elseif onPress then
			result = onPress( event )
		end

		-- Subsequent touch events will target button even if they are outside the stageBounds of button
		display.getCurrentStage():setFocus( self )
		self.isFocus = true

	elseif self.isFocus then
		local bounds = self.stageBounds
		local x,y = event.x,event.y
		local isWithinBounds =
			bounds.xMin <= x and bounds.xMax >= x and bounds.yMin <= y and bounds.yMax >= y

		if "moved" == phase then
			if over then
				-- The rollover image should only be visible while the finger is within button's stageBounds
				default.isVisible = not isWithinBounds
				over.isVisible = isWithinBounds
			end
		elseif "ended" == phase or "cancelled" == phase then
			if over then
				default.isVisible = true
				over.isVisible = false
			end

			--ADDED TOGGLE IBOBX
			if checked then
				print("togglebutton.ui call")
				if self._ischecked==false then

				--

					if(itemsSelected < 6) then
						itemsSelected = itemsSelected + 1
  					print(itemsSelected .." TOGGLEBUTTON UI CALL")
					default.isVisible = false
					over.isVisible = false
					checked.isVisible = true
					self._ischecked=true
				end
				elseif self._ischecked==true then
					itemsSelected = itemsSelected - 1
  					print(itemsSelected .." TOGGLEBUTTON UI CALL" )
					default.isVisible = true
					over.isVisible = false
					checked.isVisible = false
					self._ischecked=false
				end
			end
			--ADDED TOGGLE IBOBX

			if "ended" == phase then
				-- Only consider this a "click" if the user lifts their finger inside button's stageBounds
				if isWithinBounds then
					if onEvent then
						buttonEvent.phase = "release"
						result = onEvent( buttonEvent )
					elseif onRelease then
						result = onRelease( event )
					end
				end
			end

			-- Allow touch events to be sent normally to the objects they "hit"
			display.getCurrentStage():setFocus( nil )
			self.isFocus = false
		end
	end

	return result
end

---------------
-- Button class

function newButton( params )
	local button, default, over, size, font, textColor, offset
	itemsSelected = 0

	if params.default then
		button = display.newGroup()
		default = display.newImage( params.default )
		button:insert( default, true )
	end

	if params.over then
		over = display.newImage( params.over )
		over.isVisible = false
		button:insert( over, true )
	end

	--ADDED TOGGLE IBOBX
	local checked
	if params.checked then
		checked = display.newImage( params.checked )
		checked.isVisible = false
		button:insert( checked,true )
		button._ischecked=false
	end

	--ADDED TOGGLE IBOBX

	if params.text then

		button.text = params.text -- Added so i could check what text was added to button

		if ( params.size and type(params.size) == "number" ) then size=params.size else size=20 end
		if ( params.font ) then font=params.font else font=native.systemFontBold end
		if ( params.textColor ) then textColor=params.textColor else textColor={ 255, 255, 255, 255 } end

		-- Optional vertical correction for fonts with unusual baselines (I'm looking at you, Zapfino)
		if ( params.offset and type(params.offset) == "number" ) then offset=params.offset else offset = 0 end

		if ( params.emboss ) then
			-- Make the label text look "embossed" (also adjusts effect for textColor brightness)
			local textBrightness = ( textColor[1] + textColor[2] + textColor[3] ) / 3

			local labelHighlight = display.newText( params.text, 0, 0, font, size )
			if ( textBrightness > 127) then
				labelHighlight:setTextColor( 255, 255, 255, 20 )
			else
				labelHighlight:setTextColor( 255, 255, 255, 140 )
			end
			button:insert( labelHighlight, true )
			labelHighlight.x = labelHighlight.x + 1.5; labelHighlight.y = labelHighlight.y + 1.5 + offset

			local labelShadow = display.newText( params.text, 0, 0, font, size )
			if ( textBrightness > 127) then
				labelShadow:setTextColor( 0, 0, 0, 128 )
			else
				labelShadow:setTextColor( 0, 0, 0, 20 )
			end
			button:insert( labelShadow, true )
			labelShadow.x = labelShadow.x - 1; labelShadow.y = labelShadow.y - 1 + offset
		end

		local labelText = display.newText( params.text, 0, 0, font, size )
		labelText:setTextColor( textColor[1], textColor[2], textColor[3], textColor[4] )
		button:insert( labelText, true )
		labelText.y = labelText.y + offset

	end

	if ( params.onPress and ( type(params.onPress) == "function" ) ) then
		button._onPress = params.onPress
	end
	if ( params.onRelease and ( type(params.onRelease) == "function" ) ) then
		button._onRelease = params.onRelease
	end

	if (params.onEvent and ( type(params.onEvent) == "function" ) ) then
		button._onEvent = params.onEvent
	end

	--ADDED TOGGLE IBOBX
	if params.checked then
		button._ischecked = false
	else
		button._ischecked = nil
	end
	-- Public methods
	function button:isChecked() -- return current state
		return self._ischecked
	end

		-- Public methods
	function button:itemsSelected( number) -- return current state
		itemsSelected = number
	end

	function button:itemsSelectedNumber( ) -- return current state
		return itemsSelected
	end

	--ADDED TOGGLE IBOBX

	-- Set button as a table listener by setting a table method and adding the button as its own table listener for "touch" events
	button.touch = newButtonHandler
	button:addEventListener( "touch", button )

	if params.x then
		button.x = params.x
	end

	if params.y then
		button.y = params.y
	end

	if params.id then
		button._id = params.id
	end

	return button
end
--------------
-- Label class

function newLabel( params )
	local labelText
	local size, font, textColor, align
	local t = display.newGroup()

	if ( params.bounds ) then
		local bounds = params.bounds
		local left = bounds[1]
		local top = bounds[2]
		local width = bounds[3]
		local height = bounds[4]

		if ( params.size and type(params.size) == "number" ) then size=params.size else size=20 end
		if ( params.font ) then font=params.font else font=native.systemFontBold end
		if ( params.textColor ) then textColor=params.textColor else textColor={ 255, 255, 255, 255 } end
		if ( params.offset and type(params.offset) == "number" ) then offset=params.offset else offset = 0 end
		if ( params.align ) then align = params.align else align = "center" end

		if ( params.text ) then
			labelText = display.newText( params.text, 0, 0, font, size )
			labelText:setTextColor( textColor[1], textColor[2], textColor[3], textColor[4] )
			t:insert( labelText )
			-- TODO: handle no-initial-text case by creating a field with an empty string?

			if ( align == "left" ) then
				labelText.x = left + labelText.stageWidth * 0.5
			elseif ( align == "right" ) then
				labelText.x = (left + width) - labelText.stageWidth * 0.5
			else
				labelText.x = ((2 * left) + width) * 0.5
			end
		end

		labelText.y = top + labelText.stageHeight * 0.5

		-- Public methods
		function t:setText( newText )
			if ( newText ) then
				labelText.text = newText

				if ( "left" == align ) then
					labelText.x = left + labelText.stageWidth / 2
				elseif ( "right" == align ) then
					labelText.x = (left + width) - labelText.stageWidth / 2
				else
					labelText.x = ((2 * left) + width) / 2
				end
			end
		end

		function t:setTextColor( r, g, b, a )
			local newR = 255
			local newG = 255
			local newB = 255
			local newA = 255

			if ( r and type(r) == "number" ) then newR = r end
			if ( g and type(g) == "number" ) then newG = g end
			if ( b and type(b) == "number" ) then newB = b end
			if ( a and type(a) == "number" ) then newA = a end

			labelText:setTextColor( r, g, b, a )
		end
	end

	-- Return instance (as display group)
	return t

end


text:
namespace QI4N.Framework.Runtime
{
    using System;
    using System.Reflection;

    public class TypedModifierAppliesToFilter : AppliesToFilter
    {
        public bool AppliesTo(MethodInfo method, Type mixin, Type compositeType, Type fragmentClass)
        {
            return method.DeclaringType.IsAssignableFrom(fragmentClass);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
public class Main {
  public static void main(String args[]){
    MainFrame frame = new MainFrame();
    frame.setVisible(true);
  }
}


text:
package org.apache.ignite.internal.processors.rest;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Serializable;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
import net.sf.json.JSONObject;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.CachePeekMode;
import org.apache.ignite.cache.query.SqlQuery;
import org.apache.ignite.cache.query.annotations.QuerySqlField;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.internal.processors.rest.handlers.GridRestCommandHandler;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.testframework.GridTestUtils;

import static org.apache.ignite.IgniteSystemProperties.IGNITE_JETTY_PORT;

/**
 * Tests for Jetty REST protocol.
 */
@SuppressWarnings("unchecked")
public abstract class JettyRestProcessorAbstractSelfTest extends AbstractRestProcessorSelfTest {
    /** Grid count. */
    private static final int GRID_CNT = 3;

    /** {@inheritDoc} */
    @Override protected void beforeTestsStarted() throws Exception {
        System.setProperty(IGNITE_JETTY_PORT, Integer.toString(restPort()));

        super.beforeTestsStarted();

        initCache();
    }

    /** {@inheritDoc} */
    @Override protected void afterTestsStopped() throws Exception {
        super.afterTestsStopped();

        System.clearProperty(IGNITE_JETTY_PORT);
    }

    /** {@inheritDoc} */
    @Override protected void beforeTest() throws Exception {
        grid(0).cache(null).removeAll();
    }

    /** {@inheritDoc} */
    @Override protected int gridCount() {
        return GRID_CNT;
    }

    /**
     * @return Port to use for rest. Needs to be changed over time
     *      because Jetty has some delay before port unbind.
     */
    protected abstract int restPort();

    /**
     * @param params Command parameters.
     * @return Returned content.
     * @throws Exception If failed.
     */
    protected String content(Map<String, String> params) throws Exception {
        String addr = "http://" + LOC_HOST + ":" + restPort() + "/ignite?";

        for (Map.Entry<String, String> e : params.entrySet())
            addr += e.getKey() + '=' + e.getValue() + '&';

        URL url = new URL(addr);

        URLConnection conn = url.openConnection();

        String signature = signature();

        if (signature != null)
            conn.setRequestProperty("X-Signature", signature);

        InputStream in = conn.getInputStream();

        LineNumberReader rdr = new LineNumberReader(new InputStreamReader(in));

        StringBuilder buf = new StringBuilder(256);

        for (String line = rdr.readLine(); line != null; line = rdr.readLine())
            buf.append(line);

        return buf.toString();
    }

    /**
     * @param json JSON response.
     * @param ptrn Pattern to match.
     */
    @SuppressWarnings("TypeMayBeWeakened")
    private void jsonEquals(String json, String ptrn) {
        assertTrue("JSON mismatch [json=" + json + ", ptrn=" + ptrn + ']', Pattern.matches(ptrn, json));
    }

    /**
     * @param res Response.
     * @param success Success flag.
     * @return Regex pattern for JSON.
     */
    private String cachePattern(String res, boolean success) {
        return "\\{\\\"affinityNodeId\\\":\\\"\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12}\\\"\\," +
            "\\\"error\\\":\\\"\\\"\\," +
            "\\\"response\\\":\\\"" + res + "\\\"\\," +
            "\\\"sessionToken\\\":\\\"\\\"," +
            "\\\"successStatus\\\":" + (success ? 0 : 1) + "\\}";
    }

    /**
     * @param err Error.
     * @return Regex pattern for JSON.
     */
    private String errorPattern(String err) {
        return "\\{" +
            "\\\"error\\\":\\\"" + err + "\\\"\\," +
            "\\\"response\\\":null\\," +
            "\\\"sessionToken\\\":\\\"\\\"," +
            "\\\"successStatus\\\":" + 1 + "\\}";
    }

    /**
     * @param res Response.
     * @param success Success flag.
     * @return Regex pattern for JSON.
     */
    private String integerPattern(int res, boolean success) {
        return "\\{\\\"error\\\":\\\"\\\"\\," +
            "\\\"response\\\":" + res + "\\," +
            "\\\"sessionToken\\\":\\\"\\\"," +
            "\\\"successStatus\\\":" + (success ? 0 : 1) + "\\}";
    }

    /**
     * @param res Response.
     * @param success Success flag.
     * @return Regex pattern for JSON.
     */
    private String cacheBulkPattern(String res, boolean success) {
        return "\\{\\\"affinityNodeId\\\":\\\"\\\"\\," +
            "\\\"error\\\":\\\"\\\"\\," +
            "\\\"response\\\":" + res + "\\," +
            "\\\"sessionToken\\\":\\\"\\\"," +
            "\\\"successStatus\\\":" + (success ? 0 : 1) + "\\}";
    }

    /**
     * @param res Response.
     * @param success Success flag.
     * @return Regex pattern for JSON.
     */
    private String cacheBulkPattern(int res, boolean success) {
        return "\\{\\\"affinityNodeId\\\":\\\"\\\"\\," +
            "\\\"error\\\":\\\"\\\"\\," +
            "\\\"response\\\":" + res + "\\," +
            "\\\"sessionToken\\\":\\\"\\\"," +
            "\\\"successStatus\\\":" + (success ? 0 : 1) + "\\}";
    }

    /**
     * @param res Response.
     * @param success Success flag.
     * @return Regex pattern for JSON.
     */
    private String cachePattern(boolean res, boolean success) {
        return "\\{\\\"affinityNodeId\\\":\\\"\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12}\\\"\\," +
            "\\\"error\\\":\\\"\\\"\\," +
            "\\\"response\\\":" + res + "\\," +
            "\\\"sessionToken\\\":\\\"\\\"," +
            "\\\"successStatus\\\":" + (success ? 0 : 1) + "\\}";
    }

    /**
     * @param res Response.
     * @param success Success flag.
     * @return Regex pattern for JSON.
     */
    private String cacheBulkPattern(boolean res, boolean success) {
        return "\\{\\\"affinityNodeId\\\":\\\"\\\"\\," +
            "\\\"error\\\":\\\"\\\"\\," +
            "\\\"response\\\":" + res + "\\," +
            "\\\"sessionToken\\\":\\\"\\\"," +
            "\\\"successStatus\\\":" + (success ? 0 : 1) + "\\}";
    }

    /**
     * @param res Response.
     * @param success Success flag.
     * @return Regex pattern for JSON.
     */
    private String cacheMetricsPattern(String res, boolean success) {
        return "\\{\\\"affinityNodeId\\\":\\\"(\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12})?\\\"\\," +
            "\\\"error\\\":\\\"\\\"\\," +
            "\\\"response\\\":" + res + "\\," +
            "\\\"sessionToken\\\":\\\"\\\"," +
            "\\\"successStatus\\\":" + (success ? 0 : 1) + "\\}";
    }

    /**
     * @param res Response.
     * @param success Success flag.
     * @return Regex pattern for JSON.
     */
    private String pattern(String res, boolean success) {
        return "\\{\\\"error\\\":\\\"" + (!success ? ".+" : "") + "\\\"\\," +
            "\\\"response\\\":" + res + "\\," +
            "\\\"sessionToken\\\":\\\"\\\"," +
            "\\\"successStatus\\\":" + (success ? 0 : 1) + "\\}";
    }

    /**
     * @param res Response.
     * @param success Success flag.
     * @return Regex pattern for JSON.
     */
    private String stringPattern(String res, boolean success) {
        return "\\{\\\"error\\\":\\\"" + (!success ? ".+" : "") + "\\\"\\," +
            "\\\"response\\\":\\\"" + res + "\\\"\\," +
            "\\\"sessionToken\\\":\\\"\\\"," +
            "\\\"successStatus\\\":" + (success ? 0 : 1) + "\\}";
    }

    /**
     * @throws Exception If failed.
     */
    public void testGet() throws Exception {
        jcache().put("getKey", "getVal");

        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_GET.key(), "key", "getKey"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("Get command result: " + ret);

        jsonEquals(ret, cachePattern("getVal", true));
    }

    /**
     * @throws Exception If failed.
     */
    public void testCacheSize() throws Exception {
        jcache().removeAll();

        jcache().put("getKey", "getVal");

        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_SIZE.key()));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("Size command result: " + ret);

        jsonEquals(ret, cacheBulkPattern(1, true));
    }

    /**
     * @throws Exception If failed.
     */
    public void testIgniteName() throws Exception {
        String ret = content(F.asMap("cmd", GridRestCommand.NAME.key()));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("Name command result: " + ret);

        jsonEquals(ret, stringPattern(getTestGridName(0), true));
    }

    /**
     * @throws Exception If failed.
     */
    public void testGetOrCreateCache() throws Exception {
        String ret = content(F.asMap("cmd", GridRestCommand.GET_OR_CREATE_CACHE.key(), "cacheName", "testCache"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("Name command result: " + ret);

        grid(0).cache("testCache").put("1", "1");

        ret = content(F.asMap("cmd", GridRestCommand.DESTROY_CACHE.key(), "cacheName", "testCache"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        assertNull(grid(0).cache("testCache"));
    }

    /**
     * @throws Exception If failed.
     */
    public void testGetAll() throws Exception {
        jcache().put("getKey1", "getVal1");
        jcache().put("getKey2", "getVal2");

        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_GET_ALL.key(), "k1", "getKey1", "k2", "getKey2"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("Get all command result: " + ret);

        jsonEquals(ret,
            // getKey[12] is used since the order is not determined.
            cacheBulkPattern("\\{\\\"getKey[12]\\\":\\\"getVal[12]\\\"\\,\\\"getKey[12]\\\":\\\"getVal[12]\\\"\\}",
                true));
    }

    /**
     * @throws Exception If failed.
     */
    public void testIncorrectPut() throws Exception {
        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_PUT.key(), "key", "key0"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());
        jsonEquals(ret, errorPattern("Failed to find mandatory parameter in request: val"));
    }

    /**
     * @throws Exception If failed.
     */
    public void testContainsKey() throws Exception {
        grid(0).cache(null).put("key0", "val0");

        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_CONTAINS_KEY.key(), "key", "key0"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        jsonEquals(ret, cachePattern(true, true));
    }

    /**
     * @throws Exception If failed.
     */
    public void testContainesKeys() throws Exception {
        grid(0).cache(null).put("key0", "val0");
        grid(0).cache(null).put("key1", "val1");

        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_CONTAINS_KEYS.key(),
            "k1", "key0", "k2", "key1"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        jsonEquals(ret, cacheBulkPattern(true, true));
    }

    /**
     * @throws Exception If failed.
     */
    public void testGetAndPut() throws Exception {
        grid(0).cache(null).put("key0", "val0");

        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_GET_AND_PUT.key(), "key", "key0", "val", "val1"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        jsonEquals(ret, cachePattern("val0", true));

        assertEquals("val1", grid(0).cache(null).get("key0"));
    }

    /**
     * @throws Exception If failed.
     */
    public void testGetAndPutIfAbsent() throws Exception {
        grid(0).cache(null).put("key0", "val0");

        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_GET_AND_PUT_IF_ABSENT.key(),
            "key", "key0", "val", "val1"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        jsonEquals(ret, cachePattern("val0", true));

        assertEquals("val0", grid(0).cache(null).get("key0"));
    }

    /**
     * @throws Exception If failed.
     */
    public void testPutIfAbsent2() throws Exception {
        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_PUT_IF_ABSENT.key(),
            "key", "key0", "val", "val1"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        jsonEquals(ret, cachePattern(true, true));

        assertEquals("val1", grid(0).cache(null).get("key0"));
    }

    /**
     * @throws Exception If failed.
     */
    public void testRemoveValue() throws Exception {
        grid(0).cache(null).put("key0", "val0");

        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_REMOVE_VALUE.key(),
            "key", "key0", "val", "val1"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        jsonEquals(ret, cachePattern(false, true));

        assertEquals("val0", grid(0).cache(null).get("key0"));

        ret = content(F.asMap("cmd", GridRestCommand.CACHE_REMOVE_VALUE.key(),
            "key", "key0", "val", "val0"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        jsonEquals(ret, cachePattern(true, true));

        assertNull(grid(0).cache(null).get("key0"));
    }

    /**
     * @throws Exception If failed.
     */
    public void testGetAndRemove() throws Exception {
        grid(0).cache(null).put("key0", "val0");

        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_GET_AND_REMOVE.key(),
            "key", "key0"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        jsonEquals(ret, cachePattern("val0", true));

        assertNull(grid(0).cache(null).get("key0"));
    }

    /**
     * @throws Exception If failed.
     */
    public void testReplaceValue() throws Exception {
        grid(0).cache(null).put("key0", "val0");

        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_REPLACE_VALUE.key(),
            "key", "key0", "val", "val1", "val2", "val2"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        jsonEquals(ret, cachePattern(false, true));

        assertEquals("val0", grid(0).cache(null).get("key0"));

        ret = content(F.asMap("cmd", GridRestCommand.CACHE_REPLACE_VALUE.key(),
            "key", "key0", "val", "val1", "val2", "val0"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        jsonEquals(ret, cachePattern(true, true));

        assertEquals("val1", grid(0).cache(null).get("key0"));
    }

    /**
     * @throws Exception If failed.
     */
    public void testGetAndReplace() throws Exception {
        grid(0).cache(null).put("key0", "val0");

        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_GET_AND_REPLACE.key(),
            "key", "key0", "val", "val1"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        jsonEquals(ret, cachePattern("val0", true));

        assertEquals("val1", grid(0).cache(null).get("key0"));
    }

    /**
     * @throws Exception If failed.
     */
    public void testPut() throws Exception {
        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_PUT.key(),
            "key", "putKey", "val", "putVal"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("Put command result: " + ret);

        assertEquals("putVal", jcache().localPeek("putKey", CachePeekMode.ONHEAP));

        jsonEquals(ret, cachePattern(true, true));
    }

    /**
     * @throws Exception If failed.
     */
    public void testPutWithExpiration() throws Exception {
        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_PUT.key(),
            "key", "putKey", "val", "putVal", "exp", "2000"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        jsonEquals(ret, cachePattern(true, true));

        assertEquals("putVal", jcache().get("putKey"));

        Thread.sleep(2100);

        assertNull(jcache().get("putKey"));
    }

    /**
     * @throws Exception If failed.
     */
    public void testAdd() throws Exception {
        jcache().put("addKey1", "addVal1");

        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_ADD.key(),
            "key", "addKey2", "val", "addVal2"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        jsonEquals(ret, cachePattern(true, true));

        assertEquals("addVal1", jcache().localPeek("addKey1", CachePeekMode.ONHEAP));
        assertEquals("addVal2", jcache().localPeek("addKey2", CachePeekMode.ONHEAP));
    }

    /**
     * @throws Exception If failed.
     */
    public void testAddWithExpiration() throws Exception {
        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_ADD.key(),
            "key", "addKey", "val", "addVal", "exp", "2000"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        jsonEquals(ret, cachePattern(true, true));

        assertEquals("addVal", jcache().get("addKey"));

        Thread.sleep(2100);

        assertNull(jcache().get("addKey"));
    }

    /**
     * @throws Exception If failed.
     */
    public void testPutAll() throws Exception {
        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_PUT_ALL.key(),
            "k1", "putKey1", "k2", "putKey2",
            "v1", "putVal1", "v2", "putVal2"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("Put all command result: " + ret);

        assertEquals("putVal1", jcache().localPeek("putKey1", CachePeekMode.ONHEAP));
        assertEquals("putVal2", jcache().localPeek("putKey2", CachePeekMode.ONHEAP));

        jsonEquals(ret, cacheBulkPattern(true, true));
    }

    /**
     * @throws Exception If failed.
     */
    public void testRemove() throws Exception {
        jcache().put("rmvKey", "rmvVal");

        assertEquals("rmvVal", jcache().localPeek("rmvKey", CachePeekMode.ONHEAP));

        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_REMOVE.key(),
            "key", "rmvKey"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("Remove command result: " + ret);

        assertNull(jcache().localPeek("rmvKey", CachePeekMode.ONHEAP));

        jsonEquals(ret, cachePattern(true, true));
    }

    /**
     * @throws Exception If failed.
     */
    public void testRemoveAll() throws Exception {
        jcache().put("rmvKey1", "rmvVal1");
        jcache().put("rmvKey2", "rmvVal2");
        jcache().put("rmvKey3", "rmvVal3");
        jcache().put("rmvKey4", "rmvVal4");

        assertEquals("rmvVal1", jcache().localPeek("rmvKey1", CachePeekMode.ONHEAP));
        assertEquals("rmvVal2", jcache().localPeek("rmvKey2", CachePeekMode.ONHEAP));
        assertEquals("rmvVal3", jcache().localPeek("rmvKey3", CachePeekMode.ONHEAP));
        assertEquals("rmvVal4", jcache().localPeek("rmvKey4", CachePeekMode.ONHEAP));

        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_REMOVE_ALL.key(),
            "k1", "rmvKey1", "k2", "rmvKey2"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("Remove all command result: " + ret);

        assertNull(jcache().localPeek("rmvKey1", CachePeekMode.ONHEAP));
        assertNull(jcache().localPeek("rmvKey2", CachePeekMode.ONHEAP));
        assertEquals("rmvVal3", jcache().localPeek("rmvKey3", CachePeekMode.ONHEAP));
        assertEquals("rmvVal4", jcache().localPeek("rmvKey4", CachePeekMode.ONHEAP));

        jsonEquals(ret, cacheBulkPattern(true, true));

        ret = content(F.asMap("cmd", GridRestCommand.CACHE_REMOVE_ALL.key()));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("Remove all command result: " + ret);

        assertNull(jcache().localPeek("rmvKey1", CachePeekMode.ONHEAP));
        assertNull(jcache().localPeek("rmvKey2", CachePeekMode.ONHEAP));
        assertNull(jcache().localPeek("rmvKey3", CachePeekMode.ONHEAP));
        assertNull(jcache().localPeek("rmvKey4", CachePeekMode.ONHEAP));
        assertTrue(jcache().localSize() == 0);

        jsonEquals(ret, cacheBulkPattern(true, true));
    }

    /**
     * @throws Exception If failed.
     */
    public void testCas() throws Exception {
        jcache().put("casKey", "casOldVal");

        assertEquals("casOldVal", jcache().localPeek("casKey", CachePeekMode.ONHEAP));

        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_CAS.key(),
            "key", "casKey", "val2", "casOldVal", "val1", "casNewVal"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("CAS command result: " + ret);

        assertEquals("casNewVal", jcache().localPeek("casKey", CachePeekMode.ONHEAP));

        jsonEquals(ret, cachePattern(true, true));

        jcache().remove("casKey");
    }

    /**
     * @throws Exception If failed.
     */
    public void testReplace() throws Exception {
        jcache().put("repKey", "repOldVal");

        assertEquals("repOldVal", jcache().localPeek("repKey", CachePeekMode.ONHEAP));

        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_REPLACE.key(),
            "key", "repKey", "val", "repVal"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("Replace command result: " + ret);

        assertEquals("repVal", jcache().localPeek("repKey", CachePeekMode.ONHEAP));

        jsonEquals(ret, cachePattern(true, true));
    }

    /**
     * @throws Exception If failed.
     */
    public void testReplaceWithExpiration() throws Exception {
        jcache().put("replaceKey", "replaceVal");

        assertEquals("replaceVal", jcache().get("replaceKey"));

        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_REPLACE.key(),
            "key", "replaceKey", "val", "replaceValNew", "exp", "2000"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        jsonEquals(ret, cachePattern(true, true));

        assertEquals("replaceValNew", jcache().get("replaceKey"));

        // Use larger value to avoid false positives.
        Thread.sleep(2100);

        assertNull(jcache().get("replaceKey"));
    }

    /**
     * @throws Exception If failed.
     */
    public void testAppend() throws Exception {
        jcache().put("appendKey", "appendVal");

        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_APPEND.key(),
            "key", "appendKey", "val", "_suffix"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        jsonEquals(ret, cachePattern(true, true));

        assertEquals("appendVal_suffix", jcache().get("appendKey"));
    }

    /**
     * @throws Exception If failed.
     */
    public void testPrepend() throws Exception {
        jcache().put("prependKey", "prependVal");

        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_PREPEND.key(),
            "key", "prependKey", "val", "prefix_"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        jsonEquals(ret, cachePattern(true, true));

        assertEquals("prefix_prependVal", jcache().get("prependKey"));
    }

    /**
     * @throws Exception If failed.
     */
    public void testIncrement() throws Exception {
        String ret = content(F.asMap("cmd", GridRestCommand.ATOMIC_INCREMENT.key(),
            "key", "incrKey", "init", "2", "delta", "3"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        jsonEquals(ret, integerPattern(5, true));

        assertEquals(5, grid(0).atomicLong("incrKey", 0, true).get());

        ret = content(F.asMap("cmd", GridRestCommand.ATOMIC_INCREMENT.key(), "key", "incrKey", "delta", "10"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        jsonEquals(ret, integerPattern(15, true));

        assertEquals(15, grid(0).atomicLong("incrKey", 0, true).get());
    }

    /**
     * @throws Exception If failed.
     */
    public void testDecrement() throws Exception {
        String ret = content(F.asMap("cmd", GridRestCommand.ATOMIC_DECREMENT.key(),
            "key", "decrKey", "init", "15", "delta", "10"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        jsonEquals(ret, integerPattern(5, true));

        assertEquals(5, grid(0).atomicLong("decrKey", 0, true).get());

        ret = content(F.asMap("cmd", GridRestCommand.ATOMIC_DECREMENT.key(),
            "key", "decrKey", "delta", "3"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        jsonEquals(ret, integerPattern(2, true));

        assertEquals(2, grid(0).atomicLong("decrKey", 0, true).get());
    }

    /**
     * @throws Exception If failed.
     */
    public void testCar() throws Exception {
        jcache().put("casKey", "casOldVal");

        assertEquals("casOldVal", jcache().localPeek("casKey", CachePeekMode.ONHEAP));

        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_CAS.key(),
            "key", "casKey", "val2", "casOldVal"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("CAR command result: " + ret);

        assertNull(jcache().localPeek("casKey", CachePeekMode.ONHEAP));

        jsonEquals(ret, cachePattern(true, true));
    }

    /**
     * @throws Exception If failed.
     */
    public void testPutIfAbsent() throws Exception {
        assertNull(jcache().localPeek("casKey", CachePeekMode.ONHEAP));

        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_CAS.key(),
            "key", "casKey", "val1", "casNewVal"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("PutIfAbsent command result: " + ret);

        assertEquals("casNewVal", jcache().localPeek("casKey", CachePeekMode.ONHEAP));

        jsonEquals(ret, cachePattern(true, true));
    }

    /**
     * @throws Exception If failed.
     */
    public void testCasRemove() throws Exception {
        jcache().put("casKey", "casVal");

        assertEquals("casVal", jcache().localPeek("casKey", CachePeekMode.ONHEAP));

        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_CAS.key(), "key", "casKey"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("CAS Remove command result: " + ret);

        assertNull(jcache().localPeek("casKey", CachePeekMode.ONHEAP));

        jsonEquals(ret, cachePattern(true, true));
    }

    /**
     * @throws Exception If failed.
     */
    public void testMetrics() throws Exception {
        String ret = content(F.asMap("cmd", GridRestCommand.CACHE_METRICS.key()));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("Cache metrics command result: " + ret);

        jsonEquals(ret, cacheMetricsPattern("\\{.+\\}", true));
    }

    /**
     * @throws Exception If failed.
     */
    public void testTopology() throws Exception {
        String ret = content(F.asMap("cmd", GridRestCommand.TOPOLOGY.key(), "attr", "false", "mtr", "false"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("Topology command result: " + ret);

        jsonEquals(ret, pattern("\\[\\{.+\\}\\]", true));
    }

    /**
     * @throws Exception If failed.
     */
    public void testNode() throws Exception {
        String ret = content(F.asMap("cmd", GridRestCommand.NODE.key(), "attr", "true", "mtr", "true", "id",
            grid(0).localNode().id().toString()));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("Topology command result: " + ret);

        jsonEquals(ret, pattern("\\{.+\\}", true));

        ret = content(F.asMap("cmd", GridRestCommand.NODE.key(), "attr", "false", "mtr", "false", "ip", LOC_HOST));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("Topology command result: " + ret);

        jsonEquals(ret, pattern("\\{.+\\}", true));

        ret = content(F.asMap("cmd", GridRestCommand.NODE.key(), "attr", "false", "mtr", "false", "ip", LOC_HOST, "id",
            UUID.randomUUID().toString()));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("Topology command result: " + ret);

        jsonEquals(ret, pattern("null", true));
    }

    /**
     * Tests {@code exe} command.
     * <p>
     * Note that attempt to execute unknown task (UNKNOWN_TASK) will result in exception on server.
     *
     * @throws Exception If failed.
     */
    public void testExe() throws Exception {
        String ret = content(F.asMap("cmd", GridRestCommand.EXE.key()));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("Exe command result: " + ret);

        jsonEquals(ret, pattern("null", false));

        // Attempt to execute unknown task (UNKNOWN_TASK) will result in exception on server.
        ret = content(F.asMap("cmd", GridRestCommand.EXE.key(), "name", "UNKNOWN_TASK"));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("Exe command result: " + ret);

        jsonEquals(ret, pattern("null", false));

        grid(0).compute().localDeployTask(TestTask1.class, TestTask1.class.getClassLoader());
        grid(0).compute().localDeployTask(TestTask2.class, TestTask2.class.getClassLoader());

        ret = content(F.asMap("cmd", GridRestCommand.EXE.key(), "name", TestTask1.class.getName()));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("Exe command result: " + ret);

        jsonEquals(ret, pattern("\\{.+\\}", true));

        ret = content(F.asMap("cmd", GridRestCommand.EXE.key(), "name", TestTask2.class.getName()));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("Exe command result: " + ret);

        jsonEquals(ret, pattern("\\{.+" + TestTask2.RES + ".+\\}", true));

        ret = content(F.asMap("cmd", GridRestCommand.RESULT.key()));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        info("Exe command result: " + ret);

        jsonEquals(ret, pattern("null", false));
    }

    /**
     * @throws Exception If failed.
     */
    public void testVersion() throws Exception {
        String ret = content(F.asMap("cmd", GridRestCommand.VERSION.key()));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        jsonEquals(ret, stringPattern(".+", true));
    }

    /**
     * @throws Exception If failed.
     */
    public void testQueryArgs() throws Exception {
        String qry = "salary > ? and salary <= ?";

        Map<String, String> params = new HashMap<>();
        params.put("cmd", GridRestCommand.EXECUTE_SQL_QUERY.key());
        params.put("type", "Person");
        params.put("pageSize", "10");
        params.put("cacheName", "person");
        params.put("qry", URLEncoder.encode(qry));
        params.put("arg1", "1000");
        params.put("arg2", "2000");

        String ret = content(params);

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        JSONObject json = JSONObject.fromObject(ret);

        List items = (List)((Map)json.get("response")).get("items");

        assertEquals(2, items.size());

        assertFalse(queryCursorFound());
    }

    /**
     * @throws Exception If failed.
     */
    public void testQuery() throws Exception {
        grid(0).cache(null).put("1", "1");
        grid(0).cache(null).put("2", "2");
        grid(0).cache(null).put("3", "3");

        Map<String, String> params = new HashMap<>();
        params.put("cmd", GridRestCommand.EXECUTE_SQL_QUERY.key());
        params.put("type", "String");
        params.put("pageSize", "1");
        params.put("qry", URLEncoder.encode("select * from String"));

        String ret = content(params);

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        JSONObject json = JSONObject.fromObject(ret);

        Integer qryId = (Integer)((Map)json.get("response")).get("queryId");

        assertNotNull(qryId);

        ret = content(F.asMap("cmd", GridRestCommand.FETCH_SQL_QUERY.key(),
            "pageSize", "1", "qryId", String.valueOf(qryId)));

        json = JSONObject.fromObject(ret);

        Integer qryId0 = (Integer)((Map)json.get("response")).get("queryId");

        Boolean last = (Boolean)((Map)json.get("response")).get("last");

        assertEquals(qryId0, qryId);
        assertFalse(last);

        ret = content(F.asMap("cmd", GridRestCommand.FETCH_SQL_QUERY.key(),
            "pageSize", "1", "qryId", String.valueOf(qryId)));

        json = JSONObject.fromObject(ret);

        qryId0 = (Integer)((Map)json.get("response")).get("queryId");

        last = (Boolean)((Map)json.get("response")).get("last");

        assertEquals(qryId0, qryId);
        assertTrue(last);

        assertFalse(queryCursorFound());
    }

    /**
     * @throws Exception If failed.
     */
    public void testSqlFieldsQuery() throws Exception {
        String qry = "select concat(firstName, ' ', lastName) from Person";

        Map<String, String> params = new HashMap<>();
        params.put("cmd", GridRestCommand.EXECUTE_SQL_FIELDS_QUERY.key());
        params.put("pageSize", "10");
        params.put("cacheName", "person");
        params.put("qry", URLEncoder.encode(qry));

        String ret = content(params);

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        JSONObject json = JSONObject.fromObject(ret);

        List items = (List)((Map)json.get("response")).get("items");

        assertEquals(4, items.size());

        assertFalse(queryCursorFound());
    }

    /**
     * @throws Exception If failed.
     */
    public void testSqlFieldsMetadataQuery() throws Exception {
        String qry = "select firstName, lastName from Person";

        Map<String, String> params = new HashMap<>();
        params.put("cmd", GridRestCommand.EXECUTE_SQL_FIELDS_QUERY.key());
        params.put("pageSize", "10");
        params.put("cacheName", "person");
        params.put("qry", URLEncoder.encode(qry));

        String ret = content(params);

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        JSONObject json = JSONObject.fromObject(ret);

        List items = (List)((Map)json.get("response")).get("items");

        List meta = (List)((Map)json.get("response")).get("fieldsMetadata");

        assertEquals(4, items.size());

        assertEquals(2, meta.size());

        JSONObject o = (JSONObject)meta.get(0);

        assertEquals("FIRSTNAME", o.get("fieldName"));
        assertEquals("java.lang.String", o.get("fieldTypeName"));
        assertEquals("person", o.get("schemaName"));
        assertEquals("PERSON", o.get("typeName"));

        assertFalse(queryCursorFound());
    }

    /**
     * @throws Exception If failed.
     */
    public void testQueryClose() throws Exception {
        String qry = "salary > ? and salary <= ?";

        Map<String, String> params = new HashMap<>();
        params.put("cmd", GridRestCommand.EXECUTE_SQL_QUERY.key());
        params.put("type", "Person");
        params.put("pageSize", "1");
        params.put("cacheName", "person");
        params.put("qry", URLEncoder.encode(qry));
        params.put("arg1", "1000");
        params.put("arg2", "2000");

        String ret = content(params);

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        JSONObject json = JSONObject.fromObject(ret);

        List items = (List)((Map)json.get("response")).get("items");

        assertEquals(1, items.size());

        assertTrue(queryCursorFound());

        Integer qryId = (Integer)((Map)json.get("response")).get("queryId");

        assertNotNull(qryId);

        ret = content(F.asMap("cmd", GridRestCommand.CLOSE_SQL_QUERY.key(),
            "cacheName", "person", "qryId", String.valueOf(qryId)));

        assertNotNull(ret);
        assertTrue(!ret.isEmpty());

        assertFalse(queryCursorFound());
    }

    protected abstract String signature() throws Exception;

    /**
     * @return True if any query cursor is available.
     */
    private boolean queryCursorFound() {
        boolean found = false;

        for (int i = 0; i < GRID_CNT; ++i) {
            Map<GridRestCommand, GridRestCommandHandler> handlers =
                GridTestUtils.getFieldValue(grid(i).context().rest(), "handlers");

            GridRestCommandHandler qryHnd = handlers.get(GridRestCommand.CLOSE_SQL_QUERY);

            ConcurrentHashMap<Long, Iterator> its = GridTestUtils.getFieldValue(qryHnd, "qryCurs");

            found |= its.size() != 0;
        }

        return found;
    }

    /**
     * Init cache.
     */
    private void initCache() {
        CacheConfiguration<Integer, Person> personCacheCfg = new CacheConfiguration<>("person");
        personCacheCfg.setIndexedTypes(Integer.class, Person.class);

        IgniteCache<Integer, Person> personCache = grid(0).getOrCreateCache(personCacheCfg);

        personCache.clear();

        Person p1 = new Person("John", "Doe", 2000);
        Person p2 = new Person("Jane", "Doe", 1000);
        Person p3 = new Person("John", "Smith", 1000);
        Person p4 = new Person("Jane", "Smith", 2000);

        personCache.put(p1.getId(), p1);
        personCache.put(p2.getId(), p2);
        personCache.put(p3.getId(), p3);
        personCache.put(p4.getId(), p4);

        SqlQuery<Integer, Person> qry = new SqlQuery<>(Person.class, "salary > ? and salary <= ?");

        qry.setArgs(1000, 2000);

        assertEquals(2, personCache.query(qry).getAll().size());
    }

    /**
     * Person class.
     */
    public static class Person implements Serializable {
        /** Person id. */
        private static int PERSON_ID = 0;

        /** Person ID (indexed). */
        @QuerySqlField(index = true)
        private Integer id;

        /** First name (not-indexed). */
        @QuerySqlField
        private String firstName;

        /** Last name (not indexed). */
        @QuerySqlField
        private String lastName;

        /** Salary (indexed). */
        @QuerySqlField(index = true)
        private double salary;

        /**
         * @param firstName First name.
         * @param lastName Last name.
         * @param salary Salary.
         */
        Person(String firstName, String lastName, double salary) {
            id = PERSON_ID++;

            this.firstName = firstName;
            this.lastName = lastName;
            this.salary = salary;
        }

        /**
         * @return First name.
         */
        public String getFirstName() {
            return firstName;
        }

        /**
         * @return Last name.
         */
        public String getLastName() {
            return lastName;
        }
        /**
         * @return Salary.
         */
        public double getSalary() {

            return salary;
        }

        /**
         * @return Id.
         */
        public Integer getId() {
            return id;
        }
    }
}


text:
layout: page
title: Liberated Company Seminar
date: 2016-05-24
author: Keith Lutz
tags: weekly links, java
status: published
summary: Morbi sollicitudin at neque eget posuere. Nullam id.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 02/05/2016
  endDate: 02/10/2016
  ctyhocn: MSHTXHX
  groupCode: LCS
published: true
---
Nulla nec est tortor. Sed tempus eros id sem faucibus congue. Vestibulum sodales facilisis libero et elementum. Integer eu turpis ullamcorper, commodo lectus a, scelerisque metus. Aliquam fermentum elementum rhoncus. Integer at hendrerit magna. Etiam vitae sem ut tortor sagittis tristique vitae quis nibh. Ut sed fermentum elit, et lobortis sapien. Vestibulum quam massa, elementum quis nulla eu, fermentum hendrerit nunc. Pellentesque congue quam ligula, eget faucibus mauris tempus eu.

1 Donec malesuada erat id efficitur tristique
1 Quisque elementum diam ut volutpat fringilla
1 Vivamus in ante sed ex fermentum hendrerit
1 Aenean facilisis leo ac mauris aliquam, sed auctor nibh eleifend.

Donec quis orci convallis, aliquam orci vel, varius nisi. Ut vestibulum mi sit amet faucibus interdum. Etiam rutrum dolor quis odio semper, nec porta felis volutpat. Vivamus posuere vehicula tempor. Quisque finibus tristique iaculis. Phasellus feugiat turpis metus, quis ornare lectus mollis in. Donec auctor elit ac cursus ornare. Maecenas placerat pharetra venenatis. Nunc et sem vitae sapien placerat vestibulum. Aliquam dapibus ullamcorper orci eget maximus. Vestibulum sit amet gravida mauris. Donec fringilla est dignissim, ullamcorper urna sed, porttitor libero. Donec fermentum suscipit neque faucibus lacinia. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vitae sodales magna.


text:
"""This module is deprecated. Please use `airflow.providers.google.cloud.sensors.pubsub`."""

import warnings

# pylint: disable=unused-import
from airflow.providers.google.cloud.sensors.pubsub import PubSubPullSensor  # noqa

warnings.warn(
    "This module is deprecated. Please use `airflow.providers.google.cloud.sensors.pubsub`.",
    DeprecationWarning, stacklevel=2
)


text:
"""
Module containing APIResponseError class
"""

import os

class APIResponseError(Exception):
    """
    Error class that represents HTTP error status codes in OWM web API
    responses.

    :param cause: the message of the error
    :type cause: str
    :returns: a *APIResponseError* instance
    """
    def __init__(self, message):
        self._message = message

    def __str__(self):
        """Redefine __str__ hook for pretty-printing"""
        return ''.join(['An error HTTP status code was returned by the ' + \
                        'OWM API', os.linesep, 'Reason: ',
                        self._message]).decode('utf-8')


text:
package org.conqat.engine.persistence.index.schema;

import org.conqat.engine.persistence.store.IStore;

/**
 * Interface that can be used to decorate the stores created by this schema.
 *
 * @author $Author: heineman $
 * @version $Rev: 38851 $
 * @ConQAT.Rating GREEN Hash: C04226BF71C3377E9988BBA2F83D2240
 */
public interface IStoreDecorator {

	/** Template method used to decorate a store. */
	IStore decorate(IStore store);
}


text:
declare namespace Jymfony.Component.HttpFoundation.Websocket {
    /**
     * Utility class to decode a websocket frame.
     *
     * @internal
     */
    export class FrameBuffer {
        /**
         * Temporary buffer.
         */
        private _buffer: Buffer;

        /**
         * Incomplete frames buffer.
         */
        private _frames: Frame[];

        /**
         * Constructor.
         */
        __construct(): void;
        constructor();

        /**
         * Adds data, generates decoded messages.
         */
        concat(data: Buffer): IterableIterator<Message>;

        /**
         * Adds a frame to the buffer.
         */
        private _addFrame(frame: Frame): void;

        /**
         * Builds a message from the buffered frames.
         */
        private _buildMessage(): Message;
    }
}


text:
\timing
select count(*) from restaurantphone rp, addressphone ap where levenshtein_distance(rp.phone, ap.phone) < 4;
select count(*) from restaurantaddress ra, restaurantphone rp where levenshtein_distance(ra.name, rp.name) < 3;
select count(*) from restaurantaddress ra, addressphone ap where levenshtein_distance(ra.address, ap.address) < 4;
select count(*) from restaurantphone rp, addressphone ap where jaccard_index(rp.phone, ap.phone) > .6;
select count(*) from restaurantaddress ra, restaurantphone rp where jaccard_index(ra.name, rp.name) > .65;
select count(*) from restaurantaddress ra, addressphone ap where jaccard_index(ra.address, ap.address) > .8;


text:
"""Tests the core pipeline.
"""

import unittest
import os
import shutil
import xml.etree.ElementTree as ET
from tempfile import mkdtemp, NamedTemporaryFile
from textwrap import dedent

from sonLib.bioio import TestStatus, newickTreeParser, getTempFile

from cactus.shared.test import getCactusInputs_random
from cactus.shared.test import getCactusInputs_randomWithConstraints
from cactus.shared.test import getCactusInputs_blanchette
from cactus.shared.test import getCactusInputs_encode
from cactus.shared.test import getCactusInputs_chromosomeX
from cactus.shared.test import runWorkflow_multipleExamples
from cactus.shared.test import getBatchSystem
from cactus.shared.test import silentOnSuccess
from cactus.shared.test import initialiseGlobalDatabaseConf

from cactus.shared.common import cactusRootPath

from cactus.pipeline.cactus_workflow import getOptionalAttrib, extractNode, findRequiredNode, \
    getJobNode, CactusJob, getLongestPath, inverseJukesCantor, \
    CactusSetReferenceCoordinatesDownRecursion, prependUniqueIDs

class TestCase(unittest.TestCase):
    def setUp(self):
        self.batchSystem = "singleMachine"
        if getBatchSystem() != None:
            self.batchSystem = getBatchSystem()
        unittest.TestCase.setUp(self)
        self.configFile = os.path.join(cactusRootPath(), "cactus_config.xml")
        self.configNode = ET.parse(self.configFile).getroot()
        self.barNode = self.configNode.find("bar")
        assert self.barNode != None

    @silentOnSuccess
    @unittest.skip("")
    def testCactus_random(self):
        runWorkflow_multipleExamples(getCactusInputs_random,
                                     testNumber=1,
                                     testRestrictions=(TestStatus.TEST_SHORT,),
                                     buildAvgs=True, buildReference=True,
                                     batchSystem=self.batchSystem, buildToilStats=True)

    @silentOnSuccess
    @unittest.skip("")
    def testCactus_randomWithConstraints(self):
        runWorkflow_multipleExamples(getCactusInputs_randomWithConstraints,
                                     testNumber=1,
                                     testRestrictions=(TestStatus.TEST_SHORT,),
                                     buildAvgs=True, buildReference=True,
                                     batchSystem=self.batchSystem, buildToilStats=True,
                                     useConstraints=True)

    @silentOnSuccess
    @unittest.skip("")
    def testCactus_blanchette(self):
        runWorkflow_multipleExamples(getCactusInputs_blanchette,
                                     testNumber=1,
                                     testRestrictions=(TestStatus.TEST_MEDIUM,),
                                     buildAvgs=True, buildReference=True,
                                     batchSystem=self.batchSystem, buildToilStats=True)
    @silentOnSuccess
    @unittest.skip("")
    def testCactus_encode(self):
        runWorkflow_multipleExamples(getCactusInputs_encode,
                                     testNumber=1,
                                     testRestrictions=(TestStatus.TEST_LONG,),
                                     buildAvgs=True, buildReference=True,
                                     batchSystem=self.batchSystem, buildToilStats=True)
    @silentOnSuccess
    @unittest.skip("")
    def testCactus_chromosomes(self):
        runWorkflow_multipleExamples(getCactusInputs_chromosomeX,
                                     testRestrictions=(TestStatus.TEST_VERY_LONG,),
                                     batchSystem=self.batchSystem, buildToilStats=True)

    @silentOnSuccess
    def testCactus_splitBarJobs(self):
        """Exercise the code paths in bar that only occur on large jobs."""
        # Modify the bar node in the config file so that
        # cactus_workflow will split bar jobs even on this small
        # example
        initialiseGlobalDatabaseConf('<st_kv_database_conf type="kyoto_tycoon"><kyoto_tycoon in_memory="1" port="1978" snapshot="0"/></st_kv_database_conf>')
        tempConfigFile = getTempFile()
        tempConfigTree = ET.parse(self.configFile)
        tempConfigNode = tempConfigTree.getroot()
        tempConfigNode.find("bar").find("CactusBarWrapper").set("maxFlowerGroupSize", "10")
        tempConfigNode.find("bar").find("CactusBarWrapperLarge").set("maxFlowerGroupSize", "10")
        tempConfigNode.find("bar").set("veryLargeEndSize", "20")
        tempConfigNode.find("bar").set("largeEndSize", "10")
        tempConfigNode.find("bar").set("bandingLimit", "5")
        tempConfigTree.write(tempConfigFile)
        runWorkflow_multipleExamples(getCactusInputs_random,
                                     testNumber=1,
                                     batchSystem=self.batchSystem,
                                     configFile=tempConfigFile)
        os.remove(tempConfigFile)

    def testGetOptionalAttrib(self):
        self.assertEquals("0", getOptionalAttrib(self.barNode, "minimumBlockDegree"))
        self.assertEquals(0, getOptionalAttrib(self.barNode, "minimumBlockDegree", typeFn=int, default=1))
        self.assertEquals(None, getOptionalAttrib(self.barNode, "doesntExist"))
        self.assertEquals(1, getOptionalAttrib(self.barNode, "doesntExist", typeFn=int, default=1))

    def testFindRequiredNode(self):
        self.assertEquals(findRequiredNode(self.configNode, "bar"), self.barNode)
        try:
            findRequiredNode(self.configNode, "doesntExist")
            self.assertTrue(0)
        except:
            pass
        self.assertEquals(findRequiredNode(self.configNode, "caf"), self.configNode.findall("caf")[0])

    def testExtractNode(self):
        subNode = ET.SubElement(self.barNode, "CactusSetReferenceCoordinatesDownRecursion", { "memory":"10" })
        barNodeCopy = extractNode(self.barNode)
        barNodeCopy.attrib["added"] = "1"
        self.assertFalse("added" in self.barNode.attrib)
        self.barNode.attrib["added2"] = "1"
        self.assertTrue("added2" in self.barNode.attrib)
        self.assertFalse("added2" in barNodeCopy.attrib)
        self.assertEquals(subNode, self.barNode.find("CactusSetReferenceCoordinatesDownRecursion"))
        subNodeCopy = barNodeCopy.find("CactusSetReferenceCoordinatesDownRecursion")
        self.assertTrue(subNodeCopy != None)
        self.assertEquals("10", subNodeCopy.attrib["memory"])

    def testGetJobNode(self):
        class CactusTestJob(CactusJob):
            pass
        class CactusTestJob2(CactusJob):
            pass
        node = ET.SubElement(self.barNode, "CactusTestJob")
        self.assertEquals(node, getJobNode(self.barNode, CactusTestJob))
        self.assertEquals(None, getJobNode(self.barNode, CactusTestJob2))
        node2 = ET.SubElement(self.barNode, "CactusSetReferenceCoordinatesDownRecursion")
        self.assertEquals(node2, getJobNode(self.barNode, CactusSetReferenceCoordinatesDownRecursion))

    def testCactusJob(self):
        class CactusTestJob(CactusJob):
            pass
        node = ET.SubElement(self.barNode, "CactusTestJob", attrib={ "memory":10, "cpu":2,  "overlargeMemory":20 })
        job = CactusTestJob(self.barNode, self.barNode)
        self.assertEquals(job.getOptionalPhaseAttrib("diagonalExpansion", typeFn=int), 20)
        self.assertEquals(job.getOptionalPhaseAttrib("doesntExist", typeFn=int, default=1), 1)
        self.assertEquals(job.getOptionalJobAttrib("memory", typeFn=int), 10)
        self.assertEquals(job.getOptionalJobAttrib("cpu", typeFn=int, default=1), 2)
        self.assertEquals(job.getOptionalJobAttrib("overlargeCpu", typeFn=int, default=-1), -1)

    def testGetLongestPath(self):
        self.assertAlmostEquals(getLongestPath(newickTreeParser("(b(a:0.5):0.5,b(a:1.5):0.5)")), 2.0)
        self.assertAlmostEquals(getLongestPath(newickTreeParser("(b(a:0.5):0.5,b(a:1.5,c:10):0.5)")), 10.5)
        self.assertAlmostEquals(getLongestPath(newickTreeParser("(b(a:0.5):0.5,b(a:1.5,c:10,e,f:20):0.5)")), 20.5)

    def testInverseJukesCantor(self):
        self.assertAlmostEquals(inverseJukesCantor(0.5), 0.36493716072555599)
        self.assertAlmostEquals(inverseJukesCantor(1.0), 0.55230214641320496)
        self.assertAlmostEquals(inverseJukesCantor(10.0), 0.74999878530240571)
        self.assertAlmostEquals(inverseJukesCantor(100000.0), 0.75)

    def testPrependUniqueIDs(self):
        # Create fake FASTA files with some interesting headers.
        with NamedTemporaryFile() as fasta1, NamedTemporaryFile() as fasta2:
            fasta1.write(dedent("""
            >C10856240  2.0
            ACTAGAGG
            G

            GG
            >foo bar  baz
            ACTGACGATgacgat
            >emptyseq
            """))
            fasta2.write(dedent("""
            > space
            GTGC
            >id=1||header
            ATCC
            """))
            fasta1.flush()
            fasta2.flush()
            outDir = mkdtemp()
            outputPaths = prependUniqueIDs([fasta1.name, fasta2.name], outDir)

        assert len(outputPaths) == 2
        with open(outputPaths[0]) as f:
            self.assertEquals(f.read(), dedent("""
            >id=0|C10856240  2.0
            ACTAGAGG
            G

            GG
            >id=0|foo bar  baz
            ACTGACGATgacgat
            >id=0|emptyseq
            """))
        with open(outputPaths[1]) as f:
            self.assertEquals(f.read(), dedent("""
            >id=1| space
            GTGC
            >id=1|id=1||header
            ATCC
            """))
        shutil.rmtree(outDir)

if __name__ == '__main__':
    unittest.main()


text:
'use strict';

var gulp = require('gulp');
var concat = require('gulp-concat');
var browserify = require('browserify');
var reactify = require('reactify');
var source = require('vinyl-source-stream');
// Load plugins
var $ = require('gulp-load-plugins')();

// Styles
gulp.task('styles', function () {
    return gulp.src('app/styles/*.*')
        .pipe($.rubySass({
            style: 'expanded',
            precision: 10,
            loadPath: ['./bower_components']
        }))
        .pipe($.autoprefixer('last 1 version'))
        .pipe(gulp.dest('dist/styles'))
        .pipe($.size())
        .pipe($.connect.reload());
});

// images
gulp.task('images', function () {
    return gulp.src('app/images/*.*')
        .pipe(gulp.dest('dist/images'));
});

// Scripts
gulp.task('scripts', function() {
    browserify(['./app/scripts/app.js'])
    .transform(reactify)
    .bundle()
    .pipe(source('app.js'))
    .pipe(gulp.dest('./dist/scripts/'));
});

// HTML
gulp.task('html', function () {
    return gulp.src('app/*.html')
        .pipe($.useref())
        .pipe(gulp.dest('dist'))
        .pipe($.size())
        .pipe($.connect.reload());
});

// Clean
gulp.task('clean', function () {
    return gulp.src(['dist/styles', 'dist/scripts', 'dist/images', 'dist'], {read: false}).pipe($.clean());
});

// Bundle
gulp.task('bundle', ['styles', 'scripts', 'images', 'bower'], function(){
    return gulp.src('./app/*.html')
               .pipe($.useref.assets())
               .pipe($.useref.restore())
               .pipe($.useref())
               .pipe(gulp.dest('dist'));
});

// Build
gulp.task('build', ['html', 'bundle']);

// Default task
gulp.task('default', ['clean'], function () {
    gulp.start('build');
});

// Bower helper
gulp.task('bower', function() {
    gulp.src('bower_components/**/*.js', {base: 'bower_components'})
        .pipe(gulp.dest('dist/bower_components/'));

});


text:
package com.kabo.core.behavior;

public interface Behavior {

/* For Future use*/

}


text:
package com.mark.changesigns;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by admin on 2016/06/02.
 */
@Target(ElementType.FIELD)//表示用在字段上
@Retention(RetentionPolicy.RUNTIME)//表示在生命周期是运行时
public @interface ViewInject {
    int value() default 0;
}


text:
unless Capistrano::Configuration.respond_to?(:instance)
  abort "Requires Capistrano 2"
end

Dir["#{File.dirname(__FILE__)}/slicehost/*.rb"].each { |lib|
  Capistrano::Configuration.instance.load {load(lib)}
}


text:
from .shotgun import Shotgun, ShotgunError, Fault
from .fixture import Fixture
from .unittest import TestCase

# Silence pyflakes.
assert Shotgun and ShotgunError and Fault and Fixture and TestCase