text:
<?php
namespace Codeception\Module;

use Codeception\Exception\ModuleRequire;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpKernel\Exception\FlattenException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpFoundation\Response;

/**
 * This module uses Symfony2 Crawler and HttpKernel to emulate requests and get response.
 *
 * It implements common Framework interface.
 *
 * ## Status
 *
 * * Maintainer: **davert**
 * * Stability: **stable**
 * * Contact: codecept@davert.mail.ua
 *
 * ## Config
 *
 * * app_path: 'app' - specify custom path to your app dir, where bootstrap cache and kernel interface is located.
 * * environment: 'local' - environment used for load kernel
 * * debug: true - switch debug mode
*
 * ### Example (`functional.suite.yml`)
 *
 *     modules:
 *        enabled: [Symfony2]
 *        config:
 *           Symfony2:
 *              app_path: 'app/front'
 *              environment: 'local_test'
 *              debug: true
 *
 * ## Public Properties
 *
 * * kernel - HttpKernel instance
 * * client - current Crawler instance
 * * container - dependency injection container instance
 *
 */

class Symfony2 extends \Codeception\Lib\Framework
{
    /**
     * @var \Symfony\Component\HttpKernel\Kernel
     */
    public $kernel;

    /**
     * @var \Symfony\Component\DependencyInjection\ContainerInterface
     */
    public $container;

    public $config = array('app_path' => 'app', 'environment' => 'test', 'debug' => true);

    /**
     * @var
     */
    protected $kernelClass;

    protected $clientClass = '\Symfony\Component\HttpKernel\Client';

    public function _initialize() {
        $cache = \Codeception\Configuration::projectDir() . $this->config['app_path'] . DIRECTORY_SEPARATOR . 'bootstrap.php.cache';
        if (!file_exists($cache)) throw new ModuleRequire(__CLASS__, 'Symfony2 bootstrap file not found in '.$cache);
        require_once $cache;
        $this->kernelClass = $this->getKernelClass();
        $this->kernel = new $this->kernelClass($this->config['environment'], $this->config['debug']);
    }

    public function _before(\Codeception\TestCase $test) {
        $this->kernel->boot();
        $this->container = $this->kernel->getContainer();
        if ($this->container->has('test.client')) { // it is Symfony2.2
            $this->client = $this->container->get('test.client');
        } else {
            $this->client = new $this->clientClass($this->kernel);
        }
        $this->client->followRedirects(true);
    }

    public function _after(\Codeception\TestCase $test) {
        $this->kernel->shutdown();
        parent::_after($test);
    }

    /**
     * Attempts to guess the kernel location.
     *
     * When the Kernel is located, the file is required.
     *
     * @return string The Kernel class name
     */
    protected function getKernelClass()
    {
        $finder = new Finder();
        $finder->name('*Kernel.php')->depth('0')->in(\Codeception\Configuration::projectDir() . $this->config['app_path']);
        $results = iterator_to_array($finder);
        if (!count($results)) {
            throw new ModuleRequire(__CLASS__, 'AppKernel was not found. Specify directory where Kernel class for your application is located in "app_dir" parameter.');
        }

        $file = current($results);
        $class = $file->getBasename('.php');

        require_once $file;

        return $class;
    }

    /**
     * Checks if any email were sent by last request
     *
     * @throws \LogicException
     */
    public function seeEmailIsSent() {
        $profile = $this->getProfiler();
        if (!$profile) \PHPUnit_Framework_Assert::fail('Emails can\'t be tested without Profiler');
        if (!$profile->hasCollector('swiftmailer')) \PHPUnit_Framework_Assert::fail('Emails can\'t be tested without SwiftMailer connector');

        \PHPUnit_Framework_Assert::assertGreaterThan(0, $profile->getCollector('swiftmailer')->getMessageCount());
    }

    /**
     * Grabs a service from Symfony DIC container.
     * Recommended to use for unit testing.
     *
     * ``` php
     * <?php
     * $em = $I->grabServiceFromContainer('doctrine');
     * ?>
     * ```
     *
     * @param $service
     * @return mixed
     */
    public function grabServiceFromContainer($service) {
        if (!$this->kernel->getContainer()->has($service)) $this->fail("Service $service is not available in container");
        return $this->kernel->getContainer()->get($service);
    }

    /**
     * @return \Symfony\Component\HttpKernel\Profiler\Profile
     */
    protected function getProfiler()
    {
        if (!$this->kernel->getContainer()->has('profiler')) return null;
        $profiler = $this->kernel->getContainer()->get('profiler');
        return $profiler->loadProfileFromResponse($this->client->getResponse());
    }

    protected function debugResponse()
    {
        $this->debugSection('Page', $this->client->getHistory()->current()->getUri());
        if ($profile = $this->getProfiler()) {
            if ($profile->hasCollector('security')) {
                if ($profile->getCollector('security')->isAuthenticated()) {
                    $this->debugSection('User', $profile->getCollector('security')->getUser() . ' [' . implode(',', $profile->getCollector('security')->getRoles()) . ']');
                } else {
                    $this->debugSection('User', 'Anonymous');
                }
            }
            if ($profile->hasCollector('swiftmailer')) {
                $messages = $profile->getCollector('swiftmailer')->getMessageCount();
                if ($messages) $this->debugSection('Emails', $messages . ' sent');
            }
            if ($profile->hasCollector('timer'))    $this->debugSection('Time', $profile->getCollector('timer')->getTime());
            if ($profile->hasCollector('db'))       $this->debugSection('Db', $profile->getCollector('db')->getQueryCount() . ' queries');
        }
    }
}


text:
// renderers/samplerrenderer.cpp*
#include "stdafx.h"
#include "renderers/samplerrenderer.h"
#include "scene.h"
#include "film.h"
#include "volume.h"
#include "sampler.h"
#include "integrator.h"
#include "progressreporter.h"
#include "camera.h"
#include "intersection.h"

static uint32_t hash(char *key, uint32_t len)
{
    uint32_t hash = 0, i;
    for (hash=0, i=0; i<len; ++i) {
        hash += key[i];
        hash += (hash << 10);
        hash ^= (hash >> 6);
    }
    hash += (hash << 3);
    hash ^= (hash >> 11);
    hash += (hash << 15);
    return hash;
}

// SamplerRendererTask Definitions
void SamplerRendererTask::Run() {
    PBRT_STARTED_RENDERTASK(taskNum);
    // Get sub-_Sampler_ for _SamplerRendererTask_
    Sampler *sampler = mainSampler->GetSubSampler(taskNum, taskCount);
    if (!sampler)
    {
        reporter.Update();
        PBRT_FINISHED_RENDERTASK(taskNum);
        return;
    }

    // Declare local variables used for rendering loop
    MemoryArena arena;
    RNG rng(taskNum);

    // Allocate space for samples and intersections
    int maxSamples = sampler->MaximumSampleCount();
    Sample *samples = origSample->Duplicate(maxSamples);
    RayDifferential *rays = new RayDifferential[maxSamples];
    Spectrum *Ls = new Spectrum[maxSamples];
    Spectrum *Ts = new Spectrum[maxSamples];
    Intersection *isects = new Intersection[maxSamples];

    // Get samples from _Sampler_ and update image
    int sampleCount;
    while ((sampleCount = sampler->GetMoreSamples(samples, rng)) > 0) {
        // Generate camera rays and compute radiance along rays
        for (int i = 0; i < sampleCount; ++i) {
            // Find camera ray for _sample[i]_
            PBRT_STARTED_GENERATING_CAMERA_RAY(&samples[i]);
            float rayWeight = camera->GenerateRayDifferential(samples[i], &rays[i]);
            rays[i].ScaleDifferentials(1.f / sqrtf(sampler->samplesPerPixel));
            PBRT_FINISHED_GENERATING_CAMERA_RAY(&samples[i], &rays[i], rayWeight);

            // Evaluate radiance along camera ray
            PBRT_STARTED_CAMERA_RAY_INTEGRATION(&rays[i], &samples[i]);
            if (visualizeObjectIds) {
                if (rayWeight > 0.f && scene->Intersect(rays[i], &isects[i])) {
                    // random shading based on shape id...
                    uint32_t ids[2] = { isects[i].shapeId, isects[i].primitiveId };
                    uint32_t h = hash((char *)ids, sizeof(ids));
                    float rgb[3] = { float(h & 0xff), float((h >> 8) & 0xff),
                                     float((h >> 16) & 0xff) };
                    Ls[i] = Spectrum::FromRGB(rgb);
                    Ls[i] /= 255.f;
                }
                else
                    Ls[i] = 0.f;
            }
            else {
            if (rayWeight > 0.f)
                Ls[i] = rayWeight * renderer->Li(scene, rays[i], &samples[i], rng,
                                                 arena, &isects[i], &Ts[i]);
            else {
                Ls[i] = 0.f;
                Ts[i] = 1.f;
            }

            // Issue warning if unexpected radiance value returned
            if (Ls[i].HasNaNs()) {
                Error("Not-a-number radiance value returned "
                      "for image sample.  Setting to black.");
                Ls[i] = Spectrum(0.f);
            }
            else if (Ls[i].y() < -1e-5) {
                Error("Negative luminance value, %f, returned "
                      "for image sample.  Setting to black.", Ls[i].y());
                Ls[i] = Spectrum(0.f);
            }
            else if (isinf(Ls[i].y())) {
                Error("Infinite luminance value returned "
                      "for image sample.  Setting to black.");
                Ls[i] = Spectrum(0.f);
            }
            }
            PBRT_FINISHED_CAMERA_RAY_INTEGRATION(&rays[i], &samples[i], &Ls[i]);
        }

        // Report sample results to _Sampler_, add contributions to image
        if (sampler->ReportResults(samples, rays, Ls, isects, sampleCount))
        {
            for (int i = 0; i < sampleCount; ++i)
            {
                PBRT_STARTED_ADDING_IMAGE_SAMPLE(&samples[i], &rays[i], &Ls[i], &Ts[i]);
                camera->film->AddSample(samples[i], Ls[i]);
                PBRT_FINISHED_ADDING_IMAGE_SAMPLE();
            }
        }

        // Free _MemoryArena_ memory from computing image sample values
        arena.FreeAll();
    }

    // Clean up after _SamplerRendererTask_ is done with its image region
    camera->film->UpdateDisplay(sampler->xPixelStart,
        sampler->yPixelStart, sampler->xPixelEnd+1, sampler->yPixelEnd+1);
    delete sampler;
    delete[] samples;
    delete[] rays;
    delete[] Ls;
    delete[] Ts;
    delete[] isects;
    reporter.Update();
    PBRT_FINISHED_RENDERTASK(taskNum);
}

// SamplerRenderer Method Definitions
SamplerRenderer::SamplerRenderer(Sampler *s, Camera *c,
                                 SurfaceIntegrator *si, VolumeIntegrator *vi,
                                 bool visIds) {
    sampler = s;
    camera = c;
    surfaceIntegrator = si;
    volumeIntegrator = vi;
    visualizeObjectIds = visIds;
}

SamplerRenderer::~SamplerRenderer() {
    delete sampler;
    delete camera;
    delete surfaceIntegrator;
    delete volumeIntegrator;
}

