text:
// condor includes
#include "condor_common.h"
#include "condor_qmgr.h"

// local includes
#include "Codec.h"
#include "AviaryUtils.h"

using namespace compat_classad;
using namespace aviary::codec;
using namespace aviary::util;

// TODO: defer until linking issues sorted
//Codec*
//DefaultCodecFactory::createCodec() {
//    if (!m_codec) {
//        m_codec = new BaseCodec;
//    }
//    return m_codec;
//}

BaseCodec::BaseCodec()
{
    //
}

BaseCodec::~BaseCodec()
{
    //
}

bool
BaseCodec::addAttributeToMap (ClassAd& ad, const char* name, AttributeMapType& _map)
{
    ExprTree *expr;

    // All these extra lookups are horrible. They have to
    // be there because the ClassAd may have multiple
    // copies of the same attribute name! This means that
    // the last attribute with a given name will set the
    // value, but the last attribute tends to be the
    // attribute with the oldest (wrong) value. How
    // annoying is that!
    if (!(expr = ad.Lookup(name))) {
        dprintf(D_FULLDEBUG, "Warning: failed to lookup attribute '%s' from ad\n", name);
        return false;
    }

    classad::Value value;
    ad.EvaluateExpr(expr,value);
	std::string key = name;
    switch (value.GetType()) {
        // seems this covers expressions also
        case classad::Value::ERROR_VALUE:
        case classad::Value::UNDEFINED_VALUE:
        case classad::Value::BOOLEAN_VALUE:
            _map[key] = new AviaryAttribute(AviaryAttribute::EXPR_TYPE,trimQuotes(ExprTreeToString(expr)).c_str());
            break;
        case classad::Value::INTEGER_VALUE:
        {
            int i;
            value.IsIntegerValue (i);
            string i_str;
            formatstr(i_str,"%d",i);
            _map[key] = new AviaryAttribute(AviaryAttribute::INTEGER_TYPE,i_str.c_str());
            break;
        }
        case classad::Value::REAL_VALUE:
        {
            double d;
            value.IsRealValue(d);
            string d_str;
            formatstr(d_str,"%f",d);
            _map[key] = new AviaryAttribute(AviaryAttribute::FLOAT_TYPE,d_str.c_str());
            break;
        }
        case classad::Value::STRING_VALUE:
        default:
            _map[key] = new AviaryAttribute(AviaryAttribute::STRING_TYPE,trimQuotes(ExprTreeToString(expr)).c_str());
    }

    return true;
}

bool
BaseCodec::classAdToMap(ClassAd& ad, AttributeMapType& _map)
{
    ExprTree *expr;
	const char *name;
	ad.ResetExpr();
	_map.clear();
	while (ad.NextExpr(name,expr)) {
		if (!addAttributeToMap(ad, name, _map)) {
                    return false;
		}
	}

// //debug
//        if (IsFulldebug(D_FULLDEBUG)) {
//            ad.dPrint(D_FULLDEBUG|D_NOHEADER);
//        }

    return true;
}

bool
BaseCodec::mapToClassAd(AttributeMapType& _map, ClassAd& ad, string& text)
{

    for (AttributeMapIterator entry = _map.begin(); _map.end() != entry; entry++) {
        const char* name = entry->first.c_str();

		if (isKeyword(name)) {
			text = "Reserved ClassAd keyword cannot be an attribute name: "+ entry->first;
			return false;
		}

        AviaryAttribute* value = entry->second;

        switch (value->getType()) {
            case AviaryAttribute::INTEGER_TYPE:
                ad.Assign(name, atoi(value->getValue()));
                break;
            case AviaryAttribute::FLOAT_TYPE:
                ad.Assign(name, atof(value->getValue()));
                break;
            case AviaryAttribute::STRING_TYPE:
                ad.Assign(name, value->getValue());
                break;
            case AviaryAttribute::EXPR_TYPE:
                ad.AssignExpr(name, value->getValue());
                break;
            default:
                dprintf(D_FULLDEBUG, "Warning: Unknown/unsupported type in map for attribute '%s'\n", name);
        }
    }

//     // debug
//     if (IsFulldebug(D_FULLDEBUG)) {
//           ad.dPrint(D_FULLDEBUG|D_NOHEADER);
//     }

    return true;
}


text:
package org.neo4j.kernel.api.exceptions.schema;

import org.neo4j.kernel.api.TokenNameLookup;
import org.neo4j.kernel.api.exceptions.Status;
import org.neo4j.kernel.api.index.IndexDescriptor;

import static java.lang.String.format;

public class NoSuchIndexException extends SchemaKernelException
{
    private final IndexDescriptor descriptor;
    private final static String message = "No such INDEX ON %s.";

    public NoSuchIndexException( IndexDescriptor descriptor )
    {
        super( Status.Schema.NoSuchIndex, format( message, descriptor ) );
        this.descriptor = descriptor;
    }

    @Override
    public String getUserMessage( TokenNameLookup tokenNameLookup )
    {
        return format( message, descriptor.userDescription( tokenNameLookup ) );
    }
}

redpajama_set_name: RedPajamaGithub


text:
package colossus

import colossus.testkit.ColossusSpec
import core._
import service.Callback
import Callback.Implicits._

import akka.actor._
import akka.testkit.TestProbe

import java.net.InetSocketAddress
import scala.concurrent.duration._

import RawProtocol._

class ConnectionHandlerSpec extends ColossusSpec {

  "Server Connection Handler" must {
    "bind to worker on creation" in {
      val probe = TestProbe()
      class MyHandler(context: ServerContext) extends NoopHandler(context) {
        override def onBind() {
          probe.ref ! "BOUND"
        }
      }
      withServer(context => new MyHandler(context)) { server =>
        val c = TestClient(server.system, TEST_PORT)
        probe.expectMsg(100.milliseconds, "BOUND")
      }
    }

    "unbind on disconnect" in {
      val probe = TestProbe()
      class MyHandler(context: ServerContext) extends NoopHandler(context) {
        override def onUnbind() {
          probe.ref ! "UNBOUND"
        }
      }
      withServer(context => new MyHandler(context)) { server =>
        val c = TestClient(server.system, TEST_PORT, connectRetry = NoRetry)
        c.disconnect()
        TestClient.waitForStatus(c, ConnectionStatus.NotConnected)
        probe.expectMsg(500.milliseconds, "UNBOUND")
      }
    }
  }

  "Client Connection Handler" must {

    class MyHandler(context: Context,
                    probe: ActorRef,
                    sendBind: Boolean,
                    sendUnbind: Boolean,
                    disconnect: Boolean = false)
        extends NoopHandler(context)
        with ClientConnectionHandler {
      override def onBind() {
        if (sendBind) probe ! "BOUND"
      }
      override def onUnbind() {
        println("UNBOUND")
        if (sendUnbind) probe ! "UNBOUND"
      }

      override def connected(endpoint: WriteEndpoint) {
        println("CONNECTED")
        if (disconnect) endpoint.disconnect()
      }

      override def connectionTerminated(cause: DisconnectCause) {
        println(s"TERMINATED: $cause")
      }

    }

    "bind to worker" in {
      val probe = TestProbe()
      withIOSystem { implicit io =>
        //obvious this will fail to connect, but we don't care here
        io ! IOCommand.BindAndConnectWorkerItem(new InetSocketAddress("localhost", TEST_PORT),
                                                context => new MyHandler(context, probe.ref, true, false))
        probe.expectMsg(100.milliseconds, "BOUND")
      }
    }

    "automatically unbind on manual disconnect" in {
      val probe = TestProbe()
      class MyHandler(context: Context) extends NoopHandler(context) {
        override def onUnbind() {
          probe.ref ! "UNBOUND"
        }
        override def connected(endpoint: WriteEndpoint) {
          endpoint.disconnect()
        }
      }
      withIOSystem { implicit io =>
        withServer(RawServer.basic("test", TEST_PORT) { case x => x }) {
          io ! IOCommand.BindAndConnectWorkerItem(new InetSocketAddress("localhost", TEST_PORT), c => new MyHandler(c))
          probe.expectMsg(250.milliseconds, "UNBOUND")
        }
      }
    }

    "automatically unbind on disrupted connection" in {
      val probe = TestProbe()
      withIOSystem { implicit io =>
        val server = RawServer.basic("test", TEST_PORT) { case x => x }
        withServer(server) {
          io ! IOCommand.BindAndConnectWorkerItem(
            new InetSocketAddress("localhost", TEST_PORT),
            c => new MyHandler(c, probe.ref, true, true)
          )
          probe.expectMsg(500.milliseconds, "BOUND")
        }
        end(server)
        println("server ENDED")
        probe.expectMsg(5000.milliseconds, "UNBOUND")
      }

    }

    "automatically unbind on failure to connect" taggedAs (org.scalatest.Tag("test")) in {
      val probe = TestProbe()
      withIOSystem { implicit io =>
        io ! IOCommand.BindAndConnectWorkerItem(
          new InetSocketAddress("localhost", TEST_PORT),
          c => new MyHandler(c, probe.ref, true, true)
        )
        probe.expectMsg(250.milliseconds, "BOUND")
        probe.expectMsg(10.seconds, "UNBOUND")
      }
    }

    "NOT automatically unbind with ManualUnbindHandler mixin on disrupted connection" in {
      val probe = TestProbe()
      class MyHandler(context: Context) extends NoopHandler(context) with ManualUnbindHandler {
        override def onUnbind() {
          probe.ref ! "UNBOUND"
        }
      }
      withIOSystem { implicit io =>
        withServer(RawServer.basic("test", TEST_PORT) { case x => x }) {
          io ! IOCommand.BindAndConnectWorkerItem(new InetSocketAddress("localhost", TEST_PORT), c => new MyHandler(c))
          probe.expectNoMessage(200.milliseconds)
        }
        probe.expectNoMessage(200.milliseconds)
      }
    }

    "NOT automatically unbind on failed connection with ManualUnbindHandler" in {
      val probe = TestProbe()
      class MyHandler(context: Context) extends NoopHandler(context) with ManualUnbindHandler {
        override def onUnbind() {
          probe.ref ! "UNBOUND"
        }
      }
      withIOSystem { implicit io =>
        io ! IOCommand.BindAndConnectWorkerItem(new InetSocketAddress("localhost", TEST_PORT), c => new MyHandler(c))
        probe.expectNoMessage(200.milliseconds)
      }

    }
  }

}