void SamplerRenderer::Render(const Scene *scene) {
    PBRT_FINISHED_PARSING();
    // Allow integrators to do preprocessing for the scene
    PBRT_STARTED_PREPROCESSING();
    surfaceIntegrator->Preprocess(scene, camera, this);
    volumeIntegrator->Preprocess(scene, camera, this);
    PBRT_FINISHED_PREPROCESSING();
    PBRT_STARTED_RENDERING();
    // Allocate and initialize _sample_
    Sample *sample = new Sample(sampler, surfaceIntegrator,
                                volumeIntegrator, scene);

    // Create and launch _SamplerRendererTask_s for rendering image

    // Compute number of _SamplerRendererTask_s to create for rendering
    int nPixels = camera->film->xResolution * camera->film->yResolution;
    int nTasks = max(32 * NumSystemCores(), nPixels / (16*16));
    nTasks = RoundUpPow2(nTasks);
    ProgressReporter reporter(nTasks, "Rendering");
    vector<Task *> renderTasks;
    for (int i = 0; i < nTasks; ++i)
        renderTasks.push_back(new SamplerRendererTask(scene, this, camera,
                                                      reporter, sampler, sample,
                                                      visualizeObjectIds,
                                                      nTasks-1-i, nTasks));
    EnqueueTasks(renderTasks);
    WaitForAllTasks();
    for (uint32_t i = 0; i < renderTasks.size(); ++i)
        delete renderTasks[i];
    reporter.Done();
    PBRT_FINISHED_RENDERING();
    // Clean up after rendering and store final image
    delete sample;
    camera->film->WriteImage();
}

Spectrum SamplerRenderer::Li(const Scene *scene,
        const RayDifferential &ray, const Sample *sample, RNG &rng,
        MemoryArena &arena, Intersection *isect, Spectrum *T) const {
    Assert(ray.time == sample->time);
    Assert(!ray.HasNaNs());
    // Allocate local variables for _isect_ and _T_ if needed
    Spectrum localT;
    if (!T) T = &localT;
    Intersection localIsect;
    if (!isect) isect = &localIsect;
    Spectrum Li = 0.f;
    if (scene->Intersect(ray, isect))
        Li = surfaceIntegrator->Li(scene, this, ray, *isect, sample,
                                   rng, arena);
    else {
        // Handle ray that doesn't intersect any geometry
        for (uint32_t i = 0; i < scene->lights.size(); ++i)
           Li += scene->lights[i]->Le(ray);
    }
    Spectrum Lvi = volumeIntegrator->Li(scene, this, ray, sample, rng,
                                        T, arena);
    return *T * Li + Lvi;
}

Spectrum SamplerRenderer::Transmittance(const Scene *scene,
        const RayDifferential &ray, const Sample *sample, RNG &rng,
        MemoryArena &arena) const {
    return volumeIntegrator->Transmittance(scene, this, ray, sample,
                                           rng, arena);
}

redpajama_set_name: RedPajamaGithub


text:
package com.luajava;

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Class that contains functions accessed by lua.
 *
 * @author Thiago Ponte
 */
public final class LuaJavaAPI {
    public static HashMap<String, Method[]> methodsMap = new HashMap<String, Method[]>();
    public static HashMap<String, Method[]> methodCache = new HashMap<String, Method[]>();

    private static Class<?> LuaState_class = LuaState.class;

    private static Class<?> String_class = String.class;

    private static Class<?> List_class = List.class;

    private static Class<?> ArrayList_class = ArrayList.class;

    private static Class<?> HashMap_class = HashMap.class;

    private static Class<?> Map_class = Map.class;

    private static Class<?> LuaFunction_class = LuaFunction.class;

    private static Class<?> LuaObject_class = LuaObject.class;

    private static Class<?> LuaTable_class = LuaTable.class;

    private static Class<?> Number_class = Number.class;

    private static Class<?> Character_class = Character.class;

    private LuaJavaAPI() {
    }

    /**
     * Java implementation of the metamethod __index
     *
     * @param luaState   int that indicates the state used
     * @param obj        Object to be indexed
     * @param methodName the name of the method
     * @return number of returned objects
     */

    public static int objectIndex(long luaState, Object obj, String searchName, int type)
            throws LuaException {
        LuaState L = LuaStateFactory.getExistingState(luaState);
        synchronized (L) {

            int ret = 0;
            if (type == 0)
                if (checkMethod(L, obj, searchName) != 0)
                    return 2;

            if (type == 0 || type == 1 || type == 5)
                if ((ret = checkField(L, obj, searchName)) != 0)
                    return ret;

            if (type == 0 || type == 4)
                if (javaGetter(L, obj, searchName) != 0)
                    return 4;

            if (type == 0 || type == 3)
                if (checkClass(L, obj, searchName) != 0)
                    return 3;

            if ((type == 0 || type == 6) && obj instanceof LuaMetaTable) {
                Object res = ((LuaMetaTable) obj).__index(searchName);
                L.pushObjectValue(res);
                return 6;
            }

            return 0;
        }
    }

    public static int callMethod(long luaState, Object obj, String cacheName)
            throws LuaException {
        LuaState L = LuaStateFactory.getExistingState(luaState);

        synchronized (L) {
            Method[] methods = methodCache.get(cacheName);
            int top = L.getTop();
            Object[] objs = new Object[top];
            Method method = null;
            // gets method and arguments
            for (int i = 0; i < methods.length; i++) {

                Class[] parameters = methods[i].getParameterTypes();
                if (parameters.length != top)
                    continue;

                boolean okMethod = true;

                for (int j = 0; j < parameters.length; j++) {
                    try {
                        objs[j] = compareTypes(L, parameters[j], j + 1);

                    } catch (Exception e) {
                        okMethod = false;
                        break;
                    }
                }

                if (okMethod) {
                    method = methods[i];
                    break;
                }

            }

            // If method is null means there isn't one receiving the given arguments
            if (method == null) {
                StringBuilder msgbuilder = new StringBuilder();
                for (int i = 0; i < methods.length; i++) {
                    msgbuilder.append(methods[i].toString());
                    msgbuilder.append("\n");
                }
                throw new LuaException("Invalid method call. Invalid Parameters.\n" + msgbuilder.toString());
            }

            Object ret;
            try {
                if (!Modifier.isPublic(method.getModifiers()))
                    method.setAccessible(true);

                ret = method.invoke(obj, objs);
            } catch (Exception e) {
                throw new LuaException(e);
            }

            // Void function returns null
            if (ret == null && method.getReturnType().equals(Void.TYPE))
                return 0;

            // push result
            L.pushObjectValue(ret);

            return 1;
        }
    }

    /**
     * Java implementation of the metamethod __newindex
     *
     * @param luaState   int that indicates the state used
     * @param obj        Object to be indexed
     * @param searchName the name of the method
     * @return number of returned objects
     */

    public static int objectNewIndex(long luaState, Object obj, String searchName)
            throws LuaException {
        LuaState L = LuaStateFactory.getExistingState(luaState);
        synchronized (L) {
            int res;

            res = setFieldValue(L, obj, searchName);
            if (res != 0)
                return 1;

            res = javaSetter(L, obj, searchName);
            if (res != 0)
                return 1;

            return 0;
        }
    }

    public static int setFieldValue(LuaState L, Object obj, String fieldName) throws LuaException {
        synchronized (L) {
            Field field = null;
            Class objClass;
            boolean isClass = false;

            if (obj == null)
                return 0;

            if (obj instanceof Class) {
                objClass = (Class) obj;
                isClass = true;
            } else {
                objClass = obj.getClass();
            }

            try {
                field = objClass.getField(fieldName);
            } catch (NoSuchFieldException e) {
                /*try
                 {
				 field = objClass.getDeclaredField(fieldName);
				 }
				 catch (Exception e2)
				 */
                {
                    return 0;
                }
            }

            if (field == null)
                return 0;
            if (isClass && !Modifier.isStatic(field.getModifiers()))
                return 0;
            Class type = field.getType();
            try {
                if (!Modifier.isPublic(field.getModifiers()))
                    field.setAccessible(true);

                field.set(obj, compareTypes(L, type, 3));
            } catch (LuaException e) {
                argError(L, fieldName, 3, type);
            } catch (Exception e) {
                throw new LuaException(e);
            }

            return 1;
        }
    }

    private static String argError(LuaState L, String name, int idx, Class type) throws LuaException {

        throw new LuaException("bad argument to '" + name + "' (" + type.getName() + " expected, got " + typeName(L, 3) + " value)");

    }

    private static String typeName(LuaState L, int idx) throws LuaException {
        if (L.isObject(idx)) {
            return L.getObjectFromUserdata(idx).getClass().getName();
        }
        switch (L.type(idx)) {
            case LuaState.LUA_TSTRING:
                return "string";
            case LuaState.LUA_TNUMBER:
                return "number";
            case LuaState.LUA_TBOOLEAN:
                return "boolean";
            case LuaState.LUA_TFUNCTION:
                return "function";
            case LuaState.LUA_TTABLE:
                return "table";
            case LuaState.LUA_TTHREAD:
                return "thread";
            case LuaState.LUA_TLIGHTUSERDATA:
            case LuaState.LUA_TUSERDATA:
                return "userdata";
        }
        return "unkown";
    }

    /**
     * Java implementation of the metamethod __index
     *
     * @param luaState   int that indicates the state used
     * @param obj        Object to be indexed
     * @param methodName the name of the method
     * @return number of returned objects
     */
    public static int setArrayValue(long luaState, Object obj, int index) throws LuaException {
        LuaState L = LuaStateFactory.getExistingState(luaState);

        synchronized (L) {
            if (obj.getClass().isArray()) {
                Class<?> type = obj.getClass().getComponentType();
                try {
                    Object value = compareTypes(L, type, 3);
                    Array.set(obj, index, value);
                } catch (LuaException e) {
                    argError(L, obj.getClass().getName() + " [" + index + "]", 3, type);
                }
            } else if (obj instanceof List) {
                ((List<Object>) obj).set(index, L.toJavaObject(3));
            } else if (obj instanceof Map) {
                ((Map<Integer, Object>) obj).put(index, L.toJavaObject(3));
            } else {
                throw new LuaException("can not set " + obj.getClass().getName() + " value: " + L.toJavaObject(3) + " in " + index);
            }
            return 0;
        }
    }

    public static int getArrayValue(long luaState, Object obj, int index) throws LuaException {
        LuaState L = LuaStateFactory.getExistingState(luaState);

        synchronized (L) {
            Object ret = null;
            if (obj.getClass().isArray()) {
                ret = Array.get(obj, index);
            } else if (obj instanceof List) {
                ret = ((List) obj).get(index);
            } else if (obj instanceof Map) {
                ret = ((Map) obj).get(index);
            } else {
                throw new LuaException("can not get " + obj.getClass().getName() + " value in " + index);
            }
            L.pushObjectValue(ret);
            return 1;
        }
    }

    public static int asTable(long luaState, Object obj) throws LuaException {
        LuaState L = LuaStateFactory.getExistingState(luaState);

        synchronized (L) {

            try {
                L.newTable();
                if (obj.getClass().isArray()) {
                    int n = Array.getLength(obj);
                    for (int i = 0; i <= n - 1; i++) {
                        L.pushObjectValue(Array.get(obj, i));
                        L.rawSetI(-2, i + 1);
                    }
                } else if (obj instanceof Collection) {
                    Collection list = (Collection) obj;
                    int i = 1;
                    for (Object v : list) {
                        L.pushObjectValue(v);
                        L.rawSetI(-2, i++);
                    }
                } else if (obj instanceof Map) {
                    Map map = (Map) obj;
                    Iterator itor = map.entrySet().iterator();
                    while (itor.hasNext()) {
                        Map.Entry entry = (Map.Entry) itor.next();
                        L.pushObjectValue(entry.getKey());
                        L.pushObjectValue(entry.getValue());
                        L.setTable(-3);
                    }
					/*
					 for (Map.Entry entry : map.entrySet())
					 {
					 L.pushObjectValue(entry.getKey());
					 L.pushObjectValue(entry.getValue());
					 L.setTable(-3);
					 }*/
                }
                L.pushValue(-1);
                return 1;
            } catch (Exception e) {
                throw new LuaException("can not astable: " + e.getMessage());
            }

        }
    }

    public static int newArray(long luaState, Class<?> clazz, int size) throws LuaException {
        LuaState L = LuaStateFactory.getExistingState(luaState);
        synchronized (L) {
            try {
                Object obj = Array.newInstance(clazz, size);
                L.pushJavaObject(obj);
            } catch (Exception e) {
                throw new LuaException("can not create a array: " + e.getMessage());
            }
            return 1;
        }
    }

    public static int newArray(long luaState, Class<?> clazz) throws LuaException {
        LuaState L = LuaStateFactory.getExistingState(luaState);
        synchronized (L) {
            try {
                int top = L.getTop();
                int[] dimensions = new int[top - 1];
                for (int i = 0; i < top - 1; i++) {
                    dimensions[i] = (int) L.toInteger(i + 2);
                }
                Object obj = Array.newInstance(clazz, dimensions);
                L.pushJavaObject(obj);
            } catch (Exception e) {
                throw new LuaException("can not create a array: " + e.getMessage());
            }
            return 1;
        }
    }

    public static Class javaBindClass(String className) throws LuaException {
        Class clazz;
        try {
            clazz = Class.forName(className);
        } catch (Exception e) {
            if (className.equals("boolean"))
                clazz = Boolean.TYPE;
            else if (className.equals("byte"))
                clazz = Byte.TYPE;
            else if (className.equals("char"))
                clazz = Character.TYPE;
            else if (className.equals("short"))
                clazz = Short.TYPE;
            else if (className.equals("int"))
                clazz = Integer.TYPE;
            else if (className.equals("long"))
                clazz = Long.TYPE;
            else if (className.equals("float"))
                clazz = Float.TYPE;
            else if (className.equals("double"))
                clazz = Double.TYPE;
            else
                throw new LuaException("Class not found: " + className);
        }
        return clazz;
    }

    /**
     * Pushes a new instance of a java Object of the type className
     *
     * @param luaState  int that represents the state to be used
     * @param className name of the class
     * @return number of returned objects
     * @throws LuaException
     */
    public static int javaNewInstance(long luaState, String className) throws LuaException {
        LuaState L = LuaStateFactory.getExistingState(luaState);

        synchronized (L) {
            Class clazz;
            clazz = javaBindClass(className);
            if (clazz.isPrimitive())
                return toPrimitive(L, clazz, -1);
            else
                return getObjInstance(L, clazz);
        }
    }

    /**
     * javaNew returns a new instance of a given clazz
     *
     * @param luaState int that represents the state to be used
     * @param clazz    class to be instanciated
     * @return number of returned objects
     * @throws LuaException
     */
    public static int javaNew(long luaState, Class<?> clazz) throws LuaException {
        LuaState L = LuaStateFactory.getExistingState(luaState);

        synchronized (L) {
            if (clazz.isPrimitive()) {
                return toPrimitive(L, clazz, -1);
            } else {
                return getObjInstance(L, clazz);
            }
        }
    }

    public static int javaCreate(long luaState, Class<?> clazz) throws LuaException {
        LuaState L = LuaStateFactory.getExistingState(luaState);

        synchronized (L) {
            if (clazz.isInterface()) {
                return createProxyObject(L, clazz);
            } else if (clazz.isPrimitive()) {
                return createArray(L, clazz);
            } else if (List_class.isAssignableFrom(clazz)) {
                return createList(L, clazz);
            } else if (Map_class.isAssignableFrom(clazz)) {
                return createMap(L, clazz);
            } else {
                if (L.objLen(-1) == 0)
                    return createArray(L, clazz);
                else if (clazz.isAssignableFrom(new LuaTable(L, -1).get(1).getClass()))
                    return createArray(L, clazz);
                else
                    return getObjInstance(L, clazz);

				/*
				 LuaTable tab=new LuaTable(L, -1);
				 tab.push();
				 if(tab.isList()){
				 if(tab.isEmpty())
				 return createArray(L, clazz);
				 else if(clazz.isAssignableFrom(tab.get(1).getClass()))
				 return createArray(L, clazz);
				 else
				 return getObjInstance(L, clazz);
				 }
				 else{
				 L.setTop(1);
				 getObjInstance(L, clazz);
				 LuaObject obj=L.getLuaObject(-1);
				 Set<LuaTable.LuaEntry> sets=(Set<LuaTable.LuaEntry>)tab.entrySet();
				 for (LuaTable.LuaEntry entry:sets){
				 try{
				 obj.setField((String)entry.getKey(),entry.getValue());
				 }
				 catch(Exception e)
				 {}
				 }
				 return 1;
				 }*/
            }
        }

    }

    public static int objectCall(long luaState, Object obj) throws LuaException {
        LuaState L = LuaStateFactory.getExistingState(luaState);

        synchronized (L) {
            if (obj instanceof LuaMetaTable) {
                int n = L.getTop();
                Object[] args = new Object[n - 1];
                for (int i = 2; i <= n; i++) {
                    args[i - 2] = L.toJavaObject(i);
                }
                Object ret = ((LuaMetaTable) obj).__call(args);
                L.pushObjectValue(ret);
                return 1;
            } else {
                return 0;
            }
        }
    }

    /**
     * Function that creates an object proxy and pushes it into the stack
     *
     * @param luaState int that represents the state to be used
     * @param implem   interfaces implemented separated by comma (,)
     * @return number of returned objects
     * @throws LuaException
     */
    public static int createProxy(long luaState, String implem)
            throws LuaException {
        LuaState L = LuaStateFactory.getExistingState(luaState);
        synchronized (L) {
            return createProxyObject(L, implem);
        }
    }

    public static int createArray(long luaState, String className)
            throws LuaException {
        LuaState L = LuaStateFactory.getExistingState(luaState);
        synchronized (L) {
            Class type = javaBindClass(className);
            return createArray(L, type);
        }
    }

    /**
     * Calls the static method methodName in class className
     * that receives a LuaState as first parameter.
     *
     * @param luaState   int that represents the state to be used
     * @param className  name of the class that has the open library method
     * @param methodName method to open library
     * @return number of returned objects
     * @throws LuaException
     */
    public static int javaLoadLib(long luaState, String className, String methodName)
            throws LuaException {
        LuaState L = LuaStateFactory.getExistingState(luaState);

        synchronized (L) {
            Class clazz;
            try {
                clazz = Class.forName(className);
            } catch (ClassNotFoundException e) {
                throw new LuaException(e);
            }

            try {
                Method mt = clazz.getMethod(methodName, new Class[]{LuaState_class});
                Object obj = mt.invoke(null, new Object[]{L});

                if (obj != null && obj instanceof Integer) {
                    return ((Integer) obj).intValue();
                } else
                    return 0;
            } catch (Exception e) {
                throw new LuaException("Error on calling method. Library could not be loaded. " + e.getMessage());
            }
        }
    }

    public static int javaToString(long luaState, Object obj) throws LuaException {
        LuaState L = LuaStateFactory.getExistingState(luaState);

        synchronized (L) {
            if (obj == null)
                L.pushString("null");
            else
                L.pushString(obj.toString());
            return 1;
        }
    }

    public static int javaEquals(long luaState, Object obj, Object obj2) throws LuaException {
        LuaState L = LuaStateFactory.getExistingState(luaState);

        synchronized (L) {
            boolean eq = obj.equals(obj2);
            L.pushBoolean(eq);
            return 1;
        }
    }

    public static int javaObjectLength(long luaState, Object obj) throws LuaException {
        LuaState L = LuaStateFactory.getExistingState(luaState);

        synchronized (L) {
            int ret;
            try {
                if (obj instanceof CharSequence)
                    ret = ((CharSequence) obj).length();
                else if (obj instanceof Collection)
                    ret = ((Collection) obj).size();
                else if (obj instanceof Map)
                    ret = ((Map) obj).size();
                else
                    ret = Array.getLength(obj);
            } catch (Exception e) {
                throw new LuaException(e);
            }

            L.pushInteger(ret);

            return 1;
        }
    }

    private static int getObjInstance(LuaState L, Class<?> clazz) throws LuaException {
        synchronized (L) {
            int top = L.getTop();
            if (top == 1) {
                try {
                    Object ret = clazz.newInstance();
                    L.pushJavaObject(ret);
                    return 1;
                } catch (Exception e) {
                    if (android.view.View.class.isAssignableFrom(clazz)) {
                        try {
                            Constructor ctr = clazz.getConstructor(new Class[]{android.content.Context.class});
                            Object ret = ctr.newInstance(new Object[]{L.getContext()});
                            L.pushJavaObject(ret);
                            return 1;
                        } catch (Exception e2) {
                        }
                    }
                }
            }
            Object[] objs = new Object[top - 1];

            Constructor[] constructors = clazz.getConstructors();
            Constructor constructor = null;

            // gets method and arguments
            for (int i = 0; i < constructors.length; i++) {
                Class<?>[] parameters = constructors[i].getParameterTypes();
                if (parameters.length != top - 1)
                    continue;

                boolean okConstruc = true;

                for (int j = 0; j < parameters.length; j++) {
                    try {
                        objs[j] = compareTypes(L, parameters[j], j + 2);
                    } catch (Exception e) {
                        okConstruc = false;
                        break;
                    }
                }

                if (okConstruc) {
                    constructor = constructors[i];
                    break;
                }

            }

            // If method is null means there isn't one receiving the given arguments
            if (constructor == null) {
                StringBuilder msgbuilder = new StringBuilder();
                for (int i = 0; i < constructors.length; i++) {
                    msgbuilder.append(constructors[i].toString());
                    msgbuilder.append("\n");
                }
                throw new LuaException("Invalid constructor method call. Invalid Parameters.\n" + msgbuilder.toString());
            }

            Object ret;
            try {
                ret = constructor.newInstance(objs);
            } catch (Exception e) {
                throw new LuaException(e);
            }

            if (ret == null) {
                throw new LuaException("Couldn't instantiate java Object");
            }
            L.pushJavaObject(ret);
            return 1;
        }
    }

    /**
     * Checks if there is a field on the obj with the given name
     *
     * @param luaState  int that represents the state to be used
     * @param obj       object to be inspected
     * @param fieldName name of the field to be inpected
     * @return number of returned objects
     */
    public static int checkField(LuaState L, Object obj, String fieldName)
            throws LuaException {
        synchronized (L) {
            Field field = null;
            Class objClass;
            boolean isClass = false;

            if (obj instanceof Class) {
                objClass = (Class) obj;
                isClass = true;
            } else {
                objClass = obj.getClass();
            }

            try {
                field = objClass.getField(fieldName);
            } catch (NoSuchFieldException e) {
                return 0;
            }

            if (field == null)
                return 0;

            if (isClass && !Modifier.isStatic(field.getModifiers()))
                return 0;

            Object ret = null;
            try {
                if (!Modifier.isPublic(field.getModifiers()))
                    field.setAccessible(true);
                ret = field.get(obj);
            } catch (Exception e) {
                throw new LuaException(e);
            }

            L.pushObjectValue(ret);
            if (Modifier.isFinal(field.getModifiers()))
                return 5;
            else
                return 1;
        }
    }