text:
MongoDB\BSON\Javascript::__construct() does not allow code to contain null bytes
--FILE--
<?php
try
{
	new \MongoDB\BSON\Javascript("function foo() { return 'Something with \0 in it'; }");
}
catch ( \MongoDB\Driver\Exception\InvalidArgumentException $e )
{
	echo $e->getMessage(), "\n";
}
?>
--EXPECT--
Code cannot contain null bytes


text:
using System;
using FSpot.Imaging;
using FSpot.Utils;
using Hyena;

namespace FSpot.Loaders
{
	public static class ImageLoader
	{
		public static IImageLoader Create (SafeUri uri)
		{
			if (!App.Instance.Container.Resolve<IImageFileFactory> ().HasLoader (uri))
				throw new Exception ("Loader requested for unknown file type: " + uri.GetExtension());

			return new GdkImageLoader ();
		}
	}
}


text:
"""
@author: Sebi

File: test_bfread.py
Date: 20.04.2017
Version. 0.7
"""

import numpy as np
import os
import bftools as bf
import pytest
import datetime
import zencom as zc

def setbfpath():

    # specify bioformats_package.jar to use if required
    bfpackage = r'bfpackage/5.9.2/bioformats_package.jar'
    bf.set_bfpath(bfpackage)

    return bfpackage

"""
Here one must enter the correct and expected metadata. The CZI will be parsed and the information for the
CZI will be compared to the stuff defined here. The idea is that executing the same experiment must produce
an image which the expected metadata that can be read and parsed by the bioformats_package.jar correctly.

Usage form commadline:

pytest text_bfread.py

"""

def get_filename():
    filename = r'l:\20170419_BioFormats_CZI_Test_small_384chamber_5X_2X.czi'
    return filename

def get_dims():
    #return [16, 3, 5, 2, 640, 640]
    return [4, 3, 5, 2, 486, 486]

def get_chwlex():
    return [493, 553]

def get_chwlem():
    return [517, 568]

def get_dyes():
    return ['None', 'None']

def get_chnames():
    return ['AF488', 'AF555']

def get_chdescription():
    return ['n.a.', 'n.a.']

def create_testCZI():

    # Define the experiment to be executed
    zenexperiment = r'l:\Data\BioFormats_CZI_Test\BioFormats_CZI_Test_small_384chamber_5X_2X.czexp'

    # get current data and create filename from it
    today = datetime.datetime.today()
    currentCZI = today.strftime('%Y%m%d') + '_BF_CZI.czi'

    # Define place to store the CZI file
    savefolder = r'l:\\Data\BioFormats_CZI_Test\\' + today.strftime('%Y%m%d') + '\\'

    # check if the folder already exists
    try:
        os.makedirs(savefolder)
    except OSError:
        if not os.path.isdir(savefolder):
            raise

    czifilename_complete = zc.runExperiment(zenexperiment, savefolder, currentCZI, showCZI=False)

    # create the xml information - expects list of filenames as input
    bf.create_omexml([czifilename_complete], method=1, writeczi_metadata=True)

    # create plane info table and write into dataframe
    df = bf.get_planetable(czifilename_complete, writecsv=True, separator='\t')

    # show the dataframe
    print(df[:5])
    print(df.shape[0])

    return czifilename_complete

def test_metainfo():

    # run the test experiment to create the CZI test data set
    #czifilename_complete = create_testCZI()
    # or use an already existing CZI file to check for the metadata
    czifilename_complete = get_filename()

    # set the correct path to the bioformats_package.jar
    bfpackage = setbfpath()

    # use for BioFormtas <= 5.1.10
    # urlnamespace = 'http://www.openmicroscopy.org/Schemas/OME/2015-01'
    # use for BioFormtas > 5.2.0
    urlnamespace = 'http://www.openmicroscopy.org/Schemas/OME/2016-06'

    # get image meta-information
    MetaInfo = bf.get_relevant_metainfo_wrapper(czifilename_complete,
                                                namespace=urlnamespace,
                                                bfpath=bfpackage,
                                                showinfo=False)

    # get image as numpy array
    img6d = bf.get_image6d(czifilename_complete, MetaInfo['Sizes'])

    fulldims = get_dims()
    #print(MetaInfo['Sizes'])

    # check Sizes
    assert MetaInfo['Sizes'] == fulldims
    # check Dimension Order
    assert MetaInfo['DimOrder BF'] == 'XYCZT'
    # check Dimension Order CZI Style
    assert MetaInfo['OrderCZI'] == b'BSTCZYX0'
    # check Image Dimensions
    assert MetaInfo['TotalSeries'] == fulldims[0]
    assert MetaInfo['SizeT'] == fulldims[1]
    assert MetaInfo['SizeZ'] == fulldims[2]
    assert MetaInfo['SizeC'] == fulldims[3]
    assert MetaInfo['SizeY'] == fulldims[4]
    assert MetaInfo['SizeX'] == fulldims[5]
    # check Scaling
    assert MetaInfo['XScale'] == 0.1
    assert MetaInfo['YScale'] == 0.1
    assert MetaInfo['ZScale'] == 0.5
    # check Objective Data
    assert MetaInfo['ObjMag'] == 5.0
    assert MetaInfo['NA'] == 0.35
    assert MetaInfo['Immersion'] == 'Air'
    # check objective Name
    assert MetaInfo['ObjModel'] == 'Plan-Apochromat 5x/0.35'

    # check properties of all channels
    for ch in range(0, MetaInfo['SizeC']):
        # check Excitation and Emission Wavelengths
        assert MetaInfo['WLEx'][ch] == get_chwlex()[ch]
        assert MetaInfo['WLEm'][ch] == get_chwlem()[ch]
        # check Dye Names
        assert MetaInfo['Dyes'][ch] == get_dyes()[ch]
        assert MetaInfo['Channels'][ch] == get_chnames()[ch]
    # check Channel Description
    assert MetaInfo['ChDesc'] == ['n.a.']
    # check Numpy Array Shape
    for i in range(0, len(fulldims)):
        assert np.shape(img6d)[i] == fulldims[i]

    # # test timeseries
    #
    # seriesID = 0
    # zplane = 2
    # dims = [3, 2, 640, 640]
    # # get the actual time series from the data set
    # tseries, dimorder_out = bf.get_timeseries(czifilename_complete, MetaInfo['Sizes'], seriesID, zplane=zplane)
    #
    # for i in range(0, len(dims)):
    #     assert np.shape(tseries)[i] == dims[i]
    #
    # # check resulting dimension order
    # assert dimorder_out == 'TCXY'
    #
    #
    # # test zstack
    #
    # seriesID = 0
    # timepoint = 0
    # dims = [5, 2, 640, 640]
    # # get the actual z-stack from the data set
    # zstack, dimorder_out = bf.bftools.get_zstack(czifilename_complete, MetaInfo['Sizes'], seriesID, timepoint=timepoint)
    # print(zstack.shape)
    #
    # # get plane with the brightest pixel
    # zplane = (zstack == zstack.max()).nonzero()[0][0]
    # # check found zplane
    # assert zplane+1 == 1
    #
    # for i in range(0, len(dims)):
    #     assert np.shape(zstack)[i] == dims[i]

    # test getdimonly:

    sizes_czi = bf.czitools.read_dimensions_czi(czifilename_complete)

    dims = [1, 4, 3, 2, 5, 1216, 136216, 1]
    dimorder = 'BSTCZYX0'

    for i in range(0, len(dims)):
        assert sizes_czi[0][i] == dims[i]

    assert sizes_czi[1] == dimorder

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