    /**
     * Checks to see if there is a method with the given name.
     *
     * @param luaState   int that represents the state to be used
     * @param obj        object to be inspected
     * @param methodName name of the field to be inpected
     * @return number of returned objects
     */
    public static int checkMethod(LuaState L, Object obj, String methodName) throws LuaException {
        synchronized (L) {
            Class clazz;
            boolean isClass = false;
            if (obj instanceof Class) {
                clazz = (Class) obj;
                isClass = true;
            } else {
                clazz = obj.getClass();
            }

            String className = clazz.getName();
            String cacheName = L.toString(-1);//String.format("%c %s %s",c,className,methodName);
            Method[] mlist = methodCache.get(cacheName);
            if (mlist == null) {
                Method[] methods = methodsMap.get(className);
                if (methods == null) {
                    methods = clazz.getMethods();
                    methodsMap.put(className, methods);
                }
                ArrayList<Method> list = new ArrayList<Method>();

                for (int i = 0; i < methods.length; i++) {
                    if (methods[i].getName().equals(methodName)) {
                        if (isClass && !Modifier.isStatic(methods[i].getModifiers()))
                            continue;
                        list.add(methods[i]);
                    }
                }

                if (list.isEmpty() && isClass) {
                    methods = clazz.getClass().getMethods();
                    for (int i = 0; i < methods.length; i++) {
                        if (methods[i].getName().equals(methodName))
                            list.add(methods[i]);
                    }

                }

                mlist = new Method[list.size()];
                list.toArray(mlist);
                methodCache.put(cacheName, mlist);
            }
            if (mlist.length == 0)
                return 0;
            return 2;
        }
    }

    /**
     * Checks to see if there is a class with the given name.
     *
     * @param L         int that represents the state to be used
     * @param obj       object to be inspected
     * @param className name of the field to be inpected
     * @return number of returned objects
     */
    public static int checkClass(LuaState L, Object obj, String className) throws LuaException {
        synchronized (L) {
            Class clazz;

            if (obj instanceof Class) {
                clazz = (Class) obj;
            } else {
                return 0;
            }

            Class[] clazzes = clazz.getClasses();

            for (int i = 0; i < clazzes.length; i++) {
                if (clazzes[i].getSimpleName().equals(className)) {
                    L.pushJavaObject(clazzes[i]);
                    return 3;
                }
            }
            return 0;
        }
    }

    public static int javaGetter(LuaState L, Object obj, String methodName) throws LuaException {
        synchronized (L) {
            Class clazz;

            Method method = null;
            boolean isClass = false;
            if (obj instanceof Map) {
                Map map = (Map) obj;
                L.pushObjectValue(map.get(methodName));
                return 1;
            } else if (obj instanceof Class) {
                clazz = (Class) obj;
                isClass = true;
            } else {
                clazz = obj.getClass();
            }

            try {
                method = clazz.getMethod("get" + methodName);
            } catch (NoSuchMethodException e) {
                return 0;
            }

            if (isClass && !Modifier.isStatic(method.getModifiers()))
                return 0;

            Object ret;
            try {
                ret = method.invoke(obj);
            } catch (Exception e) {
                throw new LuaException(e);
            }

            if (ret instanceof CharSequence)
                L.pushString(ret.toString());
            else
                L.pushObjectValue(ret);
            return 1;
        }
    }

    public static int javaSetter(LuaState L, Object obj, String methodName) throws LuaException {
        synchronized (L) {
            Class clazz;
            boolean isClass = false;

            if (obj instanceof Map) {
                Map map = (Map) obj;
                map.put(methodName, L.toJavaObject(3));
                return 1;
            } else if (obj instanceof Class) {
                clazz = (Class) obj;
                isClass = true;
            } else {
                clazz = obj.getClass();
            }

            String className = clazz.getName();
            Method[] methods = methodsMap.get(className);
            if (methods == null) {
                methods = clazz.getMethods();
                methodsMap.put(className, methods);
            }

            if (methodName.length() > 2 && methodName.substring(0, 2).equals("on") && L.type(-1) == LuaState.LUA_TFUNCTION)
                return javaSetListener(L, obj, methodName, methods, isClass);

            return javaSetMethod(L, obj, methodName, methods, isClass);

        }
    }

    private static int javaSetListener(LuaState L, Object obj, String methodName, Method[] methods, boolean isClass) throws LuaException {
        synchronized (L) {
            String name = "setOn" + methodName.substring(2) + "Listener";
            for (Method m : methods) {
                if (!m.getName().equals(name))
                    continue;
                if (isClass && !Modifier.isStatic(m.getModifiers()))
                    continue;

                Class<?>[] tp = m.getParameterTypes();
                if (tp.length == 1 && tp[0].isInterface()) {
                    L.newTable();
                    L.pushValue(-2);
                    L.setField(-2, methodName);
                    try {
                        Object listener = L.getLuaObject(-1).createProxy(tp[0]);
                        m.invoke(obj, new Object[]{listener});
                        return 1;
                    } catch (Exception e) {
                        throw new LuaException(e);
                    }
                }
            }
        }
        return 0;
    }

    private static int javaSetMethod(LuaState L, Object obj, String methodName, Method[] methods, boolean isClass) throws LuaException {
        synchronized (L) {
            String name = "set" + methodName;
            Object arg = null;
            StringBuilder buf = new StringBuilder();
            for (Method m : methods) {
                if (!m.getName().equals(name))
                    continue;
                if (isClass && !Modifier.isStatic(m.getModifiers()))
                    continue;

                Class<?>[] tp = m.getParameterTypes();
                if (tp.length != 1)
                    continue;

                try {
                    arg = compareTypes(L, tp[0], -1);
                } catch (LuaException e) {
                    buf.append(tp[0]);
                    buf.append("\n");
                    continue;
                }

                try {
                    m.invoke(obj, new Object[]{arg});
                    return 1;
                } catch (Exception e) {
                    throw new LuaException(e);
                }

            }
            if (buf.length() > 0)
                throw new LuaException("Invalid setter " + methodName + ". Invalid Parameters.\n" + buf.toString() + L.typeName(-1));
        }
        return 0;
    }

    private static int createProxyObject(LuaState L, String implem)
            throws LuaException {
        synchronized (L) {
            try {
                LuaObject luaObj = L.getLuaObject(2);
                Object proxy = luaObj.createProxy(implem);
                L.pushJavaObject(proxy);
            } catch (Exception e) {
                throw new LuaException(e);
            }

            return 1;
        }
    }

    private static int createProxyObject(LuaState L, Class implem) throws LuaException {
        synchronized (L) {
            L.pushJavaObject(createProxyObject(L, implem, 2));
            return 1;
        }
    }

    private static Object createProxyObject(LuaState L, Class implem, int idx) throws LuaException {
        synchronized (L) {
            try {
                LuaObject luaObj = L.getLuaObject(idx);
                Object proxy = luaObj.createProxy(implem);
                return proxy;
            } catch (Exception e) {
                throw new LuaException(e);
            }
        }
    }

    private static int createArray(LuaState L, Class<?> type) throws LuaException {
        synchronized (L) {
            L.pushJavaObject(createArray(L, type, 2));
            return 1;
        }
    }

    private static Object createArray(LuaState L, Class<?> type, int idx) throws LuaException {
        synchronized (L) {
            try {
                int n = L.objLen(idx);
                Object array = Array.newInstance(type, n);

                if (type == String_class) {
                    for (int i = 1; i <= n; i++) {
                        L.pushNumber(i);
                        L.getTable(idx);
                        Array.set(array, i - 1, L.toString(-1));
                        L.pop(1);
                    }
                } else if (type == Double.TYPE) {
                    for (int i = 1; i <= n; i++) {
                        L.pushNumber(i);
                        L.getTable(idx);
                        Array.set(array, i - 1, L.toNumber(-1));
                        L.pop(1);
                    }
                } else if (type == Float.TYPE) {
                    for (int i = 1; i <= n; i++) {
                        L.pushNumber(i);
                        L.getTable(idx);
                        Array.set(array, i - 1, (float) L.toNumber(-1));
                        L.pop(1);
                    }
                } else if (type == Long.TYPE) {
                    for (int i = 1; i <= n; i++) {
                        L.pushNumber(i);
                        L.getTable(idx);
                        Array.set(array, i - 1, L.toInteger(-1));
                        L.pop(1);
                    }
                } else if (type == Integer.TYPE) {
                    for (int i = 1; i <= n; i++) {
                        L.pushNumber(i);
                        L.getTable(idx);
                        Array.set(array, i - 1, (int) L.toInteger(-1));
                        L.pop(1);
                    }
                } else if (type == Short.TYPE) {
                    for (int i = 1; i <= n; i++) {
                        L.pushNumber(i);
                        L.getTable(idx);
                        Array.set(array, i - 1, (short) L.toInteger(-1));
                        L.pop(1);
                    }
                } else if (type == Character.TYPE) {
                    for (int i = 1; i <= n; i++) {
                        L.pushNumber(i);
                        L.getTable(idx);
                        Array.set(array, i - 1, (char) L.toInteger(-1));
                        L.pop(1);
                    }
                } else if (type == Byte.TYPE) {
                    for (int i = 1; i <= n; i++) {
                        L.pushNumber(i);
                        L.getTable(idx);
                        Array.set(array, i - 1, (byte) L.toInteger(-1));
                        L.pop(1);
                    }
                } else {
                    for (int i = 1; i <= n; i++) {
                        L.pushNumber(i);
                        L.getTable(idx);
                        Array.set(array, i - 1, compareTypes(L, type, -1));
                        L.pop(1);
                    }
                }
                return array;
            } catch (Exception e) {
                throw new LuaException(e);
            }
        }
    }

    private static int createList(LuaState L, Class<?> type) throws LuaException {
        synchronized (L) {
            L.pushJavaObject(createList(L, type, 2));
            return 1;
        }
    }

    private static Object createList(LuaState L, Class<?> type, int idx) throws LuaException {
        synchronized (L) {
            int n = L.objLen(idx);
            try {
                if (type.equals(List_class))
                    type = ArrayList_class;
                List<Object> list = (List<Object>) type.newInstance();
                for (int i = 1; i <= n; i++) {
                    L.pushNumber(i);
                    L.getTable(idx);
                    list.add(L.toJavaObject(-1));
                    L.pop(1);
                }
                return list;
            } catch (Exception e) {
                throw new LuaException(e);
            }
        }
    }

    private static int createMap(LuaState L, Class<?> clazz) throws LuaException {
        // TODO: Implement this method
        synchronized (L) {
            L.pushJavaObject(createMap(L, clazz, 2));
            return 1;
        }
    }

    private static Object createMap(LuaState L, Class<?> clazz, int idx) throws LuaException {
        // TODO: Implement this method
        synchronized (L) {
            try {
                if (clazz.equals(Map_class))
                    clazz = HashMap_class;
                Map<Object, Object> map = (Map<Object, Object>) clazz.newInstance();
                L.pushNil();
                while (L.next(idx) != 0) {
                    map.put(L.toJavaObject(-2), L.toJavaObject(-1));
                    L.pop(1);
                }
                return map;
            } catch (Exception e) {
                throw new LuaException(e);
            }
        }
    }

    private static Object compareTypes(LuaState L, Class<?> parameter, int idx)
            throws LuaException {
        boolean okType = true;
        Object obj = null;
        int type = L.type(idx);
        switch (type) {
            case 1: //boolean
            {
                if (parameter.isPrimitive()) {
                    if (parameter != Boolean.TYPE) {
                        okType = false;
                    }
                } else if (!parameter.isAssignableFrom(Boolean.TYPE)) {
                    okType = false;
                }
                obj = L.toBoolean(idx);
            }
            break;
            case 4: //string
            {
                if (!parameter.isAssignableFrom(String_class)) {
                    okType = false;
                } else {
                    obj = L.toString(idx);
                }
            }
            break;
            case 6: //function
            {
                if (!parameter.isAssignableFrom(LuaFunction_class)) {
                    okType = false;
                } else {
                    obj = L.getLuaObject(idx);
                }
            }
            break;
            case 5: //table
            {
                if (parameter.isAssignableFrom(LuaTable_class)) {
                    obj = L.getLuaObject(idx);
                } else if (parameter.isArray()) {
                    obj = createArray(L, parameter.getComponentType(), idx);
                } else if (parameter.isInterface()) {
                    obj = createProxyObject(L, parameter, idx);
                } else if (Map_class.isAssignableFrom(parameter)) {
                    obj = createMap(L, parameter, idx);
                } else {
                    okType = false;
                }
            }
            break;
            case 3: //number
            {
                if (L.isInteger(idx)) {
                    Long lg = new Long(L.toInteger(idx));
                    obj = LuaState.convertLuaNumber(lg, parameter);
                } else {
                    Double db = new Double(L.toNumber(idx));
                    obj = LuaState.convertLuaNumber(db, parameter);
                }
                if (obj == null) {
                    okType = false;
                }
            }
            break;
            case 7: //userdata
            {
                if (L.isObject(idx)) {
                    Object userObj = L.getObjectFromUserdata(idx);
                    if (userObj == null) {
                        obj = null;
                    } else if (parameter.isPrimitive() && (Number_class.isAssignableFrom(userObj.getClass()) || Character_class.isAssignableFrom(userObj.getClass()))) {
                        obj = userObj;
                    } else if (parameter.isAssignableFrom(userObj.getClass())) {
                        obj = userObj;
                    } else {
                        okType = false;
                    }
                } else {
                    if (!parameter.isAssignableFrom(LuaObject_class)) {
                        okType = false;
                    } else {
                        obj = L.getLuaObject(idx);
                    }
                }
            }
            break;
            case 0: //nil
            {
                obj = null;
            }
            break;
            default: //other
            {
                throw new LuaException("Invalid Parameters.");
            }
        }
        if (!okType) {
            throw new LuaException("Invalid Parameter.");
        }

        return obj;
    }

    private static int toPrimitive(LuaState L, Class type, int idx) throws LuaException {
        Object obj = null;

        if (type == Character.TYPE && L.type(idx) == LuaState.LUA_TSTRING) {
            String s = L.toString(idx);
            if (s.length() == 1)
                obj = s.charAt(0);
            else
                obj = s.toCharArray();
        } else if (!L.isNumber(idx)) {
            throw new LuaException(L.toString(idx) + " is not number");
        } else if (type == Double.TYPE) {
            obj = L.toNumber(idx);
        } else if (type == Float.TYPE) {
            obj = (float) L.toNumber(idx);
        } else if (type == Long.TYPE) {
            obj = L.toInteger(idx);
        } else if (type == Integer.TYPE) {
            obj = (int) L.toInteger(idx);
        } else if (type == Short.TYPE) {
            obj = (short) L.toInteger(idx);
        } else if (type == Character.TYPE) {
            obj = (char) L.toInteger(idx);
        } else if (type == Byte.TYPE) {
            obj = (byte) L.toInteger(idx);
        } else if (type == Boolean.TYPE) {
            obj = L.toBoolean(idx);
        }
        L.pushJavaObject(obj);
        return 1;
    }

}


text:
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
#else
static const int ddLogLevel = LOG_LEVEL_INFO;
#endif


text:
package com.example.slidinglayout3d;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

/**
 * com.example.slidinglayout3d.MainActivity
 *
 * @Description:程序的主界面。
 * @author Kebin.Yan
 * @date Create At :2015年7月1日 下午1:08:59
 */
public class MainActivity extends Activity
{

	/**
	 * 侧滑布局对象,用于通过手指滑动将左侧的菜单布局进行显示或隐藏。
	 */
	private ThreeDSlidingLayout slidingLayout;

	/**
	 * menu按钮,点击按钮展示左侧布局,再点击一次隐藏左侧布局。
	 */
	private Button menuButton;

	/**
	 * 放在content布局中的ListView。
	 */
	private ListView contentListView;

	/**
	 * 作用于contentListView的适配器。
	 */
	private ArrayAdapter<String> contentListAdapter;

	/**
	 * 用于填充contentListAdapter的数据源。
	 */
	private String[] contentItems = { "Content Item 1", "Content Item 2", "Content Item 3", "Content Item 4", "Content Item 5", "Content Item 6", "Content Item 7", "Content Item 8", "Content Item 9",
			"Content Item 10", "Content Item 11", "Content Item 12", "Content Item 13", "Content Item 14", "Content Item 15", "Content Item 16" };

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		slidingLayout = (ThreeDSlidingLayout) findViewById(R.id.slidingLayout);

		menuButton = (Button) findViewById(R.id.menuButton);
		contentListView = (ListView) findViewById(R.id.contentList);
		contentListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, contentItems);
		contentListView.setAdapter(contentListAdapter);
		// 设置content
		slidingLayout.setScrollEvent(contentListView);
		menuButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (slidingLayout.isLeftLayoutVisible())
				{
					slidingLayout.scrollToRightLayout();
				} else
				{
					slidingLayout.scrollToLeftLayout();
				}
			}
		});
		contentListView.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			{
				String text = contentItems[position];
				Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
			}
		});
	}
}


text:
package org.locationtech.geomesa.fs.storage.orc.utils

import org.apache.orc.TypeDescription
import org.apache.orc.storage.ql.io.sarg.{PredicateLeaf, SearchArgument, SearchArgumentFactory}
import org.locationtech.geomesa.filter.{Bounds, FilterHelper}
import org.locationtech.geomesa.fs.storage.orc.OrcFileSystemStorage
import org.locationtech.jts.geom.{Geometry, Point}
import org.opengis.feature.simple.SimpleFeatureType
import org.opengis.filter.Filter

import java.sql.Timestamp

object OrcSearchArguments {

  import scala.collection.JavaConverters._

  /**
    * Creates a push-down predicate for Orc files based on a CQL filter
    *
    * @param sft simple feature type
    * @param description orc file description
    * @param filter cql filter
    * @return
    */
  def apply(sft: SimpleFeatureType,
            description: TypeDescription,
            filter: Filter): Option[(SearchArgument, Array[String])] = {
    import org.apache.orc.TypeDescription.Category._

    val predicates = FilterHelper.propertyNames(filter, sft).distinct.flatMap { prop =>
      val binding = sft.getDescriptor(prop).getType.getBinding
      val preds = if (classOf[Geometry].isAssignableFrom(binding)) {
        if (classOf[Point] == binding) {
          FilterHelper.extractGeometries(filter, prop).values.map(addPoint(prop, _))
        } else {
          // orc doesn't support push-down predicates against complex fields
          Seq.empty
        }
      } else {
        // count the columns before the property
        val offset = sft.getAttributeDescriptors.asScala.take(sft.indexOf(prop)).foldLeft(0) { (sum, d) =>
          sum + OrcFileSystemStorage.fieldCount(d)
        }

        val category = description.getChildren.get(offset).getCategory
        val typeAndConversion = category match {
          case BOOLEAN   => Some(PredicateLeaf.Type.BOOLEAN, (v: Any) => v)
          case INT       => Some(PredicateLeaf.Type.LONG, (v: Any) => v.asInstanceOf[java.lang.Integer].longValue)
          case LONG      => Some(PredicateLeaf.Type.LONG, (v: Any) => v)
          case FLOAT     => Some(PredicateLeaf.Type.FLOAT, (v: Any) => v.asInstanceOf[java.lang.Float].doubleValue)
          case DOUBLE    => Some(PredicateLeaf.Type.FLOAT, (v: Any) => v)
          case STRING    => Some(PredicateLeaf.Type.STRING, (v: Any) => v)
          case TIMESTAMP => Some(PredicateLeaf.Type.TIMESTAMP, (v: Any) => new Timestamp(v.asInstanceOf[java.util.Date].getTime))
          case BINARY | LIST | MAP => None // orc doesn't support push-down predicates against complex fields
          case BYTE | CHAR | SHORT | DATE | DECIMAL | VARCHAR | STRUCT =>
            throw new IllegalArgumentException(s"SimpleFeature TypeDefinition should not have type '$category'")
        }
        typeAndConversion.toSeq.flatMap { case (typ, conversion) =>
          FilterHelper.extractAttributeBounds(filter, prop, binding).values.flatMap(add(prop, _, typ, conversion))
        }
      }

      if (preds.isEmpty) {
        Seq.empty
      } else {
        Seq(preds)
      }
    }

    if (predicates.isEmpty) { None } else {
      val arg = SearchArgumentFactory.newBuilder
      if (predicates.length > 1) {
        arg.startAnd()
      }
      predicates.foreach { preds =>
        if (preds.length == 1) {
          preds.head.apply(arg)
        } else {
          arg.startOr()
          preds.foreach(_.apply(arg))
          arg.end()
        }
      }
      if (predicates.length > 1) {
        arg.end()
      }
      // note: column name array does not matter at all
      Some((arg.build, Array.empty))
    }
  }

  private def add(
      prop: String,
      bounds: Bounds[_],
      typ: PredicateLeaf.Type,
      convert: Any => Any): Option[SearchArgument.Builder => Unit] = {
    if (bounds.isRange) {
      if (bounds.isBoundedBothSides) {
        // between seems to be endpoint inclusive, so should not have any false negatives regardless of bounds inclusiveness
        Some(arg => arg.between(prop, typ, convert(bounds.lower.value.get), convert(bounds.upper.value.get)))
      } else if (bounds.isBounded) {
        if (bounds.upper.value.isDefined) {
          if (bounds.upper.inclusive) {
            Some(arg => arg.lessThanEquals(prop, typ, convert(bounds.upper.value.get)))
          } else {
            Some(arg => arg.lessThan(prop, typ, convert(bounds.upper.value.get)))
          }
        } else if (bounds.lower.inclusive) {
          Some(arg => arg.startNot().lessThan(prop, typ, convert(bounds.lower.value.get)).end())
        } else {
          Some(arg => arg.startNot().lessThanEquals(prop, typ, convert(bounds.lower.value.get)).end())
        }
      } else {
        None
      }
    } else {
      Some(arg => arg.equals(prop, typ, convert(bounds.lower.value.get)))
    }
  }

  private def addPoint(prop: String, bounds: Geometry): SearchArgument.Builder => Unit = {
    val x = OrcFileSystemStorage.geometryXField(prop)
    val y = OrcFileSystemStorage.geometryYField(prop)
    val envelope = bounds.getEnvelopeInternal

    arg => {
      arg.startAnd()
      if (envelope.getMinX == envelope.getMaxX) {
        arg.equals(x, PredicateLeaf.Type.FLOAT, envelope.getMinX)
      } else {
        arg.between(x, PredicateLeaf.Type.FLOAT, envelope.getMinX, envelope.getMaxX)
      }
      if (envelope.getMinY == envelope.getMaxY) {
        arg.equals(y, PredicateLeaf.Type.FLOAT, envelope.getMinY)
      } else {
        arg.between(y, PredicateLeaf.Type.FLOAT, envelope.getMinY, envelope.getMaxY)
      }
      arg.end()
    }
  }
}


text:
import os
import sys

import tm
import tmparser
import tmexceptions
import highlighters

from PyQt4 import QtGui
from PyQt4.QtCore import Qt

__prog__='Turing Machine Simulator'