text:
require "luaScript/ExtensionTest/CocosBuilderTest"
require "luaScript/ExtensionTest/WebProxyTest"

local LINE_SPACE = 40
local kItemTagBasic = 1000

local ExtensionTestEnum =
{
    TEST_NOTIFICATIONCENTER = 0,
    TEST_CCCONTROLBUTTON    = 1,
    TEST_COCOSBUILDER       = 2,
    TEST_WEBSOCKET          = 3,
    TEST_EDITBOX            = 4,
	TEST_TABLEVIEW          = 5,
    TEST_MAX_COUNT          = 6,
}

local testsName =
{
    "NotificationCenterTest",
    "CCControlButtonTest",
    "CocosBuilderTest",
    "WebSocketTest",
    "EditBoxTest",
    "TableViewTest",
}

--Create toMainLayr MenuItem
function CreateExtensionsBasicLayerMenu(pMenu)
	if nil == pMenu then
		return
	end
	local function toMainLayer()
       local pScene = ExtensionsTestMain()
       if pScene ~= nil then
           CCDirector:sharedDirector():replaceScene(pScene)
       end
    end
    --Create BackMneu
    CCMenuItemFont:setFontName("Arial")
    CCMenuItemFont:setFontSize(24)
   	local pMenuItemFont = CCMenuItemFont:create("Back")
    pMenuItemFont:setPosition(ccp(VisibleRect:rightBottom().x - 50, VisibleRect:rightBottom().y + 25))
    pMenuItemFont:registerScriptTapHandler(toMainLayer)
    pMenu:addChild(pMenuItemFont)
end

-------------------------------------
--Notification Center Test
-------------------------------------
local NotificationCenterParam =
{
	kTagLight   = 100,
    kTagConnect =  200,

	MSG_SWITCH_STATE = "SwitchState"
}
local function runNotificationCenterTest()

		local pNewScene = CCScene:create()
		local pNewLayer = CCLayer:create()
		local function BaseInitSceneLayer(pLayer)
		  if nil == pLayer then
			  return
		  end
		  local s = CCDirector:sharedDirector():getWinSize()

    	local function toggleSwitch(tag,menuItem)
    		local toggleItem = tolua.cast(menuItem,"CCMenuItemToggle")
    		local nIndex     = toggleItem:getSelectedIndex()
    		local selectedItem = toggleItem:selectedItem()
    		if 0 == nIndex  then
    			selectedItem = nil
    		end
    		CCNotificationCenter:sharedNotificationCenter():postNotification(NotificationCenterParam.MSG_SWITCH_STATE,selectedItem)
    	end

    	local switchlabel1 = CCLabelTTF:create("switch off", "Marker Felt", 26)
    	local switchlabel2 = CCLabelTTF:create("switch on", "Marker Felt", 26)
    	local switchitem1  = CCMenuItemLabel:create(switchlabel1)
    	local switchitem2 = CCMenuItemLabel:create(switchlabel2)
    	local switchitem = CCMenuItemToggle:create(switchitem1)
    	switchitem:addSubItem(switchitem2)
    	switchitem:registerScriptTapHandler(toggleSwitch)
    	--turn on
    	switchitem:setSelectedIndex(1)
        local menu = CCMenu:create()
        menu:addChild(switchitem)
    	menu:setPosition(ccp(s.width/2+100, s.height/2))
   		pLayer:addChild(menu)

    	local menuConnect = CCMenu:create()
    	menuConnect:setPosition(ccp(0,0))
    	pLayer:addChild(menuConnect)
    	local i = 1
    	local bSwitchOn = false
    	local bConnectArray =
    	{
    		false,
    		false,
    		false
    	}

    	local lightArray = {}

    	local function updateLightState()
    		for i = 1, 3 do
    			if bSwitchOn and bConnectArray[i] then
    			    lightArray[i]:setOpacity(255)
    			else
        			lightArray[i]:setOpacity(50)
        		end
    		end
    	end

    	local function switchStateChanged()
    		local nIndex = switchitem:getSelectedIndex()

    		if 0 == nIndex then
    			bSwitchOn = false
    		else
    			bSwitchOn = true
    		end
    		updateLightState()
    	end

    	local function setIsConnectToSwitch(pLight,bConnect,nIdx)
    		bConnectArray[nIdx]  = bConnect
    		print("come in")
    		if bConnect then
    			CCNotificationCenter:sharedNotificationCenter():registerScriptObserver(pLight, switchStateChanged,NotificationCenterParam.MSG_SWITCH_STATE)
    		else
    			CCNotificationCenter:sharedNotificationCenter():unregisterScriptObserver(pLight,NotificationCenterParam.MSG_SWITCH_STATE)
    		end
    		updateLightState()
    	end

    	for  i = 1, 3 do
        	lightArray[i] = CCSprite:create("Images/Pea.png")
       		lightArray[i]:setTag(NotificationCenterParam.kTagLight + i)
        	lightArray[i]:setPosition(ccp(100, s.height / 4 * i) )
        	pLayer:addChild(lightArray[i])

        	local connectlabel1 = CCLabelTTF:create("not connected", "Marker Felt", 26)

        	local connectlabel2 = CCLabelTTF:create("connected", "Marker Felt", 26)
        	local connectitem1 = CCMenuItemLabel:create(connectlabel1)
        	local connectitem2 = CCMenuItemLabel:create(connectlabel2)
        	local connectitem = CCMenuItemToggle:create(connectitem1)
        	connectitem:addSubItem(connectitem2)

        	connectitem:setTag(NotificationCenterParam.kTagConnect+i)

        	local function connectToSwitch(tag,menuItem)
    		   local connectMenuitem = tolua.cast(menuItem,"CCMenuItemToggle")
    		   local bConnected = true
    		   if connectMenuitem:getSelectedIndex() == 0 then
    		   	   bConnected = false
    		   end
    		   local nIdx = connectMenuitem:getTag()-NotificationCenterParam.kTagConnect
    		   setIsConnectToSwitch(lightArray[nIdx],bConnected,nIdx)
    		end

        	connectitem:registerScriptTapHandler(connectToSwitch)
        	local nX,nY = lightArray[i]:getPosition()
        	connectitem:setPosition(ccp(nX,nY+50))

            menuConnect:addChild(connectitem, 0,connectitem:getTag())

       		if  i == 2 then
            	connectitem:setSelectedIndex(1)
            end
            bConnectArray[i]   = false
           	if 1 == connectitem:getSelectedIndex() then
           		bConnectArray[i]  = true
           	end
    	end

    	for i = 1, 3 do
    	   setIsConnectToSwitch(lightArray[i],bConnectArray[i],i)
    	end
    	local toggleSelectIndex  = switchitem:getSelectedIndex()
    	local toggleSelectedItem = switchitem:selectedItem()
    	if 0 == toggleSelectIndex  then
    		toggleSelectedItem = nil
    	end
    	CCNotificationCenter:sharedNotificationCenter():postNotification(NotificationCenterParam.MSG_SWITCH_STATE, toggleSelectedItem)

    	--for testing removeAllObservers */
    	local function doNothing()
    	end
    	CCNotificationCenter:sharedNotificationCenter():registerScriptObserver(pNewLayer,doNothing, "random-observer1")
    	CCNotificationCenter:sharedNotificationCenter():registerScriptObserver(pNewLayer,doNothing, "random-observer2")
    	CCNotificationCenter:sharedNotificationCenter():registerScriptObserver(pNewLayer,doNothing, "random-observer3")

    	local function CreateToMainMenu(pMenu)
		     if nil == pMenu then
				return
			 end
			 local function toMainLayer()
				local numObserversRemoved = CCNotificationCenter:sharedNotificationCenter():removeAllObservers(pNewLayer)
				if 3 ~= numObserversRemoved then
					print("All observers were not removed!")
				end

				for i = 1 , 3 do
					 if bConnectArray[i] then
					 	CCNotificationCenter:sharedNotificationCenter():unregisterScriptObserver(lightArray[i],NotificationCenterParam.MSG_SWITCH_STATE)
					 end
				end

       			local pScene = ExtensionsTestMain()
       			if pScene ~= nil then
           			CCDirector:sharedDirector():replaceScene(pScene)
       			end
    		 end
    		 --Create BackMneu
    		 CCMenuItemFont:setFontName("Arial")
    		 CCMenuItemFont:setFontSize(24)
   			 local pMenuItemFont = CCMenuItemFont:create("Back")
    		 pMenuItemFont:setPosition(ccp(VisibleRect:rightBottom().x - 50, VisibleRect:rightBottom().y + 25))
    		 pMenuItemFont:registerScriptTapHandler(toMainLayer)
    		 pMenu:addChild(pMenuItemFont)
	   end
	   --Add Menu
	   local pToMainMenu = CCMenu:create()
       CreateToMainMenu(pToMainMenu)
       pToMainMenu:setPosition(ccp(0, 0))
       pLayer:addChild(pToMainMenu,10)
	   end

    BaseInitSceneLayer(pNewLayer)
	pNewScene:addChild(pNewLayer)

	return pNewScene