#
#
def main():

    # Initialized the qt application
    app = QtGui.QApplication(sys.argv)
    gui = GUI()
    gui.initGUI()
    gui.installHandlers()
    gui.show()
    sys.exit(app.exec_())

#
#
class GUI(QtGui.QWidget):

    TAPE_SIZE = 31
    TAPE_HEAD = int(round(TAPE_SIZE / 2))
    TAPE_HEAD_LEFT = TAPE_HEAD - 1
    TAPE_HEAD_RIGHT = TAPE_HEAD + 1
    DEF_WIDTH = 800
    DEF_HEIGHT = 600
    HSPACING = 10
    VSPACING = 5
    ICON = 'icon.png'

    # Tape style(s)
    TAPE_HEAD_STYLE = 'QLineEdit { border: 2px solid red; background: white;}'

    #
    #
    def __init__(self):
        super(GUI, self).__init__()
        # Turing machine and Turing machine parser
        self.parser = tmparser.TuringMachineParser()
        self.turing_machine = None

    #
    #
    def initGUI(self):

        # Configure window
        self.setMinimumSize(GUI.DEF_WIDTH, GUI.DEF_HEIGHT)
        self.setWindowTitle(__prog__)
        self.setWindowIcon(QtGui.QIcon(GUI.ICON))

        self.main_vbox = QtGui.QVBoxLayout(self)

        # Add Tape widgets
        self._initTape()
        # Add log text box
        self._initLogArea()

        # Add controls
        self._initControlArea()

        self.resize(GUI.DEF_WIDTH, GUI.DEF_HEIGHT)

    #
    #
    def installHandlers(self):
        self.set_tm_btn.clicked.connect(self.onSetTuringMachineClicked)
        self.set_tape_btn.clicked.connect(self.onSetTapeClicked)
        self.run_step_btn.clicked.connect(self.onRunStepClicked)
        self.run_all_btn.clicked.connect(self.onRunUntilHaltClicked)
        self.src_load_btn.clicked.connect(self.onLoadClicked)
        self.src_save_btn.clicked.connect(self.onSaveClicked)
        self.clear_log_btn.clicked.connect(self.onClearLogClicked)
        self.print_all_tape_btn.clicked.connect(self.onPrintAllTape)

    #
    # QtGui event handlers
    #

    #
    #
    def onSetTuringMachineClicked(self):

        tmstr = str(self.src_textbox.toPlainText())
        try:
            self.parser.clean()
            self.parser.parseString(tmstr)
            self.turing_machine = self.parser.create()
            self.turing_machine.attachObserver(self)

            self._printInfoLog('Turing machine created')
            self._printInfoLog('Current state: ' +
                                str(self.turing_machine.getCurrentState()))

            #sys.stderr.write(str(self.turing_machine) + '\n')
        except Exception, e:
            self._printErrorLog('Error: %s' % str(e))

    #
    #
    def onSetTapeClicked(self):
        tapestr = str(self.tape_textbox.toPlainText())
        if self.turing_machine != None:
            self.turing_machine.setTape(tapestr)
            self.turing_machine.setAtInitialState()
            self._printInfoLog('Tape value established')
        else:
            self._printErrorLog('Error: The Turing machine must be set before'
                                ' set the tape')

    #
    #
    def onRunStepClicked(self):

        try:
            self.turing_machine.step()

        except tmexceptions.HaltStateException, e:
            self._printErrorLog(str(e))

        except tmexceptions.UnsetTapeException, e:
            self._printErrorLog(str(e))

        except tmexceptions.UnknownTransitionException, e:
            self._printErrorLog(str(e))

        except AttributeError:
            self._printErrorLog('Error: Turing machine is unset')

    #
    #
    def onRunUntilHaltClicked(self):

        try:

            if self.turing_machine.isAtHaltState():
                self._printErrorLog('Error: The Turing Machine is on halt state')

            else:
                self._printInfoLog('---------- Run Until Halt ----------')

                try:
                    while not self.turing_machine.isAtHaltState():
                        self.turing_machine.step()

                except tmexceptions.UnsetTapeException, e:
                    self._printErrorLog(str(e))

                except tmexceptions.UnknownTransitionException, e:
                    self._printErrorLog(str(e))

        except AttributeError:
            self._printErrorLog('Error: Turing machine is unset')
    #
    #
    def onLoadClicked(self):

        fname = QtGui.QFileDialog.getOpenFileName(self, 'Load file',
                                                  os.path.expanduser('~'))

        if fname:
            f = open(fname, 'r')
            fstr = f.read()
            self.src_textbox.setPlainText(fstr)
            f.close()

            self._printInfoLog('Loaded file: %s' % fname)
    #
    #
    def onSaveClicked(self):

        fname = QtGui.QFileDialog.getSaveFileName(self, 'Save file',
                                                  os.path.expanduser('~'))

        if fname:
            f = open(fname, 'w')
            fstr = str(self.src_textbox.toPlainText())
            f.write(fstr)
            f.close()

            self._printInfoLog('Saved file: %s' % fname)

    #
    #
    def onClearLogClicked(self):

        self.log_textbox.clear()

    #
    #
    def onPrintAllTape(self):
        if self.turing_machine:
            try:
                tape_value = ' '.join(self.turing_machine.getTapeIterator())
                self._printInfoLog('***************************************')
                self._printInfoLog('Tape Values:')
                self._printStrikingInfoLog(tape_value)
                self._printInfoLog('***************************************')
            except Exception, e:
                self._printErrorLog(str(e))
        else:
            self._printErrorLog('Error: The Turing Machine must be set '
                                'before print the tape')

    #
    # Turing Machine observer methods
    #

    #
    #
    def onStepStart(self, current_state, current_tape_symbol):
        self._printInfoLog('+++++++++++++++++++++++++++++++++++++++++++++++')
        self._printInfoLog('Started step at state "%s" with tape symbol "%s"'
                            % ( str(current_state), str(current_tape_symbol)))
    #
    #
    def onStepEnd(self, new_state, writed_symbol, movement):
        self._printInfoLog('-----------------------------------------------')

        self._printInfoLog('Writed Symbol: ' + str(writed_symbol) )

        if movement == tm.TuringMachine.MOVE_LEFT:
            self._printInfoLog('Head moved to the left')
        elif movement == tm.TuringMachine.MOVE_RIGHT:
            self._printInfoLog('Head moved to the right')
        else:
            self._printInfoLog('Head remains at the same position')

        self._printInfoLog('Current state: ' + str(new_state) +
            (' (FINAL)' if self.turing_machine.isAtFinalState() else '') )

    #
    #
    def onTapeChanged(self, head_pos):
        self._redrawTape(head_pos)

    #
    #
    def onHeadMoved(self, head_pos, old_head_pos):
        self._redrawTape(head_pos)

    #
    # 'Private'
    #

    #
    # Creates and adds the tape widgets
    def _initTape(self):
        self.tape_label = QtGui.QLabel('Tape', self)

        self.tape_hbox = QtGui.QHBoxLayout()

#        self.tape_lbutton = QtGui.QPushButton('<', self)
#        self.tape_rbutton = QtGui.QPushButton('>', self)
        self.tape_textboxes = self._createTape()

#        self.tape_hbox.addWidget(self.tape_lbutton)
        for txbx in self.tape_textboxes:
            self.tape_hbox.addWidget(txbx)
#        self.tape_hbox.addWidget(self.tape_rbutton)

        self.main_vbox.addWidget(self.tape_label, 0, Qt.AlignCenter)
        self.main_vbox.addLayout(self.tape_hbox, 1)
        self.main_vbox.addSpacing(GUI.VSPACING)

    #
    #
    def _createTape(self):
        tptx = [QtGui.QLineEdit(self) for i in xrange(GUI.TAPE_SIZE)]
        for txbx in tptx:
            txbx.setReadOnly(True)
            txbx.setFocusPolicy(Qt.NoFocus)
            txbx.setAlignment(Qt.AlignHCenter)

        tptx[GUI.TAPE_HEAD].setStyleSheet(GUI.TAPE_HEAD_STYLE)
        return tptx

    #
    #
    def _initLogArea(self):

        log_vbox = QtGui.QVBoxLayout()

        # Add log text box
        log_label = QtGui.QLabel('Activity Log', self)
        self.log_textbox = QtGui.QTextEdit(self)
        self.log_textbox.setReadOnly(True)
        log_vbox.addWidget(log_label, 0, Qt.AlignCenter)
        log_vbox.addWidget(self.log_textbox)

        # Add some control buttons
        log_hbox = QtGui.QHBoxLayout()
        self.clear_log_btn = QtGui.QPushButton('Clear Log', self)
        self.print_all_tape_btn = QtGui.QPushButton('Print All Tape', self)

        log_hbox.addWidget(self.print_all_tape_btn)
        log_hbox.addWidget(self.clear_log_btn)

        log_vbox.addLayout(log_hbox)

        # Add all the previous stuff to the window layout
        self.main_vbox.addLayout(log_vbox, 1)
        self.main_vbox.addSpacing(GUI.VSPACING)

    #
    #
    def _initControlArea(self):
        self.ctrl_hbox = QtGui.QHBoxLayout()

        # Add source text box and load/save buttons
        ctrl_llabel = QtGui.QLabel("TM Source Code", self)
        self.src_textbox = QtGui.QTextEdit(self)
        highlighters.TMSourceHightlighter(self.src_textbox, "Classic" )
        self.src_load_btn = QtGui.QPushButton('Load', self)
        self.src_save_btn = QtGui.QPushButton('Save', self)

        self.ctrl_lvbox = QtGui.QVBoxLayout()
        self.ctrl_lvbox.addWidget(ctrl_llabel, 0, Qt.AlignCenter)
        self.ctrl_lvbox.addWidget(self.src_textbox)
        ctrl_btn_hbox = QtGui.QHBoxLayout()
        ctrl_btn_hbox.addWidget(self.src_load_btn)
        ctrl_btn_hbox.addWidget(self.src_save_btn)
        self.ctrl_lvbox.addLayout(ctrl_btn_hbox)

        # Add control buttons
        ctrl_rlabel = QtGui.QLabel("Tape's Initial Value", self)
        self.tape_textbox = QtGui.QPlainTextEdit(self)
        self.set_tm_btn = QtGui.QPushButton('Set TM', self)
        self.set_tape_btn = QtGui.QPushButton('Set Tape', self)
        self.run_step_btn = QtGui.QPushButton('Run Step', self)
        self.run_all_btn = QtGui.QPushButton('Run Until Halt', self)

        self.ctrl_rvbox = QtGui.QVBoxLayout()
        self.ctrl_rvbox.addWidget(ctrl_rlabel, 0, Qt.AlignCenter)
        self.ctrl_rvbox.addWidget(self.tape_textbox)
        self.ctrl_rvbox.addWidget(self.set_tm_btn)
        self.ctrl_rvbox.addWidget(self.set_tape_btn)
        self.ctrl_rvbox.addWidget(self.run_step_btn)
        self.ctrl_rvbox.addWidget(self.run_all_btn)

        # Add some tooltips
        self.set_tape_btn.setToolTip('Sets the tape values and forces the TM '
                                     'to be at the initial state')

        # Add the control area to the main layout
        self.ctrl_hbox.addLayout(self.ctrl_lvbox, 2)
        self.ctrl_hbox.addSpacing(GUI.HSPACING)
        self.ctrl_hbox.addLayout(self.ctrl_rvbox, 1)
        self.main_vbox.addLayout(self.ctrl_hbox, 2)

    #
    #
    def _redrawTape(self, head_pos):
        blank = self.turing_machine.getBlankSymbol()

        sym = self.turing_machine.getSymbolAt(head_pos)
        self.tape_textboxes[GUI.TAPE_HEAD].setText('' if sym == blank
                                                    else str(sym))

        for i in xrange(1, GUI.TAPE_HEAD + 1):
            txtbx_index = GUI.TAPE_HEAD - i
            tape_index = head_pos - i
            sym = self.turing_machine.getSymbolAt(tape_index)
            self.tape_textboxes[txtbx_index].setText('' if sym == blank
                                                    else str(sym))

        for inc, i in enumerate(xrange(GUI.TAPE_HEAD + 1, GUI.TAPE_SIZE)):
            tape_index = head_pos + inc + 1
            sym = self.turing_machine.getSymbolAt(tape_index)
            self.tape_textboxes[i].setText('' if sym == blank else str(sym))

    #
    #
    def _printErrorLog(self, error):
        """
        Prints a message on the log_textbox
        Text Color: RED
        """
        self.log_textbox.setTextColor(Qt.red)
        self.log_textbox.setFontWeight( QtGui.QFont.Normal )
        self.log_textbox.append(error)

    #
    #
    def _printInfoLog(self, msg):
        """
        Prints a message on the log_textbox
        Text Color: BLACK
        """
        self.log_textbox.setTextColor(Qt.black)
        self.log_textbox.setFontWeight( QtGui.QFont.Normal )
        self.log_textbox.append(msg)

    #
    #
    def _printStrikingInfoLog(self, msg):
        """
        Prints a message on the log_textbox makeing it more visible than a
        normal log
        """
        self.log_textbox.setTextColor( Qt.darkBlue )
        self.log_textbox.setFontWeight( QtGui.QFont.Bold )
        self.log_textbox.append(msg)
#
#
if __name__ == '__main__':
    main()


text:
package com.txmcu.iairsdk.config;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.os.CountDownTimer;
import android.util.Log;

import com.txmcu.iairsdk.R;
import com.txmcu.iairsdk.wifi.WifiHotManager;
import com.txmcu.iairsdk.wifi.WifiHotManager.OpretionsType;
import com.txmcu.iairsdk.wifi.WifiHotManager.WifiBroadCastOperations;

/**
 * 设备状态管理器
 * @author Oliver
 *
 */
public class XinStateManager
implements WifiBroadCastOperations , Udpclient.UdpclientOperations{

	private Activity context;
	private XinOperations operations;
	private WifiHotManager wifiHotM;
	private static XinStateManager instance = null;
	private Udpclient udpclient = null;

	static String TAG = "XinStateManager";

	//private iAirApplication application;

	public enum ConfigType {
		Succeed,
		Failed,
		//Failed_Connect_XiaoXin,
	//	Failed_TimeOut,
		//Failed_XiaoXinConfig
	}
	public enum State
	{
		Init,
		//Scaned,
		Config,
	}
	public State mCurState = State.Init;
	public static int TimeOutSecond = 120;

	/**
	 * 回调实现的接口函数,
	 * @author Administrator
	 *
	 */
	public static interface XinOperations {

		/**
		 * @param init callback ,close wait dialog
		 */
		public void initResult(boolean result,String curSSID,List<ScanResult> SSID);

		/**
		 * @param invoke callback
		 */
		public void configResult(ConfigType type );

		public void log(String msg);
	}
	public static void destroy() {
		instance = null;
	}
	public static XinStateManager getInstance(Activity context) {

		if (instance == null) {
			instance = new XinStateManager(context,(XinOperations) context);

		}
		return instance;
	}

	/**
	 * 构造函数,如果当前的WiFi是设备的XIAOXIN_AP,则删除这个WiFi。避免用户WIFI状态切换错误
	 * @param context
	 * @param operations
	 */
	private XinStateManager(Activity context,XinOperations operations) {
		this.context = context;
		this.operations = operations;
		//this.application = ((iAirApplication)context.getApplication());
		wifiHotM = WifiHotManager.getInstance(this.context, XinStateManager.this);
		WifiInfo curWifiInfo = wifiHotM.getConnectWifiInfo();
		if(curWifiInfo!=null&&curWifiInfo.getSSID()!=null&&curWifiInfo.getSSID().endsWith(iAirConstants.XIAOXIN_SSID))
		{
			wifiHotM.removeWifiInfo(curWifiInfo.getNetworkId());
		}
		if (curWifiInfo!=null&&curWifiInfo.getNetworkId()==-1)
		{
			operations.log("no wifi connection");
			//iAirUtil.toastMessage(context, context.getString(R.string.add_device_no_wifi));

		}
		//wifiHotM.scanWifiHot();
	}
	CountDownTimer initCoolTimer;
	int initscanRetryTimes=0;
	public void Init()
	{
		mCurState = State.Init;

		udpclient = new Udpclient(this,this,context,wifiHotM);
		//operations.log("Init");

		startScan();
		//udpclient.operations= this;
		//backupCurrentWifiState();
	}
	/**
	 * 开始扫描WIFI列表
	 */
	private void startScan() {

		WifiInfo curWifiInfo = wifiHotM.getConnectWifiInfo();
		if(curWifiInfo!=null&&curWifiInfo.getSSID()!=null&&curWifiInfo.getSSID().endsWith(iAirConstants.XIAOXIN_SSID))
		{
			wifiHotM.removeWifiInfo(curWifiInfo.getNetworkId());
		}
		_scannlist.clear();
		wifiHotM.scanWifiHot();
		initscanRetryTimes=0;
		if (initCoolTimer!=null) {
			initCoolTimer.cancel();
		}

		//operations.initResult(true, curSSID, SSID)

		initCoolTimer = new CountDownTimer(8000, 3000) {

		     public void onTick(long millisUntilFinished) {
		    	 initscanRetryTimes++;

		    	 if(mCurState == State.Init&&_scannlist.size()==0)
		    	 {
		    		 operations.log("times"+initscanRetryTimes+" left:"+millisUntilFinished/1000);
		    		// if()
		    		// {
		    			// operations.log("try max times:"+initscanRetryTimes);
		    			// operations.configResult(ConfigType.Failed);
		    			 //initCoolTimer.cancel();
		    		// }

		    		 initscanRetryTimes++;
		    		 operations.log("scan timeout retry"+initscanRetryTimes);
		    		 wifiHotM.unRegisterWifiScanBroadCast();
		    		 wifiHotM.scanWifiHot();

		    	 }
		    	// iAirUtil.setProgressText(getString(R.string.add_device_cooldown)+(millisUntilFinished / 1000)+getString(R.string.second));
		         //mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
		     }

		     public void onFinish() {

		    	 if(_scannlist.size()==0)
		    	 {
		    			List<ScanResult> apList = wifiHotM.getRecentScanResults();
		    			backupCurrentWifiState(apList);

		    		 //operations.log("times ok");
		    		// operations.initResult(false,"",null);
		    	 }

		    	 //iAirUtil.toastMessage(DeviceAddActivity.this, getString(R.string.add_device_failed));
		         //mTextField.setText("done!");
		     }
		  }.start();
	}

/**
	 * 用户开始配置设备,此过程需要120秒。
 *
 * @param SSID
 * @param Pwd
 * @param _userid
 * @param _sn
 * @param vsn
 * @param homeId
 */
	public void Config(String SSID,String Pwd,String _sn,String _userid,String vsn,String homeId)
	{
		mCurState = State.Config;
		SSID = SSID.replace("\"", "");
		//application.setWifibackupPwd(Pwd);
		//wifibackupPwd = Pwd;
		userid=_userid;
		sn=_sn;

		//if(mCurState == State.Config)
		//{
		List<String> detailinfo = getWifiDetailInfo(SSID);
		udpclient.setSendWifiInfo(SSID, Pwd,
				detailinfo.get(0), detailinfo.get(1),
					detailinfo.get(2),sn,userid,vsn,homeId);

			//udpclient.Looper();
		//}
		//
	}
	public void Destroy()
	{
		restoreCurrentWifiState();
		wifiHotM.unRegisterWifiConnectBroadCast();
		wifiHotM.unRegisterWifiScanBroadCast();
		wifiHotM.unRegisterWifiStateBroadCast();
		WifiHotManager.destroy();
		XinStateManager.destroy();

		if (initCoolTimer!=null) {
			initCoolTimer.cancel();
		}
		udpclient.destroy();

	}

	/**
	 * 获取WIFI的详细信息,如加密方式,加密算法和通道信息
	 * @param ssid
	 * @return
	 */
	public List<String> getWifiDetailInfo(String ssid)
	{
		String channel = "6";
		String AuthMode="OPEN";
		String EncrypType="None";

		//application.setWifibackupChannel("6");
		//wifibackupChannel = "6";
		for (ScanResult scanRet : _scannlist)
		{
			String scanSSIDString = scanRet.SSID.replace("\"", "");
			if (scanSSIDString.equals(ssid))
			{
				int  ch =  getChannel(scanRet.frequency);
				channel = String.valueOf(ch);
				logudp(scanRet.capabilities);

				if (scanRet.equals("[ESS]"))
				{//OPEN None pwd
					 AuthMode="OPEN";
					 EncrypType="None";
				}
				else
				{
					if(scanRet.capabilities.contains("WPA") && !scanRet.capabilities.contains("WPA2"))
	                 {
						 AuthMode ="WPAPSK";

	                 }
					 else if(scanRet.capabilities.contains("WPA2"))
	                 {
						 AuthMode ="WPA2PSK";

	                 }
					 else if(scanRet.capabilities.contains("WEP"))   {

						 EncrypType="WEP";
						 if(scanRet.capabilities.contains("ESS"))   {
							 AuthMode ="OPEN";
						 }
						 else {
							 AuthMode ="SHARED";
						}
					}

	                 if(scanRet.capabilities.contains("TKIP"))
	                 {
	                	 EncrypType="TKIP";
	                 }
	                 if(scanRet.capabilities.contains("CCMP"))
	                 {
	                	 EncrypType="AES";
	                 }
				}
				break;
			}
		}

		//List<String> authInfo = wifiHotM.getAuthMode(ssid);
		List<String> ret = new ArrayList<String>();

		ret.add(AuthMode);
		ret.add(EncrypType);
		ret.add(channel);
		return ret;
	}
	/**
	 * 检测ssid是否在list中
	 * @param list
	 * @param ssid
	 * @return
	 */
	Boolean isWifiContain(List<ScanResult> list,String ssid)
	{
		for (ScanResult scanResult : list) {
			if (scanResult.SSID.equals(ssid)) {
				return true;
			}
		}
		return false;
	}
	String userid;
	String sn;
	List<ScanResult> _scannlist = new ArrayList<ScanResult>();
	int wifiBackupNetId = -1;

/**
	 * 备份当前已经连接的WIFI,连接完设备后,需要改回当前的配置
 * @param scannlist
 */
	private void backupCurrentWifiState(List<ScanResult> scannlist )
	{

		WifiInfo info = wifiHotM.getConnectWifiInfo();
		//wifibackupNetId=-1;
		//_scannlist = scannlist;
		for (ScanResult scanResult : scannlist) {
			if (!scanResult.SSID.equals(iAirConstants.XIAOXIN_SSID))
			{
				if(!isWifiContain(_scannlist,scanResult.SSID))
					_scannlist.add(scanResult);
			}
		}
		//application.setWifibackupSSID("");
		String curSSIDString = "";
		wifiBackupNetId = -1;
		//application.setWifibackupNetId(-1);
		if (info!=null&&info.getSSID()!=null&&!info.getSSID().equals(iAirConstants.XIAOXIN_SSID)) {
			wifiBackupNetId = info.getNetworkId();
			//application.setWifibackupNetId(info.getNetworkId());
			curSSIDString = info.getSSID().replace("\"", "");

		}

		operations.initResult(true,curSSIDString,_scannlist);

	}

/**
	 * 还原之前备份的设备信息
 */
	public void restoreCurrentWifiState() {
		//operations.log("restoreCurrentWifiState");
		if(wifiBackupNetId!=-1)
			wifiHotM.enableNetWorkById(wifiBackupNetId);
	}
	// wifi scan callback
	@Override
	public void disPlayWifiScanResult(List<ScanResult> wifiList) {

		wifiHotM.unRegisterWifiScanBroadCast();
		Log.i(TAG, " scan: = " + wifiList);
		operations.log("disPlayWifiScanResult"+wifiList.size());
		if(mCurState == State.Init)
		{
			//mCurState = State.Scaned;
			backupCurrentWifiState(wifiList);
			//if (application.getWifibackupSSID().length()>0) {

			//}
		}

		//wifiHotM.enableNetwork(SSID, password)
	}

	// wifi connect callback
	@Override
	public boolean disPlayWifiConResult(boolean result, WifiInfo wifiInfo) {

		Log.i(TAG, "disPlayWifiConResult");
		//operations.log("disPlayWifiConResult"+result+wifiInfo);
		wifiHotM.unRegisterWifiConnectBroadCast();

		return false;
	}

	// wifi connect & scan ,when wifi enable
	@Override
	public void operationByType(OpretionsType type, String SSID,String pwd) {
		Log.i(TAG, "operationByType!type = " + type);

		operations.log("operationByType!type = " + type);
		if (type == OpretionsType.SCAN) {
			//wifiHotM.scanWifiHot();
			startScan();
		}
		else {
			wifiHotM.connectToHotpot(SSID, pwd);
		}
	}
	@Override
	public void setState(boolean result, String exception) {
		// TODO Auto-generated method stub
		restoreCurrentWifiState();
		//operations.log(" setState result:"+exception);
		if (result && exception.startsWith("Ok")) {
			operations.configResult(ConfigType.Succeed);
		}
		else {
			operations.configResult(ConfigType.Failed);
		}
	}
	@Override
	public void logudp(String msg) {
		// TODO Auto-generated method stub
		operations.log("udp:" + msg);
	}

	 public static int getChannel(int frequency)
	    {
	            int channel = 0;
	            switch(frequency){
	            case 2412:
	                    channel = 1;
	                    break;
	            case 2417:
	                    channel = 2;
	                    break;
	            case 2422:
	                    channel = 3;
	                    break;
	            case 2427:
	                    channel = 4;
	                    break;
	            case 2432:
	                    channel = 5;
	                    break;
	            case 2437:
	                    channel = 6;
	                    break;
	            case 2442:
	                    channel = 7;
	                    break;
	            case 2447:
	                    channel = 8;
	                    break;
	            case 2452:
	                    channel = 9;
	                    break;
	            case 2457:
	                    channel = 10;
	                    break;
	            case 2462:
	                    channel = 11;
	                    break;
	            case 2467:
	                    channel = 12;
	                    break;
	            case 2472:
	                    channel = 13;
	                    break;
	            case 2484:
	                    channel = 14;
	                    break;
	            }
	            return channel;
	    }

}