end
-------------------------------------
--  Control Extensions Test
-------------------------------------
local ControlExtensionsTestEnum =
{
    kCCControlSliderTest 			= 0,
    kCCControlColourPickerTest		= 1,
    kCCControlSwitchTest			= 2,
    kCCControlButtonTest_HelloVariableSize = 3,
    kCCControlButtonTest_Event		= 4,
    kCCControlButtonTest_Styling    = 5,
    kCCControlPotentiometerTest		= 6,
    kCCControlStepperTest			= 7,
    kCCControlTestMax               = 8
}

local ControlExtensionsTestArray =
{
	"CCControlSliderTest",
    "ControlColourPickerTest",
    "ControlSwitchTest",
    "ControlButtonTest_HelloVariableSize",
    "ControlButtonTest_Event",
    "ControlButtonTest_Styling",
    "ControlPotentiometerTest",
    "CCControlStepperTest",
}
local function runCCControlTest()
	local nMaxCases = ControlExtensionsTestEnum.kCCControlTestMax
	--kCCControlSliderTest
    local nCurCase  = ControlExtensionsTestEnum.kCCControlSliderTest
    local pSceneTitleLabel = nil

    local function GetSceneTitleLabel()
    	return pSceneTitleLabel
    end

    local function SetSceneTitleLabel(pLabel)
    	pSceneTitleLabel = pLabel
    end

    local function GetControlExtensionsTitle()
    	return ControlExtensionsTestArray[nCurCase + 1]
    end

    local pNewScene = CCScene:create()

	local function CreateBasicMenu(pMenu)
		if nil == pMenu then
			return
		end

    	local function backCallback()
    		nCurCase = nCurCase - 1
    		if nCurCase < 0 then
    			nCurCase = nCurCase + nMaxCases
    		end
 			CurrentControlScene()
    	end

    	local function restartCallback()
			CurrentControlScene()
    	end

    	local function nextCallback()
    		  nCurCase = nCurCase + 1
    		  --No check nMaxCases
    		  nCurCase = nCurCase % nMaxCases
			  CurrentControlScene()
   		end

    	local size = CCDirector:sharedDirector():getWinSize()
    	local item1 = CCMenuItemImage:create(s_pPathB1, s_pPathB2)
    	item1:registerScriptTapHandler(backCallback)
    	pMenu:addChild(item1,kItemTagBasic)
    	local item2 = CCMenuItemImage:create(s_pPathR1, s_pPathR2)
    	item2:registerScriptTapHandler(restartCallback)
    	pMenu:addChild(item2,kItemTagBasic)
    	local item3 = CCMenuItemImage:create(s_pPathF1, s_pPathF2)
    	pMenu:addChild(item3,kItemTagBasic)
    	item3:registerScriptTapHandler(nextCallback)

    	local size = CCDirector:sharedDirector():getWinSize()
    	item1:setPosition(CCPointMake(size.width / 2 - item2:getContentSize().width * 2, item2:getContentSize().height / 2))
    	item2:setPosition(CCPointMake(size.width / 2, item2:getContentSize().height / 2))
    	item3:setPosition(CCPointMake(size.width / 2 + item2:getContentSize().width * 2, item2:getContentSize().height / 2))

	end

	local function BaseInitSceneLayer(pLayer,pStrTitle)
		if nil == pLayer then
			return
		end
		--Add Menu
		local pToMainMenu = CCMenu:create()
    	CreateExtensionsBasicLayerMenu(pToMainMenu)
    	pToMainMenu:setPosition(ccp(0, 0))
    	pLayer:addChild(pToMainMenu,10)

    	--Add the generated background
        local pBackground = CCSprite:create("extensions/background.png")
        pBackground:setPosition(VisibleRect:center())
        pLayer:addChild(pBackground)

        --Add the ribbon
        local pRibbon = CCScale9Sprite:create("extensions/ribbon.png", CCRectMake(1, 1, 48, 55))
        pRibbon:setContentSize(CCSizeMake(VisibleRect:getVisibleRect().size.width, 57))
        pRibbon:setPosition(ccp(VisibleRect:center().x, VisibleRect:top().y - pRibbon:getContentSize().height / 2.0))
        pLayer:addChild(pRibbon)

        --Add the title
        pSceneTitleLabel = CCLabelTTF:create("Title", "Arial", 12)
        pSceneTitleLabel:setPosition(ccp (VisibleRect:center().x, VisibleRect:top().y - pSceneTitleLabel:getContentSize().height / 2 - 5))
        pLayer:addChild(pSceneTitleLabel, 1)
        pSceneTitleLabel:setString(pStrTitle)

    	local pOperateMenu = CCMenu:create()
    	CreateBasicMenu(pOperateMenu)
    	pOperateMenu:setPosition(ccp(0, 0))
		pLayer:addChild(pOperateMenu,1)
	end

	local function InitSliderTest(pLayer)
		if nil == pLayer then
			return
		end

		local screenSize = CCDirector:sharedDirector():getWinSize()
		--Add a label in which the slider value will be displayed
		local pDisplayValueLabel = CCLabelTTF:create("Move the slider thumb!\nThe lower slider is restricted." ,"Marker Felt", 32)
        pDisplayValueLabel:retain()
        pDisplayValueLabel:setAnchorPoint(ccp(0.5, -1.0))
        pDisplayValueLabel:setPosition(ccp(screenSize.width / 1.7, screenSize.height / 2.0))
        pLayer:addChild(pDisplayValueLabel)

        local function valueChanged(strEventName,pSender)
        	if nil == pSender or nil == pDisplayValueLabel then
        		return
        	end
        	local pControl = tolua.cast(pSender,"CCControlSlider")
        	local strFmt = nil
        	if pControl:getTag() == 1 then
        		strFmt = string.format("Upper slider value = %.02f",pControl:getValue())
        	elseif pControl:getTag() == 2 then
        		strFmt = string.format("Lower slider value = %.02f",pControl:getValue())
        	end

        	if nil ~= strFmt then
        		pDisplayValueLabel:setString(CCString:create(strFmt):getCString())
        	end
        end
        --Add the slider
        local pSlider = CCControlSlider:create("extensions/sliderTrack.png","extensions/sliderProgress.png" ,"extensions/sliderThumb.png")
        pSlider:setAnchorPoint(ccp(0.5, 1.0))
        pSlider:setMinimumValue(0.0)
        pSlider:setMaximumValue(5.0)
        pSlider:setPosition(ccp(screenSize.width / 2.0, screenSize.height / 2.0 + 16))
		pSlider:setTag(1)

        --When the value of the slider will change, the given selector will be call
        pSlider:addHandleOfControlEvent(valueChanged, CCControlEventValueChanged)

		local pRestrictSlider = CCControlSlider:create("extensions/sliderTrack.png","extensions/sliderProgress.png" ,"extensions/sliderThumb.png")
        pRestrictSlider:setAnchorPoint(ccp(0.5, 1.0))
        pRestrictSlider:setMinimumValue(0.0)
        pRestrictSlider:setMaximumValue(5.0)
		pRestrictSlider:setMaximumAllowedValue(4.0)
		pRestrictSlider:setMinimumAllowedValue(1.5)
		pRestrictSlider:setValue(3.0)
        pRestrictSlider:setPosition(ccp(screenSize.width / 2.0, screenSize.height / 2.0 - 24))
		pRestrictSlider:setTag(2)
		--same with restricted
		pRestrictSlider:addHandleOfControlEvent(valueChanged, CCControlEventValueChanged)
	    pLayer:addChild(pSlider)
		pLayer:addChild(pRestrictSlider)
	end

	--ColourPickerTest
	local function InitColourPickerTest(pLayer)
		if nil == pLayer then
			return
		end
		local screenSize = CCDirector:sharedDirector():getWinSize()
		local pColorLabel = nil

        local pNode  = CCNode:create()
        pNode:setPosition(ccp (screenSize.width / 2, screenSize.height / 2))
        pLayer:addChild(pNode, 1)

        local dLayer_width = 0

        --Create the colour picker,pStrEventName not use
        local function colourValueChanged(pStrEventName,pSender)
        	if nil == pSender or nil == pColorLabel then
        		return
        	end

        	local pPicker = tolua.cast(pSender,"CCControlColourPicker")
        	local strFmt  = string.format("#%02X%02X%02X",pPicker:getColor().r, pPicker:getColor().g, pPicker:getColor().b)
        	pColorLabel:setString(CCString:create(strFmt):getCString())
        end
        local pColourPicker = CCControlColourPicker:create()
        pColourPicker:setColor(ccc3(37, 46, 252))
        pColourPicker:setPosition(ccp (pColourPicker:getContentSize().width / 2, 0))
        pColourPicker:addHandleOfControlEvent(colourValueChanged, CCControlEventValueChanged)
        pNode:addChild(pColourPicker)

	    dLayer_width = dLayer_width + pColourPicker:getContentSize().width

	   --Add the black background for the text
        local pBackground = CCScale9Sprite:create("extensions/buttonBackground.png")
        pBackground:setContentSize(CCSizeMake(150, 50))
        pBackground:setPosition(ccp(dLayer_width + pBackground:getContentSize().width / 2.0, 0))
        pNode:addChild(pBackground)
        dLayer_width = dLayer_width + pBackground:getContentSize().width

        pColorLabel = CCLabelTTF:create("#color", "Marker Felt", 30)
        pColorLabel:retain()
		pColorLabel:setPosition(pBackground:getPosition())
        pNode:addChild(pColorLabel)

        --Set the layer size
        pNode:setContentSize(CCSizeMake(dLayer_width, 0))
        pNode:setAnchorPoint(ccp (0.5, 0.5))

        --Update the color text
	    colourValueChanged("", pColourPicker)
	end

	--SwitchTest
	local function InitSwitchTest(pLayer)
		if nil == pLayer then
			return
		end

		local screenSize = CCDirector:sharedDirector():getWinSize()

        local pNode = CCNode:create()
        pNode:setPosition(ccp (screenSize.width / 2, screenSize.height / 2))
        pLayer:addChild(pNode, 1)

        local dLayer_width = 0

        --Add the black background for the text
        local pBackground = CCScale9Sprite:create("extensions/buttonBackground.png")
        pBackground:setContentSize(CCSizeMake(80, 50))
        pBackground:setPosition(ccp(dLayer_width + pBackground:getContentSize().width / 2.0, 0))
        pNode:addChild(pBackground)
        dLayer_width = dLayer_width + pBackground:getContentSize().width

        local pDisplayValueLabel  = CCLabelTTF:create("#color" ,"Marker Felt" ,30)
        pDisplayValueLabel:retain()

        pDisplayValueLabel:setPosition(pBackground:getPosition())
        pNode:addChild(pDisplayValueLabel)

        --Create the switch
        local function valueChanged(strEventName,pSender)
        	if nil == pDisplayValueLabel or nil == pSender then
        		return
        	end

        	local pControl = tolua.cast(pSender,"CCControlSwitch")
        	if pControl:isOn() then
        		pDisplayValueLabel:setString("On")
        	else
        		pDisplayValueLabel:setString("Off")
        	end
        end
        local pSwitchControl = CCControlSwitch:create(
                CCSprite:create("extensions/switch-mask.png"),
                CCSprite:create("extensions/switch-on.png"),
                CCSprite:create("extensions/switch-off.png"),
                CCSprite:create("extensions/switch-thumb.png"),
                CCLabelTTF:create("On", "Arial-BoldMT", 16),
                CCLabelTTF:create("Off", "Arial-BoldMT", 16)
            )
        pSwitchControl:setPosition(ccp (dLayer_width + 10 + pSwitchControl:getContentSize().width / 2, 0))
        pNode:addChild(pSwitchControl)
        pSwitchControl:addHandleOfControlEvent(valueChanged, CCControlEventValueChanged)

        --Set the layer size
        pNode:setContentSize(CCSizeMake(dLayer_width, 0))
        pNode:setAnchorPoint(ccp (0.5, 0.5))

        --Update the value label
        valueChanged("", pSwitchControl)
	end

	--Hvs:HelloVariableSize
	local function HvsStandardButtonWithTitle(pStrTitle)
	    -- Creates and return a button with a default background and title color.
    	local pBackgroundButton = CCScale9Sprite:create("extensions/button.png")
    	local pBackgroundHighlightedButton = CCScale9Sprite:create("extensions/buttonHighlighted.png")

    	pTitleButton = CCLabelTTF:create(pStrTitle, "Marker Felt", 30)

    	pTitleButton:setColor(ccc3(159, 168, 176))

    	local pButton = CCControlButton:create(pTitleButton, pBackgroundButton)
    	pButton:setBackgroundSpriteForState(pBackgroundHighlightedButton, CCControlStateHighlighted)
    	pButton:setTitleColorForState(ccc3(255,255,255), CCControlStateHighlighted)

    	return pButton
	end

	local function InitHelloVariableSize(pLayer)
		if nil == pLayer then
			return
		end

		local screenSize = CCDirector:sharedDirector():getWinSize()
		local strArray   = CCArray:create()
		strArray:addObject(CCString:create("Hello"))
		strArray:addObject(CCString:create("Variable"))
		strArray:addObject(CCString:create("Size"))
		strArray:addObject(CCString:create("!"))

		local pNode = CCNode:create()
		pLayer:addChild(pNode,1)
		local dTotalWidth = 0
		local dHeight     = 0
		local pObj        = nil

		local i = 0
    	local nLen = strArray:count()
    	for i = 0, nLen - 1 do
        	pObj = tolua.cast(strArray:objectAtIndex(i), "CCString")
        	--Creates a button with pLayer string as title
            local pButton = HvsStandardButtonWithTitle(pObj:getCString())
            pButton:setPosition(ccp (dTotalWidth + pButton:getContentSize().width / 2, pButton:getContentSize().height / 2))
            pNode:addChild(pButton)

            --Compute the size of the layer
            dHeight = pButton:getContentSize().height
            dTotalWidth = dTotalWidth + pButton:getContentSize().width
    	end

		pNode:setAnchorPoint(ccp (0.5, 0.5))
        pNode:setContentSize(CCSizeMake(dTotalWidth, dHeight))
        pNode:setPosition(ccp(screenSize.width / 2.0, screenSize.height / 2.0))

        --Add the black background
        local pBackground = CCScale9Sprite:create("extensions/buttonBackground.png")
        pBackground:setContentSize(CCSizeMake(dTotalWidth + 14, dHeight + 14))
        pBackground:setPosition(ccp(screenSize.width / 2.0, screenSize.height / 2.0))
        pLayer:addChild(pBackground)
	end

	local function StylingStandardButtonWithTitle(pStrTitle)
    	local pBackgroundButton = CCScale9Sprite:create("extensions/button.png")
    	pBackgroundButton:setPreferredSize(CCSizeMake(45, 45))
    	local pBackgroundHighlightedButton = CCScale9Sprite:create("extensions/buttonHighlighted.png")
    	pBackgroundHighlightedButton:setPreferredSize(CCSizeMake(45, 45))

        local pTitleButton = CCLabelTTF:create(pStrTitle, "Marker Felt", 30)

    	pTitleButton:setColor(ccc3(159, 168, 176))

    	local pButton = CCControlButton:create(pTitleButton, pBackgroundButton)
        pButton:setBackgroundSpriteForState(pBackgroundHighlightedButton, CCControlStateHighlighted)
    	pButton:setTitleColorForState(ccc3(255,255,255), CCControlStateHighlighted)

        return pButton
	end

	local function InitStyling(pLayer)
		if nil == pLayer then
			return
		end

		local screenSize = CCDirector:sharedDirector():getWinSize()

        local pNode = CCNode:create()
        pLayer:addChild(pNode, 1)

        local nSpace = 10

        local nMax_w = 0
        local nMax_h = 0
        local i = 0
        local j = 0
        for i = 0, 2 do
          for j = 0, 2 do
          	    --Add the buttons
          	    local strFmt = string.format("%d",math.random(0,32767) % 30)
                local pButton = StylingStandardButtonWithTitle(CCString:create(strFmt):getCString())
                pButton:setAdjustBackgroundImage(false)
                pButton:setPosition(ccp (pButton:getContentSize().width / 2 + (pButton:getContentSize().width + nSpace) * i,
                                         pButton:getContentSize().height / 2 + (pButton:getContentSize().height + nSpace) * j))

                pNode:addChild(pButton)

                nMax_w = math.max(pButton:getContentSize().width * (i + 1) + nSpace  * i, nMax_w)
                nMax_h = math.max(pButton:getContentSize().height * (j + 1) + nSpace * j, nMax_h)
          end
        end

        pNode:setAnchorPoint(ccp (0.5, 0.5))
        pNode:setContentSize(CCSizeMake(nMax_w, nMax_h))
        pNode:setPosition(ccp(screenSize.width / 2.0, screenSize.height / 2.0))

        --Add the black background
        local pBackgroundButton = CCScale9Sprite:create("extensions/buttonBackground.png")
        pBackgroundButton:setContentSize(CCSizeMake(nMax_w + 14, nMax_h + 14))
        pBackgroundButton:setPosition(ccp(screenSize.width / 2.0, screenSize.height / 2.0))
        pLayer:addChild(pBackgroundButton)
	end

	local function InitButtonTestEvent(pLayer)
		if nil == pLayer then
			return
		end

		local screenSize = CCDirector:sharedDirector():getWinSize()

        --Add a label in which the button events will be displayed
        local pDisplayValueLabel = nil
        pDisplayValueLabel = CCLabelTTF:create("No Event", "Marker Felt", 32)
        pDisplayValueLabel:setAnchorPoint(ccp(0.5, -1))
       	pDisplayValueLabel:setPosition(ccp(screenSize.width / 2.0, screenSize.height / 2.0))
        pLayer:addChild(pDisplayValueLabel, 1)

        --Add the button
        local pBackgroundButton            = CCScale9Sprite:create("extensions/button.png")
        local pBackgroundHighlightedButton = CCScale9Sprite:create("extensions/buttonHighlighted.png")

        local pTitleButtonLabel = CCLabelTTF:create("Touch Me!", "Marker Felt", 30)
        pTitleButtonLabel:setColor(ccc3(159, 168, 176))

        local pControlButton = CCControlButton:create(pTitleButtonLabel, pBackgroundButton)
        local function touchDownAction()
        	if nil == pDisplayValueLabel then
        		return
        	end
        	pDisplayValueLabel:setString(CCString:create("Touch Down"):getCString())
        end

        local function touchDragInsideAction()
        	if nil == pDisplayValueLabel then
        		return
        	end
        	pDisplayValueLabel:setString(CCString:create("Drag Inside"):getCString())
        end

        local function touchDragOutsideAction()
        	if nil == pDisplayValueLabel then
        		return
        	end
        	pDisplayValueLabel:setString(CCString:create("Drag Outside"):getCString())
        end

        local function touchDragEnterAction()
        	if nil == pDisplayValueLabel then
        		return
        	end
        	pDisplayValueLabel:setString(CCString:create("Drag Enter"):getCString())
        end

        local function touchDragExitAction()
        	if nil == pDisplayValueLabel then
        		return
        	end
        	pDisplayValueLabel:setString(CCString:create("Drag Exit"):getCString())
        end

        local function touchUpInsideAction()
        	if nil == pDisplayValueLabel then
        		return
        	end
        	pDisplayValueLabel:setString(CCString:create("Touch Up Inside."):getCString())
        end

        local function touchUpOutsideAction()
        	if nil == pDisplayValueLabel then
        		return
        	end
        	pDisplayValueLabel:setString(CCString:create("Touch Up Outside."):getCString())
        end

        local function touchCancelAction()
        	if nil == pDisplayValueLabel then
        		return
        	end
        	pDisplayValueLabel:setString(CCString:create("Touch Cancel"):getCString())
        end

        pControlButton:setBackgroundSpriteForState(pBackgroundHighlightedButton, CCControlStateHighlighted)
        pControlButton:setTitleColorForState(ccc3(255, 255, 255), CCControlStateHighlighted)
        pControlButton:setAnchorPoint(ccp(0.5, 1))
        pControlButton:setPosition(ccp(screenSize.width / 2.0, screenSize.height / 2.0))
        pControlButton:addHandleOfControlEvent(touchDownAction,CCControlEventTouchDown)
        pControlButton:addHandleOfControlEvent(touchDragInsideAction,CCControlEventTouchDragInside)
        pControlButton:addHandleOfControlEvent(touchDragOutsideAction,CCControlEventTouchDragOutside)
        pControlButton:addHandleOfControlEvent(touchDragEnterAction,CCControlEventTouchDragEnter)
        pControlButton:addHandleOfControlEvent(touchDragExitAction,CCControlEventTouchDragExit)
        pControlButton:addHandleOfControlEvent(touchUpInsideAction,CCControlEventTouchUpInside)
        pControlButton:addHandleOfControlEvent(touchUpOutsideAction,CCControlEventTouchUpOutside)
        pControlButton:addHandleOfControlEvent(touchCancelAction,CCControlEventTouchCancel)
        pLayer:addChild(pControlButton, 1)

		--Add the black background
        local pBackgroundButton = CCScale9Sprite:create("extensions/buttonBackground.png")
        pBackgroundButton:setContentSize(CCSizeMake(300, 170))
        pBackgroundButton:setPosition(ccp(screenSize.width / 2.0, screenSize.height / 2.0))
        pLayer:addChild(pBackgroundButton)
	end
	--PotentiometerTest
	local function InitPotentiometerTest(pLayer)
		if nil == pLayer then
			return
		end

		local screenSize = CCDirector:sharedDirector():getWinSize()

        local pNode = CCNode:create()
        pNode:setPosition(ccp (screenSize.width / 2, screenSize.height / 2))
        pLayer:addChild(pNode, 1)

        local dLayer_width = 0

        -- Add the black background for the text
        local pBackground  = CCScale9Sprite:create("extensions/buttonBackground.png")
        pBackground:setContentSize(CCSizeMake(80, 50))
        pBackground:setPosition(ccp(dLayer_width + pBackground:getContentSize().width / 2.0, 0))
        pNode:addChild(pBackground)

        dLayer_width = dLayer_width + pBackground:getContentSize().width

        local pDisplayValueLabel = CCLabelTTF:create("", "HelveticaNeue-Bold", 30)
        pDisplayValueLabel:setPosition(pBackground:getPosition())
        pNode:addChild(pDisplayValueLabel)

        -- Add the slider
        local function valueChanged(strEventName,pSender)
        	if nil == pSender then
        		return
        	end

        	local pControl = tolua.cast(pSender,"CCControlPotentiometer")
        	local strFmt = string.format("%0.2f",pControl:getValue())
        	pDisplayValueLabel:setString(CCString:create(strFmt):getCString())
        end
        local pPotentiometer = CCControlPotentiometer:create("extensions/potentiometerTrack.png","extensions/potentiometerProgress.png"
                                                                               ,"extensions/potentiometerButton.png")
        pPotentiometer:setPosition(ccp (dLayer_width + 10 + pPotentiometer:getContentSize().width / 2, 0))

        -- When the value of the slider will change, the given selector will be call
        pPotentiometer:addHandleOfControlEvent(valueChanged, CCControlEventValueChanged)

		pNode:addChild(pPotentiometer)

        dLayer_width = dLayer_width + pPotentiometer:getContentSize().width

        -- Set the layer size
        pNode:setContentSize(CCSizeMake(dLayer_width, 0))
        pNode:setAnchorPoint(ccp (0.5, 0.5))

        -- Update the value label
        valueChanged("", pPotentiometer)
	end

	local function InitStepperTest(pLayer)
		if nil == pLayer then
			return
		end

		local screenSize = CCDirector:sharedDirector():getWinSize()

        local pNode = CCNode:create()
        pNode:setPosition(ccp (screenSize.width / 2, screenSize.height / 2))
        pLayer:addChild(pNode, 1)

        local layer_width          = 0

        -- Add the black background for the text
        local background  = CCScale9Sprite:create("extensions/buttonBackground.png")
        background:setContentSize(CCSizeMake(100, 50))
        background:setPosition(ccp(layer_width + background:getContentSize().width / 2.0, 0))
        pNode:addChild(background)

        local pDisplayValueLabel =  CCLabelTTF:create("0", "HelveticaNeue-Bold", 30)

        pDisplayValueLabel:setPosition(background:getPosition())
        pNode:addChild(pDisplayValueLabel)

        layer_width   = layer_width + background:getContentSize().width

        local minusSprite       = CCSprite:create("extensions/stepper-minus.png")
    	local plusSprite        = CCSprite:create("extensions/stepper-plus.png")

    	local function valueChanged(strEventName,pSender)
    		if nil == pDisplayValueLabel or nil == pSender then
    			return
    		end

    		local pControl = tolua.cast(pSender,"CCControlStepper")
    		local strFmt   = string.format("%0.02f",pControl:getValue() )
    		pDisplayValueLabel:setString(CCString:create(strFmt):getCString())
    	end
        local stepper   = CCControlStepper:create(minusSprite, plusSprite)
        stepper:setPosition(ccp (layer_width + 10 + stepper:getContentSize().width / 2, 0))
        stepper:addHandleOfControlEvent(valueChanged, CCControlEventValueChanged)
        pNode:addChild(stepper)

        layer_width  = layer_width + stepper:getContentSize().width

        -- Set the layer size
        pNode:setContentSize(CCSizeMake(layer_width, 0))
        pNode:setAnchorPoint(ccp (0.5, 0.5))

        -- Update the value label
        valueChanged("", stepper)
	end

	local function InitSpecialSceneLayer(pLayer)
		if ControlExtensionsTestEnum.kCCControlSliderTest == nCurCase then
			   InitSliderTest(pLayer)
    	elseif ControlExtensionsTestEnum.kCCControlColourPickerTest == nCurCase then
    		   InitColourPickerTest(pLayer)
    	elseif ControlExtensionsTestEnum.kCCControlSwitchTest == nCurCase then
    	       InitSwitchTest(pLayer)
    	elseif ControlExtensionsTestEnum.kCCControlButtonTest_HelloVariableSize == nCurCase then
    		   InitHelloVariableSize(pLayer)
    	elseif ControlExtensionsTestEnum.kCCControlButtonTest_Event == nCurCase then
    		   InitButtonTestEvent(pLayer)
    	elseif ControlExtensionsTestEnum.kCCControlButtonTest_Styling == nCurCase then
    		   InitStyling(pLayer)
    	elseif ControlExtensionsTestEnum.kCCControlPotentiometerTest == nCurCase then
    		   InitPotentiometerTest(pLayer)
    	elseif ControlExtensionsTestEnum.kCCControlStepperTest == nCurCase then
    	       InitStepperTest(pLayer)
    	end
	end

    function CurrentControlScene()
    	pNewScene = nil
		pNewScene = CCScene:create()
		local pNewLayer = CCLayer:create()
    	BaseInitSceneLayer(pNewLayer,GetControlExtensionsTitle())
    	InitSpecialSceneLayer(pNewLayer)
		pNewScene:addChild(pNewLayer)
		if nil ~= pNewScene then
		    CCDirector:sharedDirector():replaceScene(pNewScene)
		end

    end

    local pNewLayer = CCLayer:create()
    BaseInitSceneLayer(pNewLayer,GetControlExtensionsTitle())
    InitSpecialSceneLayer(pNewLayer)
	pNewScene:addChild(pNewLayer)

	return pNewScene
end

local function runEditBoxTest()
	local newScene = CCScene:create()
	local newLayer = CCLayer:create()
	local visibleOrigin = CCEGLView:sharedOpenGLView():getVisibleOrigin()
    local visibleSize = CCEGLView:sharedOpenGLView():getVisibleSize()

    local pBg = CCSprite:create("Images/HelloWorld.png")
    pBg:setPosition(ccp(visibleOrigin.x+visibleSize.width/2, visibleOrigin.y+visibleSize.height/2))
    newLayer:addChild(pBg)

    local TTFShowEditReturn = CCLabelTTF:create("No edit control return!", "", 30)
    TTFShowEditReturn:setPosition(ccp(visibleOrigin.x+visibleSize.width/2, visibleOrigin.y + visibleSize.height - 50))
    newLayer:addChild(TTFShowEditReturn)

    -- Back Menu
	local pToMainMenu = CCMenu:create()
    CreateExtensionsBasicLayerMenu(pToMainMenu)
    pToMainMenu:setPosition(ccp(0, 0))
    newLayer:addChild(pToMainMenu,10)

    local editBoxSize = CCSizeMake(visibleSize.width - 100, 60)
    local EditName = nil
    local EditPassword = nil
    local EditEmail = nil

	local function editBoxTextEventHandle(strEventName,pSender)
		local edit = tolua.cast(pSender,"CCEditBox")
		local strFmt
		if strEventName == "began" then
			strFmt = string.format("editBox %p DidBegin !", edit)
			print(strFmt)
		elseif strEventName == "ended" then
			strFmt = string.format("editBox %p DidEnd !", edit)
			print(strFmt)
		elseif strEventName == "return" then
			strFmt = string.format("editBox %p was returned !",edit)
			if edit == EditName then
				TTFShowEditReturn:setString("Name EditBox return !")
			elseif edit == EditPassword then
				TTFShowEditReturn:setString("Password EditBox return !")
			elseif edit == EditEmail then
				TTFShowEditReturn:setString("Email EditBox return !")
			end
			print(strFmt)
		elseif strEventName == "changed" then
			strFmt = string.format("editBox %p TextChanged, text: %s ", edit, edit:getText())
			print(strFmt)
		end
	end
    -- top
    EditName = CCEditBox:create(editBoxSize, CCScale9Sprite:create("extensions/green_edit.png"))
    EditName:setPosition(ccp(visibleOrigin.x+visibleSize.width/2, visibleOrigin.y+visibleSize.height*3/4))
    local targetPlatform = CCApplication:sharedApplication():getTargetPlatform()
    if kTargetIphone == targetPlatform or kTargetIpad == targetPlatform then
	   EditName:setFontName("Paint Boy")
	else
		EditName:setFontName("fonts/Paint Boy.ttf")
	end
    EditName:setFontSize(25)
    EditName:setFontColor(ccc3(255,0,0))
    EditName:setPlaceHolder("Name:")
    EditName:setPlaceholderFontColor(ccc3(255,255,255))
    EditName:setMaxLength(8)
    EditName:setReturnType(kKeyboardReturnTypeDone)
	--Handler
	EditName:registerScriptEditBoxHandler(editBoxTextEventHandle)
    newLayer:addChild(EditName)

    --middle
    EditPassword = CCEditBox:create(editBoxSize, CCScale9Sprite:create("extensions/orange_edit.png"))
    EditPassword:setPosition(ccp(visibleOrigin.x+visibleSize.width/2, visibleOrigin.y+visibleSize.height/2))
	if kTargetIphone == targetPlatform or kTargetIpad == targetPlatform then
		EditPassword:setFont("American Typewriter", 30)
	else
		EditPassword:setFont("fonts/American Typewriter.ttf", 30)
	end

    EditPassword:setFontColor(ccc3(0,255,0))
    EditPassword:setPlaceHolder("Password:")
    EditPassword:setMaxLength(6)
    EditPassword:setInputFlag(kEditBoxInputFlagPassword)
    EditPassword:setInputMode(kEditBoxInputModeSingleLine)
	EditPassword:registerScriptEditBoxHandler(editBoxTextEventHandle)
    newLayer:addChild(EditPassword)

    --bottom
    EditEmail = CCEditBox:create(CCSizeMake(editBoxSize.width, editBoxSize.height), CCScale9Sprite:create("extensions/yellow_edit.png"))
    EditEmail:setPosition(ccp(visibleOrigin.x+visibleSize.width/2, visibleOrigin.y+visibleSize.height/4))
    EditEmail:setAnchorPoint(ccp(0.5, 1.0))
    EditEmail:setPlaceHolder("Email:")
    EditEmail:setInputMode(kEditBoxInputModeEmailAddr)
    EditEmail:registerScriptEditBoxHandler(editBoxTextEventHandle)
    newLayer:addChild(EditEmail)
    newLayer:setPosition(ccp(10, 20))

	newScene:addChild(newLayer)
	return newScene