text:
using Content.Shared.Actions.ActionTypes;
using Content.Shared.Hands;
using Content.Shared.Inventory;
using Content.Shared.Inventory.Events;
using Robust.Shared.Map;
using Robust.Shared.Serialization;

namespace Content.Shared.Actions;

/// <summary>
///     Event raised directed at items or clothing when they are equipped or held. In order for an item to grant actions some
///     system can subscribe to this event and add actions to the <see cref="Actions"/> list.
/// </summary>
/// <remarks>
///     Note that a system could also just manually add actions as a result of a <see cref="GotEquippedEvent"/> or <see
///     cref="GotEquippedHandEvent"/>. This exists mostly as a convenience event, while also helping to keep
///     action-granting logic separate from general equipment behavior.
/// </remarks>
public sealed class GetItemActionsEvent : EntityEventArgs
{
    public SortedSet<ActionType> Actions = new();

    /// <summary>
    ///     Slot flags for the inventory slot that this item got equipped to. Null if not in a slot (i.e., if equipped to hands).
    /// </summary>
    public SlotFlags? SlotFlags;

    /// <summary>
    ///     If true, the item was equipped to a users hands.
    /// </summary>
    public bool InHands => SlotFlags == null;

    public GetItemActionsEvent(SlotFlags? slotFlags = null)
    {
        SlotFlags = slotFlags;
    }
}

/// <summary>
///     Event used to communicate with the server that a client wishes to perform some action.
/// </summary>
[Serializable, NetSerializable]
public sealed class RequestPerformActionEvent : EntityEventArgs
{
    public readonly ActionType Action;
    public readonly EntityUid? EntityTarget;
    public readonly MapCoordinates? MapTarget;

    public RequestPerformActionEvent(InstantAction action)
    {
        Action = action;
    }

    public RequestPerformActionEvent(EntityTargetAction action, EntityUid entityTarget)
    {
        Action = action;
        EntityTarget = entityTarget;
    }

    public RequestPerformActionEvent(WorldTargetAction action, MapCoordinates mapTarget)
    {
        Action = action;
        MapTarget = mapTarget;
    }
}

/// <summary>
///     This is the type of event that gets raised when an <see cref="InstantAction"/> is performed. The <see
///     cref="Performer"/> field is automatically filled out by the <see cref="SharedActionsSystem"/>.
/// </summary>
/// <remarks>
///     To define a new action for some system, you need to create an event that inherits from this class.
/// </remarks>
public abstract class InstantActionEvent : BaseActionEvent { }

/// <summary>
///     This is the type of event that gets raised when an <see cref="EntityTargetAction"/> is performed. The <see
///     cref="Performer"/> and <see cref="Target"/> fields will automatically be filled out by the <see
///     cref="SharedActionsSystem"/>.
/// </summary>
/// <remarks>
///     To define a new action for some system, you need to create an event that inherits from this class.
/// </remarks>
public abstract class EntityTargetActionEvent : BaseActionEvent
{
    /// <summary>
    ///     The entity that the user targeted.
    /// </summary>
    public EntityUid Target;
}

/// <summary>
///     This is the type of event that gets raised when an <see cref="WorldTargetAction"/> is performed. The <see
///     cref="Performer"/> and <see cref="Target"/> fields will automatically be filled out by the <see
///     cref="SharedActionsSystem"/>.
/// </summary>
/// <remarks>
///     To define a new action for some system, you need to create an event that inherits from this class.
/// </remarks>
public abstract class WorldTargetActionEvent : BaseActionEvent
{
    /// <summary>
    ///     The coordinates of the location that the user targeted.
    /// </summary>
    public MapCoordinates Target;
}

/// <summary>
///     Base class for events that are raised when an action gets performed. This should not generally be used outside of the action
///     system.
/// </summary>
[ImplicitDataDefinitionForInheritors]
public abstract class BaseActionEvent : HandledEntityEventArgs
{
    /// <summary>
    ///     The user performing the action.
    /// </summary>
    public EntityUid Performer;
}


text:
package de.saarland.util;

/**
 * @author Almer Bolatov
 *         Date: 10/31/13
 *         Time: 1:23 PM
 */
public class Logger {
	static int line = 1;
	static int indent = 0;
	private Logger() {}

	private static boolean ON = true;
	private static String filter = "GN";

	public static void log(String tag, String msg) {
		if (ON && tag.equals(tag)) {
			System.out.println(String.format("%d.\t%s: %s%s", line++, tag, ind(), msg));
		}
	}

	public static void err(String tag, String msg) {
		if (ON && tag.equals(tag)) {
	//		System.err.println(String.format("%d.\t%s: %s", line++, tag, msg));
			System.out.println(String.format("%d.\t%s: %s%s", line++, tag, ind(), msg).toUpperCase());
		}
	}

	public static void increment() {
		indent++;
	}

	public static void decrement() {
		indent--;
	}

	private static String ind() {
		assert indent >= 0;

		String s = "";
		for (int i = 0; i < indent; i++) {
			s += "\t";
		}
		return s;
	}
}


text:
"""TVM Script Parser Intrinsic Classes"""
# pylint: disable=redefined-builtin, relative-beyond-top-level
import tvm.tir
from .registry import register
from .utils import get_param_list

class Intrin:
    def __init__(self, intrin, stmt=False):
        self.intrin = intrin
        self.stmt = stmt

    def signature(self):
        return "tir." + self.intrin.__name__, get_param_list(self.intrin)

    def handle(self, arg_list):
        return self.intrin(*arg_list)

@register
def bool(imm):
    return tvm.tir.const(imm, "bool")

@register
def int8(imm):
    return tvm.tir.const(imm, "int8")

@register
def int16(imm):
    return tvm.tir.const(imm, "int16")

@register
def int32(imm):
    return tvm.tir.const(imm, "int32")

@register
def int64(imm):
    return tvm.tir.const(imm, "int64")

@register
def uint8(imm):
    return tvm.tir.const(imm, "uint8")

@register
def uint16(imm):
    return tvm.tir.const(imm, "uint16")

@register
def uint32(imm):
    return tvm.tir.const(imm, "uint32")

@register
def uint64(imm):
    return tvm.tir.const(imm, "uint64")

@register
def float8(imm):
    return tvm.tir.const(imm, "float8")

@register
def float16(imm):
    return tvm.tir.const(imm, "float16")

@register
def float32(imm):
    return tvm.tir.const(imm, "float32")

@register
def float64(imm):
    return tvm.tir.const(imm, "float64")

@register
def floordiv(x, y):
    return tvm.tir.floordiv(x, y)

@register
def floormod(x, y):
    return tvm.tir.floormod(x, y)

@register
def load(dtype, var, index, predicate=True):
    return tvm.tir.Load(dtype, var, index, predicate)

@register
def cast(value, dtype):
    return tvm.tir.Cast(dtype, value)

@register
def ramp(base, stride, lanes):
    return tvm.tir.Ramp(base, stride, lanes)

@register
def broadcast(value, lanes):
    return tvm.tir.Broadcast(value, lanes)

@register
def iter_var(var, dom, iter_type, thread_tag):
    iter_type = getattr(tvm.tir.IterVar, iter_type)
    return tvm.tir.IterVar(dom, var, iter_type, thread_tag)

@register
def max(a, b):  # pylint: disable=redefined-builtin
    return tvm.tir.Max(a, b)

def get_axis(begin, end, iter_type):
    ana = tvm.arith.Analyzer()
    extent = ana.simplify(end - begin)
    block_var_dom = tvm.ir.Range.from_min_extent(begin, extent)

    iter_type_dict = {"data_par": 0, "reduce": 2, "scan": 3, "opaque": 4}
    return tvm.tir.IterVar(block_var_dom, "bv", iter_type_dict[iter_type])

@register
def range(begin, end):
    return get_axis(begin, end, "data_par")

@register
def reduce_axis(begin, end):
    return get_axis(begin, end, "reduce")

@register
def scan_axis(begin, end):
    return get_axis(begin, end, "scan")

@register
def opaque_axis(begin, end):
    return get_axis(begin, end, "opaque")

@register
class EvaluateIntrin(Intrin):
    def __init__(self):
        def evaluate(value):
            return tvm.tir.Evaluate(value)

        super().__init__(evaluate, stmt=True)

@register
class StoreIntrin(Intrin):
    def __init__(self):
        def store(var, index, value, predicate=True):
            return tvm.tir.Store(var, value, index, predicate)

        super().__init__(store, stmt=True)