end

local CreateExtensionsTestTable =
{
	runNotificationCenterTest,
	runCCControlTest,
	runCocosBuilder,
	runWebSocketTest,
	runEditBoxTest,
	runTableViewTest,
}

local s = CCDirector:sharedDirector():getWinSize()

local function ExtensionsMainLayer()

	local function CreateExtensionsTestScene(nPerformanceNo)
	  	local pNewscene = CreateExtensionsTestTable[nPerformanceNo]()
  		return pNewscene
	end

	local function menuCallback(tag, pMenuItem)
		local scene = nil
    	local nIdx = pMenuItem:getZOrder() - kItemTagBasic
		local ExtensionsTestScene = CreateExtensionsTestScene(nIdx)
    	if nil ~= ExtensionsTestScene then
         	CCDirector:sharedDirector():replaceScene(ExtensionsTestScene)
    	end
	end

	local layer = CCLayer:create()
	local menu = CCMenu:create()
    menu:setPosition(CCPointMake(0, 0))
    CCMenuItemFont:setFontName("Arial")
    CCMenuItemFont:setFontSize(24)
    local targetPlatform = CCApplication:sharedApplication():getTargetPlatform()
    local bSupportWebSocket = false
    if (kTargetIphone == targetPlatform) or (kTargetIpad == targetPlatform) or (kTargetAndroid == targetPlatform) or (kTargetWindows == targetPlatform) then
        bSupportWebSocket = true
    end
    local bSupportEdit = false
    if (kTargetIphone == targetPlatform) or (kTargetIpad == targetPlatform) or
        (kTargetAndroid == targetPlatform) or (kTargetWindows == targetPlatform) or
        (kTargetMacOS == targetPlatform) or (kTargetTizen == targetPlatform) then
        bSupportEdit = true
    end
    for i = 1, ExtensionTestEnum.TEST_MAX_COUNT do
		local item = CCMenuItemFont:create(testsName[i])
	    item:registerScriptTapHandler(menuCallback)
        item:setPosition(s.width / 2, s.height - i * LINE_SPACE)
        menu:addChild(item, kItemTagBasic + i)
        if ((i == ExtensionTestEnum.TEST_WEBSOCKET + 1) and (false == bSupportWebSocket))
        or ((i == ExtensionTestEnum.TEST_EDITBOX + 1) and (false == bSupportEdit)) then
            item:setEnabled(false)
        end
	end

    layer:addChild(menu)

	return layer
end

-------------------------------------
--  Extensions Test
-------------------------------------
function ExtensionsTestMain()
	local scene = CCScene:create()

	scene:addChild(ExtensionsMainLayer())
	scene:addChild(CreateBackMenuItem())

	return scene
end


text:
import {toDOM, nodeToDOM} from "../format"
import {elt} from "../dom"

import {DIRTY_REDRAW} from "./main"
import {childContainer} from "./dompos"

function options(ranges) {
  return {
    pos: 0,
    preRenderContent() { this.pos++ },
    postRenderContent() { this.pos++ },

    onRender(node, dom, offset) {
      if (node.isBlock) {
        if (offset != null)
          dom.setAttribute("pm-offset", offset)
        dom.setAttribute("pm-size", node.nodeSize)
        if (node.isTextblock)
          adjustTrailingHacks(dom, node)
        if (dom.contentEditable == "false")
          dom = elt("div", null, dom)
        if (!node.type.contains) this.pos++
      }

      return dom
    },
    onContainer(node) {
      node.setAttribute("pm-container", true)
    },
    // : (Node, DOMNode, number) → DOMNode
    renderInlineFlat(node, dom, offset) {
      ranges.advanceTo(this.pos)
      let pos = this.pos, end = pos + node.nodeSize
      let nextCut = ranges.nextChangeBefore(end)

      let inner = dom, wrapped
      for (let i = 0; i < node.marks.length; i++) inner = inner.firstChild

      if (dom.nodeType != 1) {
        dom = elt("span", null, dom)
        if (nextCut == -1) wrapped = dom
      }
      if (!wrapped && (nextCut > -1 || ranges.current.length)) {
        wrapped = inner == dom ? (dom = elt("span", null, inner))
                               : inner.parentNode.appendChild(elt("span", null, inner))
      }

      dom.setAttribute("pm-offset", offset)
      dom.setAttribute("pm-size", node.nodeSize)

      let inlineOffset = 0
      while (nextCut > -1) {
        let size = nextCut - pos
        let split = splitSpan(wrapped, size)
        if (ranges.current.length)
          split.className = ranges.current.join(" ")
        split.setAttribute("pm-inner-offset", inlineOffset)
        inlineOffset += size
        ranges.advanceTo(nextCut)
        nextCut = ranges.nextChangeBefore(end)
        if (nextCut == -1)
          wrapped.setAttribute("pm-inner-offset", inlineOffset)
        pos += size
      }

      if (ranges.current.length)
        wrapped.className = ranges.current.join(" ")
      this.pos += node.nodeSize
      return dom
    },
    document
  }
}

function splitSpan(span, at) {
  let textNode = span.firstChild, text = textNode.nodeValue
  let newNode = span.parentNode.insertBefore(elt("span", null, text.slice(0, at)), span)
  textNode.nodeValue = text.slice(at)
  return newNode
}

export function draw(pm, doc) {
  pm.content.textContent = ""
  pm.content.appendChild(toDOM(doc, options(pm.ranges.activeRangeTracker())))
}

function adjustTrailingHacks(dom, node) {
  let needs = node.content.size == 0 || node.lastChild.type.isBR ||
      (node.type.isCode && node.lastChild.isText && /\n$/.test(node.lastChild.text))
      ? "br" : !node.lastChild.isText && node.lastChild.type.contains == null ? "text" : null
  let last = dom.lastChild
  let has = !last || last.nodeType != 1 || !last.hasAttribute("pm-ignore") ? null
      : last.nodeName == "BR" ? "br" : "text"
  if (needs != has) {
    if (has) dom.removeChild(last)
    if (needs) dom.appendChild(needs == "br" ? elt("br", {"pm-ignore": "trailing-break"})
                               : elt("span", {"pm-ignore": "cursor-text"}, ""))
  }
}

function findNodeIn(parent, i, node) {
  for (; i < parent.childCount; i++) {
    let child = parent.child(i)
    if (child == node) return i
  }
  return -1
}

function movePast(dom) {
  let next = dom.nextSibling
  dom.parentNode.removeChild(dom)
  return next
}

export function redraw(pm, dirty, doc, prev) {
  if (dirty.get(prev) == DIRTY_REDRAW) return draw(pm, doc)

  let opts = options(pm.ranges.activeRangeTracker())

  function scan(dom, node, prev, pos) {
    let iPrev = 0, pChild = prev.firstChild
    let domPos = dom.firstChild

    for (let iNode = 0, offset = 0; iNode < node.childCount; iNode++) {
      let child = node.child(iNode), matching, reuseDOM
      let found = pChild == child ? iPrev : findNodeIn(prev, iPrev + 1, child)
      if (found > -1) {
        matching = child
        while (iPrev != found) {
          iPrev++
          domPos = movePast(domPos)
        }
      }

      if (matching && !dirty.get(matching)) {
        reuseDOM = true
      } else if (pChild && !child.isText && child.sameMarkup(pChild) && dirty.get(pChild) != DIRTY_REDRAW) {
        reuseDOM = true
        if (pChild.type.contains)
          scan(childContainer(domPos), child, pChild, pos + offset + 1)
      } else {
        opts.pos = pos + offset
        let rendered = nodeToDOM(child, opts, offset)
        dom.insertBefore(rendered, domPos)
        reuseDOM = false
      }

      if (reuseDOM) {
        domPos.setAttribute("pm-offset", offset)
        domPos.setAttribute("pm-size", child.nodeSize)
        domPos = domPos.nextSibling
        pChild = prev.maybeChild(++iPrev)
      }
      offset += child.nodeSize
    }

    while (pChild) {
      domPos = movePast(domPos)
      pChild = prev.maybeChild(++iPrev)
    }
    if (node.isTextblock) adjustTrailingHacks(dom, node)
  }
  scan(pm.content, doc, prev, 0)
}


text:
package com.github.seraphain.examples.spring.ws.beans;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.bind.annotation.XmlSeeAlso;

import com.github.seraphain.examples.spring.ws.beans.ObjectFactory;
import com.github.seraphain.examples.spring.ws.beans.TestReq;
import com.github.seraphain.examples.spring.ws.beans.TestRsp;
import com.github.seraphain.examples.spring.ws.beans.WsException_Exception;

/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2.9-b130926.1035
 * Generated source version: 2.2
 *
 */
@WebService(name = "exampleServiceApi", targetNamespace = "http://seraphain.github.com/service")
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
@XmlSeeAlso({
    ObjectFactory.class
})
public interface ExampleServiceApi {

    /**
     *
     * @param testReq
     * @return
     *     returns com.github.seraphain.examples.spring.ws.beans.TestRsp
     * @throws WsException_Exception
     */
    @WebMethod
    @WebResult(name = "testRsp", targetNamespace = "http://seraphain.github.com/service", partName = "testRsp")
    public TestRsp test(
        @WebParam(name = "testReq", targetNamespace = "http://seraphain.github.com/service", partName = "testReq")
        TestReq testReq)
        throws WsException_Exception
    ;

}