text:
#include "device_manager.h"
#include "atomisp_device.h"
#include "isp_controller.h"
#include "isp_image_processor.h"
#include "x3a_analyzer_simple.h"
#if HAVE_IA_AIQ
#include "x3a_analyzer_aiq.h"
#endif
#if HAVE_LIBCL
#include "cl_3a_image_processor.h"
#include "cl_csc_image_processor.h"
#include "cl_hdr_handler.h"
#include "cl_tnr_handler.h"
#endif
#if HAVE_LIBDRM
#include "drm_display.h"
#endif
#include "analyzer_loader.h"
#include <base/xcam_3a_types.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <string>
#include <getopt.h>
#include "test_common.h"

using namespace XCam;

static Mutex g_mutex;
static Cond  g_cond;
static bool  g_stop = false;

class MainDeviceManager
    : public DeviceManager
{
public:
    MainDeviceManager ()
        : _file (NULL)
        , _save_file (false)
        , _interval (1)
        , _frame_count (0)
        , _frame_save (0)
        , _enable_display (false)
    {
#if HAVE_LIBDRM
        _display = DrmDisplay::instance();
#endif
        XCAM_OBJ_PROFILING_INIT;
    }

    ~MainDeviceManager () {
        close_file ();
    }

    void enable_save_file (bool enable) {
        _save_file = enable;
    }
    void set_interval (uint32_t inteval) {
        _interval = inteval;
    }
    void set_frame_save (uint32_t frame_save) {
        _frame_save = frame_save;
    }

    void enable_display(bool value) {
        _enable_display = value;
    }

    void set_display_mode(DrmDisplayMode mode) {
        _display->set_display_mode (mode);
    }

protected:
    virtual void handle_message (SmartPtr<XCamMessage> &msg);
    virtual void handle_buffer (SmartPtr<VideoBuffer> &buf);

    int display_buf (SmartPtr<VideoBuffer> &buf);

private:
    void open_file ();
    void close_file ();

    FILE      *_file;
    bool       _save_file;
    uint32_t   _interval;
    uint32_t   _frame_count;
    uint32_t   _frame_save;
    SmartPtr<DrmDisplay> _display;
    bool       _enable_display;
    XCAM_OBJ_PROFILING_DEFINES;
};

void
MainDeviceManager::handle_message (SmartPtr<XCamMessage> &msg)
{
    XCAM_UNUSED (msg);
}

void
MainDeviceManager::handle_buffer (SmartPtr<VideoBuffer> &buf)
{
    FPS_CALCULATION (fps_buf, 30);

    XCAM_OBJ_PROFILING_START;

    if (_enable_display)
        display_buf (buf);

    XCAM_OBJ_PROFILING_END("main_dev_manager_display", 30);

    if (!_save_file)
        return ;

    if ((_frame_count++ % _interval) != 0)
        return;

    if ((_frame_save != 0) && (_frame_count > _frame_save)) {
        SmartLock locker (g_mutex);
        g_stop = true;
        g_cond.broadcast ();
        return;
    }

    const VideoBufferInfo & frame_info = buf->get_video_info ();
    uint8_t *frame = buf->map ();

    if (frame == NULL)
        return;

    uint32_t size = 0;

    switch(frame_info.format)  {
    case V4L2_PIX_FMT_NV12:  // 420
    case V4L2_PIX_FMT_NV21:
        size = XCAM_ALIGN_UP(frame_info.width, 2) * XCAM_ALIGN_UP(frame_info.height, 2) * 3 / 2;
        break;
    case V4L2_PIX_FMT_YUV422P: // 422 Planar
    case V4L2_PIX_FMT_YUYV: // 422
    case V4L2_PIX_FMT_SBGGR10:
    case V4L2_PIX_FMT_SGBRG10:
    case V4L2_PIX_FMT_SGRBG10:
    case V4L2_PIX_FMT_SRGGB10:
    case V4L2_PIX_FMT_SBGGR12:
    case V4L2_PIX_FMT_SGBRG12:
    case V4L2_PIX_FMT_SGRBG12:
    case V4L2_PIX_FMT_SRGGB12:
        size = XCAM_ALIGN_UP(frame_info.width, 2) * XCAM_ALIGN_UP(frame_info.height, 2) * 2;
        break;
    default:
        XCAM_LOG_ERROR (
            "unknown v4l2 format(%s) in buffer handle",
            xcam_fourcc_to_string (frame_info.format));
        return;
    }

    open_file ();

    if (!_file) {
        XCAM_LOG_ERROR ("open file failed");
    }

    if (fwrite (frame, size, 1, _file) <= 0) {
        XCAM_LOG_WARNING ("write frame failed.");
    }
}

int
MainDeviceManager::display_buf (SmartPtr<VideoBuffer> &buf)
{
#if HAVE_LIBDRM
    XCamReturn ret = XCAM_RETURN_NO_ERROR;
    const VideoBufferInfo & frame_info = buf->get_video_info ();
    struct v4l2_rect rect = { 0, 0, (int)frame_info.width, (int)frame_info.height };

    if (!_display->is_render_inited ()) {
        ret = _display->render_init (0, 0, 1920, 1080, frame_info.format, &rect);
        CHECK (ret, "display failed on render_init");
    }
    ret = _display->render_setup_frame_buffer (buf);
    CHECK (ret, "display failed on framebuf set");
    ret = _display->render_buffer (buf);
    CHECK (ret, "display failed on rendering");
#endif
    return 0;
}

void
MainDeviceManager::open_file ()
{
    if ((_file) && (_frame_save == 0))
        return;

    std::string file_name = DEFAULT_SAVE_FILE_NAME;

    if (_frame_save != 0) {
        file_name += std::to_string(_frame_count);
    }
    file_name += ".raw";

    _file = fopen(file_name.c_str(), "wb");
}

void
MainDeviceManager::close_file ()
{
    if (_file)
        fclose (_file);
    _file = NULL;
}

#define V4L2_CAPTURE_MODE_STILL   0x2000
#define V4L2_CAPTURE_MODE_VIDEO   0x4000
#define V4L2_CAPTURE_MODE_PREVIEW 0x8000

typedef enum {
    AnalyzerTypeSimple = 0,
    AnalyzerTypeAiq,
    AnalyzerTypeDynamic,
} AnalyzerType;

void dev_stop_handler(int sig)
{
    XCAM_UNUSED (sig);

    SmartLock locker (g_mutex);
    g_stop = true;
    g_cond.broadcast ();

    //exit(0);
}

void print_help (const char *bin_name)
{
    printf ("Usage: %s [-a analyzer]\n"
            "Configurations:\n"
            "\t -a analyzer   specify a analyzer\n"
            "\t               select from [simple, aiq, dynamic], default is [simple]\n"
            "\t -m mem_type   specify video memory type\n"
            "\t               mem_type select from [dma, mmap], default is [mmap]\n"
            "\t -s            save file to %s\n"
            "\t -n interval   save file on every [interval] frame\n"
            "\t -c            process image with cl kernel\n"
            "\t -f pixel_fmt  specify output pixel format\n"
            "\t               pixel_fmt select from [NV12, YUYV, BA10, RG12], default is [NV12]\n"
            "\t -d cap_mode   specify capture mode\n"
            "\t               cap_mode select from [video, still], default is [video]\n"
            "\t -i frame_save specify the frame count to save, default is 0 which means endless\n"
            "\t -p preview on local display\n"
            "\t -e display_mode    preview mode\n"
            "\t                select from [primary, overlay], default is [primary]\n"
            "\t -h            help\n"
            "CL features:\n"
            "\t --hdr         specify hdr type, default is hdr off\n"
            "\t               select from [rgb, lab]\n"
            "\t --tnr         specify temporal noise reduction type, default is tnr off\n"
            "\t               select from [rgb, yuv, both]\n"
            "\t --tnr-level   specify tnr level\n"
            "\t --bilateral   enable bilateral noise reduction\n"
            "\t --enable-snr  enable simple noise reduction\n"
            "\t --enable-ee   enable YEENR\n"
            "(e.g.: xxxx --hdr=xx --tnr=xx --tnr-level=xx --bilateral --enable-snr --enable-ee)\n\n"
            , bin_name
            , DEFAULT_SAVE_FILE_NAME);
}

int main (int argc, char *argv[])
{
    XCamReturn ret = XCAM_RETURN_NO_ERROR;
    SmartPtr<MainDeviceManager> device_manager = new MainDeviceManager;
    SmartPtr<V4l2Device> device;
    SmartPtr<V4l2SubDevice> event_device;
    SmartPtr<IspController> isp_controller;
    SmartPtr<X3aAnalyzer> analyzer;
    SmartPtr<ImageProcessor> isp_processor;
    SmartPtr<CLCscImageProcessor> cl_csc_proccessor;
    AnalyzerType  analyzer_type = AnalyzerTypeSimple;
    DrmDisplayMode display_mode = DRM_DISPLAY_MODE_PRIMARY;
#if HAVE_LIBDRM
    SmartPtr<DrmDisplay> drm_disp = DrmDisplay::instance();
#endif

#if HAVE_LIBCL
    SmartPtr<CL3aImageProcessor> cl_processor;
#endif
    bool have_cl_processor = false;
    bool need_display = false;
    enum v4l2_memory v4l2_mem_type = V4L2_MEMORY_MMAP;
    const char *bin_name = argv[0];
    int opt;
    uint32_t capture_mode = V4L2_CAPTURE_MODE_VIDEO;
    uint32_t pixel_format = V4L2_PIX_FMT_NV12;
    uint32_t hdr_type = CL_HDR_DISABLE;
    uint32_t tnr_type = CL_TNR_DISABLE;
    uint32_t denoise_type = 0;
    uint8_t tnr_level = 0;

    const char *short_opts = "sca:n:m:f:d:pi:e:h";
    const struct option long_opts[] = {
        {"hdr", required_argument, NULL, 'H'},
        {"tnr", required_argument, NULL, 'T'},
        {"tnr-level", required_argument, NULL, 'L'},
        {"bilateral", no_argument, NULL, 'I'},
        {"enable-snr", no_argument, NULL, 'S'},
        {"enable-ee", no_argument, NULL, 'E'},
        {0, 0, 0, 0},
    };

    while ((opt = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
        switch (opt) {
        case 'a': {
            if (!strcmp (optarg, "dynamic"))
                analyzer_type = AnalyzerTypeDynamic;
            else if (!strcmp (optarg, "simple"))
                analyzer_type = AnalyzerTypeSimple;
#if HAVE_IA_AIQ
            else if (!strcmp (optarg, "aiq"))
                analyzer_type = AnalyzerTypeAiq;
#endif
            else {
                print_help (bin_name);
                return -1;
            }
            break;
        }

        case 'm': {
            if (!strcmp (optarg, "dma"))
                v4l2_mem_type = V4L2_MEMORY_DMABUF;
            else if (!strcmp (optarg, "mmap"))
                v4l2_mem_type = V4L2_MEMORY_MMAP;
            else
                print_help (bin_name);
            break;
        }

        case 's':
            device_manager->enable_save_file (true);
            break;
        case 'n':
            device_manager->set_interval (atoi(optarg));
            break;
        case 'c':
            have_cl_processor = true;
            break;
        case 'f':
            CHECK_EXP ((strlen(optarg) == 4), "invalid pixel format\n");
            pixel_format = v4l2_fourcc ((unsigned)optarg[0],
                                        (unsigned)optarg[1],
                                        (unsigned)optarg[2],
                                        (unsigned)optarg[3]);
            break;
        case 'd':
            if (!strcmp (optarg, "still"))
                capture_mode = V4L2_CAPTURE_MODE_STILL;
            else if (!strcmp (optarg, "video"))
                capture_mode = V4L2_CAPTURE_MODE_VIDEO;
            else  {
                print_help (bin_name);
                return -1;
            }
            break;
        case 'p':
            need_display = true;
            break;
        case 'e': {
            if (!strcmp (optarg, "primary"))
                display_mode = DRM_DISPLAY_MODE_PRIMARY;
            else if (!strcmp (optarg, "overlay"))
                display_mode = DRM_DISPLAY_MODE_OVERLAY;
            else {
                print_help (bin_name);
                return -1;
            }
            break;
        }
        case 'i':
            device_manager->set_frame_save(atoi(optarg));
            break;
        case 'H': {
            if (!strcasecmp (optarg, "rgb"))
                hdr_type = CL_HDR_TYPE_RGB;
            else if (!strcasecmp (optarg, "lab"))
                hdr_type = CL_HDR_TYPE_LAB;
            else {
                print_help (bin_name);
                return -1;
            }
            break;
        }
        case 'I': {
            denoise_type |= XCAM_DENOISE_TYPE_BILATERAL;
            break;
        }
        case 'S': {
            denoise_type |= XCAM_DENOISE_TYPE_SIMPLE;
            break;
        }
        case 'E': {
            denoise_type |= XCAM_DENOISE_TYPE_EE;
            break;
        }
        case 'T': {
            if (!strcasecmp (optarg, "yuv"))
                tnr_type = CL_TNR_TYPE_YUV;
            else if (!strcasecmp (optarg, "rgb"))
                tnr_type = CL_TNR_TYPE_RGB;
            else if (!strcasecmp (optarg, "both"))
                tnr_type = CL_TNR_TYPE_YUV | CL_TNR_TYPE_RGB;
            else {
                print_help (bin_name);
                return -1;
            }
            break;
        }
        case 'L': {
            if (atoi(optarg) < 0 || atoi(optarg) > 255) {
                print_help (bin_name);
                return -1;
            }
            tnr_level = atoi(optarg);
            break;
        }
        case 'h':
            print_help (bin_name);
            return 0;

        default:
            print_help (bin_name);
            return -1;
        }
    }

    if (need_display) {
        device_manager->enable_display (true);
        device_manager->set_display_mode (display_mode);
    }
    if (!device.ptr ())  {
        if (capture_mode == V4L2_CAPTURE_MODE_STILL)
            device = new AtomispDevice (CAPTURE_DEVICE_STILL);
        else if (capture_mode == V4L2_CAPTURE_MODE_VIDEO)
            device = new AtomispDevice (CAPTURE_DEVICE_VIDEO);
        else
            device = new AtomispDevice (DEFAULT_CAPTURE_DEVICE);
    }
    if (!event_device.ptr ())
        event_device = new V4l2SubDevice (DEFAULT_EVENT_DEVICE);
    if (!isp_controller.ptr ())
        isp_controller = new IspController (device);

    switch (analyzer_type) {
    case AnalyzerTypeSimple:
        analyzer = new X3aAnalyzerSimple ();
        break;
#if HAVE_IA_AIQ
    case AnalyzerTypeAiq:
        analyzer = new X3aAnalyzerAiq (isp_controller, DEFAULT_CPF_FILE);
        break;
#endif
    case AnalyzerTypeDynamic: {
        const char *path_of_3a = DEFAULT_DYNAMIC_3A_LIB;
        SmartPtr<AnalyzerLoader> loader = new AnalyzerLoader (path_of_3a);
        analyzer = loader->load_analyzer (loader);
        CHECK_EXP (analyzer.ptr (), "load dynamic 3a lib(%s) failed", path_of_3a);
        break;
    }
    default:
        print_help (bin_name);
        return -1;
    }

    signal(SIGINT, dev_stop_handler);

    device->set_sensor_id (0);
    device->set_capture_mode (capture_mode);
    //device->set_mem_type (V4L2_MEMORY_DMABUF);
    device->set_mem_type (v4l2_mem_type);
    device->set_buffer_count (8);
    if (pixel_format == V4L2_PIX_FMT_SRGGB12)
        device->set_framerate (30, 1);
    else
        device->set_framerate (25, 1);
    ret = device->open ();
    CHECK (ret, "device(%s) open failed", device->get_device_name());
    ret = device->set_format (1920, 1080, pixel_format, V4L2_FIELD_NONE, 1920 * 2);
    CHECK (ret, "device(%s) set format failed", device->get_device_name());

    ret = event_device->open ();
    CHECK (ret, "event device(%s) open failed", event_device->get_device_name());
    int event = V4L2_EVENT_ATOMISP_3A_STATS_READY;
    ret = event_device->subscribe_event (event);
    CHECK_CONTINUE (
        ret,
        "device(%s) subscribe event(%d) failed",
        event_device->get_device_name(), event);
    event = V4L2_EVENT_FRAME_SYNC;
    ret = event_device->subscribe_event (event);
    CHECK_CONTINUE (
        ret,
        "device(%s) subscribe event(%d) failed",
        event_device->get_device_name(), event);

    device_manager->set_capture_device (device);
    device_manager->set_event_device (event_device);
    device_manager->set_isp_controller (isp_controller);
    if (analyzer.ptr())
        device_manager->set_analyzer (analyzer);

    if (have_cl_processor)
        isp_processor = new IspExposureImageProcessor (isp_controller);
    else
        isp_processor = new IspImageProcessor (isp_controller);

    XCAM_ASSERT (isp_processor.ptr ());
    device_manager->add_image_processor (isp_processor);
    if ((display_mode == DRM_DISPLAY_MODE_PRIMARY) && need_display && (!have_cl_processor)) {
        cl_csc_proccessor = new CLCscImageProcessor();
        XCAM_ASSERT (cl_csc_proccessor.ptr ());
        device_manager->add_image_processor (cl_csc_proccessor);
    }

#if HAVE_LIBCL
    if (have_cl_processor) {
        cl_processor = new CL3aImageProcessor ();
        cl_processor->set_stats_callback(device_manager);
        cl_processor->set_hdr (hdr_type);
        cl_processor->set_denoise (denoise_type);
        if (need_display) {
            cl_processor->set_output_format (V4L2_PIX_FMT_XBGR32);
        }
        cl_processor->set_tnr (tnr_type, tnr_level);
        device_manager->add_image_processor (cl_processor);
    }
#endif

    ret = device_manager->start ();
    CHECK (ret, "device manager start failed");

    // wait for interruption
    {
        SmartLock locker (g_mutex);
        while (!g_stop)
            g_cond.wait (g_mutex);
    }

    ret = device_manager->stop();
    CHECK_CONTINUE (ret, "device manager stop failed");
    device->close ();
    event_device->close ();

    return 0;
}


text:
package self.philbrown.AbLE;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import self.philbrown.AbLE.annotations.AnnotatedLayoutInflater;
import self.philbrown.AbLE.view.AbLE_Annotation;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.RelativeLayout;

/**
 * This activity uses AbLE to create layouts from annotated java code.
 * @author Phil Brown
 *
 */
public class AbLEActivity extends Activity {

	/**
	 * A singleton of this class is kept at the Activity level. For performance reasons, this instance
	 * can only be obtained through weak references using the {@link #obtain()} method.
	 */
	private static AbLEActivity self;

	/**
	 * {@code true} if the user has specified a custom content size. This is accessed by screen-size
	 * related methods that are used for screen sizing and scaling
	 */
	private static boolean customContentSize = false;
	/**
	 * The width specified by the user, in pixels
	 * @see #customContentSize
	 */
	private static int customContentWidth = 0;
	/**
	 * The height specified by the user, in pixels
	 * @see #customContentSize
	 */
	private static int customContentHeight = 0;

	private int backgroundResource = 0;
	private int backgroundColor = Color.BLACK;

	/**
	 * Keeps track of whether or not application-level meta data has already been handled.
	 */
	private static boolean applicationMetaDataUsed = false;

	/** The view in which all content is displayed */
	protected static View contentView;

	/** Keeps track of the current visible state of the keyboard. True if it is visible. Otherwise false. */
	private boolean isKeyboardVisible = false;

	/** Estimated keyboard height */
	private int keyboardHeight = 0;

	/**
	 * Maintains a list of listeners that should receive callbacks for lifecycle events.
	 * This is static to allow it to remain unaltered across mulitple activities.
	 */
	protected static volatile List<ActivityListener> listeners = new ArrayList<ActivityListener>();

	/**
	 * Overrides the default constructor
	 */
	public AbLEActivity()
	{
		super();
		self = this;
	}

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		try {
			if (!applicationMetaDataUsed)
			{
				ApplicationInfo app = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
				Bundle metaData = app.metaData;
				if (metaData != null)
				{
					applicationMetaDataUsed = true;
					//meta-data for screen size can be added in the form WxH, where x must be lower case,
		        	//and W and H refer to the width and height in pixels, respectively
		        	String contentSize = metaData.getString("contentSize");
		        	if (contentSize != null)
		        	{
		        		String[] split = contentSize.split("x");
		        		customContentWidth = Integer.parseInt(split[0]);
		        		customContentHeight = Integer.parseInt(split[1]);

		        		customContentSize = true;

		        	}

		        	int resourceID = metaData.getInt("background", -1);
		        	if (resourceID != -1)
		        	{
		        		backgroundResource = resourceID;
		        	}
		        	else
		        	{
		        		String background = metaData.getString("background");
		        		if (background != null)
		        		{
		        			try
		        			{
		        				backgroundColor = Color.parseColor(background);
		        				AbLEUtil.info("Setting color to %s", background);
		        			}
		        			catch (IllegalArgumentException e)
		        			{
		        				AbLEUtil.err("Invalid color %s!", background);
		        			}
		        		}

		        	}
				}
			}

			ActivityInfo app = getPackageManager().getActivityInfo(getComponentName(), PackageManager.GET_ACTIVITIES|PackageManager.GET_META_DATA);
			Bundle metaData = app.metaData;
	        if (metaData != null)
	        {
	        	String layoutFile = metaData.getString("layout");
	        	AbLEUtil.info("Inflating View at file %s", layoutFile);
	        	Class<?> layout = Class.forName(layoutFile);
	        	contentView = AnnotatedLayoutInflater.inflate(this, layout, null);
	        	contentView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener()
	    		{

	    			public void onGlobalLayout() {
	    			    Rect r = new Rect();
	    			    //r will be populated with the coordinates of your view that area still visible.
	    			    contentView.getWindowVisibleDisplayFrame(r);

	    			    int heightDiff = contentView.getRootView().getHeight() - (r.bottom - r.top);
	    			    if (heightDiff > 100)
	    			    { // if more than 100 pixels, its probably a keyboard...
	    			    	keyboardHeight = heightDiff;
	    			        if (!isKeyboardVisible)
	    			        	setKeyboardVisible(true);
	    			    }
	    			    else
	    			    {
	    			    	if (isKeyboardVisible)
	    			    		setKeyboardVisible(false);
	    			    }
	    			 }
	    		});

	        	if (customContentSize)
	        	{
	        		RelativeLayout rl = new RelativeLayout(this);
	        		rl.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

	        		if (backgroundResource > 0)
	        		{
	        			rl.setBackgroundResource(backgroundResource);
	        		}
	        		else//use background color
	        		{
	        			rl.setBackgroundColor(backgroundColor);
	        		}

	        		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(customContentWidth, customContentHeight);
	        		params.addRule(RelativeLayout.CENTER_IN_PARENT);
	        		contentView.setLayoutParams(params);

	        		rl.addView(contentView);
	        		setContentView(rl);
	        	}
	        	else
	        	{
	        		setContentView(contentView);
	        	}
	        }
		} catch (NameNotFoundException e) {

			e.printStackTrace();
		} catch (ClassNotFoundException e) {

			e.printStackTrace();
		}

		for (ActivityListener listener : listeners)
		{
			listener.onCreate();
		}
	}

	/**
	 * Returns the location of the contentView within the screen. This is different from the screen size
	 * when the developer specifies a custom screen size in the application meta-data
	 * @param out the array in which to place the location x and y coordinates, respectively.
	 */
	public static void getContentLocationOnScreen(int[] out)
	{
		contentView.getLocationOnScreen(out);
	}

	/**
	 * @return {@code true} if the developer has specified a custom screen size in the application
	 * meta-data
	 */
	public static boolean isScreenSizeCustomized()
	{
		return customContentSize;
	}

	/**
	 * @return the developer-customized screen width, or 0 if not specified.
	 */
	public static int getCustomWidth()
	{
		return customContentWidth;
	}

	/**
	 * @return the developer-customized screen height, or 0 if not specified.
	 */
	public static int getCustomHeight()
	{
		return customContentHeight;
	}

	/**
	 * Sets the visible state of the keyboard and notifies any listeners of the change.
	 * @param state new visible state of the keyboard
	 */
	private void setKeyboardVisible(boolean state)
	{
		isKeyboardVisible = state;
		if (state)
		{
			onKeyboardShown();
		}
		else
		{
			onKeyboardHidden();
		}
	}

	public boolean isKeyboardVisible()
	{
		return isKeyboardVisible;
	}

	/** Hides the keyboard if it is open */
	public void hideKeyboard()
	{
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		if (isKeyboardVisible)
			imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
	}

	/** Shows the keyboard if it is closed */
	public void showKeyboard()
	{
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		if (!isKeyboardVisible)
			imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
	}

	/**
	 *
	 * @return the estimated height of the keyboard, or 0 if unknown.
	 */
	public int getKeyboardHeight()
	{
		return keyboardHeight;
	}

	/**
	 * Recursively iterates through all views and view children in the layout to look for
	 * a view with the given id.
	 * @param id the id of the view in question
	 * @param v the view whose id to check, or whose children id's to check
	 * @return the view in the layout with the given id, or null if it was not found.
	 */
	public View recursivelyFindViewById(int id, View v)
	{
		if (v.getId() == id)
		{
			return v;
		}
		else
		{
			if (v instanceof ViewGroup)
			{
				for (int i = 0; i < ((ViewGroup) v).getChildCount(); i++)
				{
					View _v = recursivelyFindViewById(id, ((ViewGroup) v).getChildAt(i));
					if (_v != null)
						return _v;
				}
			}
		}
		return null;
	}

	/**
	 * This is a replacement for {@link Activity#findViewById(int)}, that handles the id query
	 * based on the annotations-based layout scheme.
	 * @param id the view id for which to query
	 * @return the view with the given id, or null if no view with that id is found in the layout.
	 */
	@Override
	public View findViewById(int id)
	{
		return recursivelyFindViewById(id, contentView);
	}

	/**
	 * Adds a listener to {@link #listeners}.
	 * This does not check for multiple instances of listeners.
	 * @param listener
	 */
	public static synchronized void addListener(ActivityListener listener)
	{
		listeners.add(listener);
	}

	/**
	 * Removes the listener. Good idea to call this before a listener is nullified.
	 * @param listener
	 */
	public static synchronized void removeListener(ActivityListener listener)
	{
		listeners.remove(listener);
	}

	/**
	 * Checks to see if the given listener is already registered to receive callbacks
	 * @param listener the listener to check
	 * @return true if {@code listener} is registered. Otherwise, false.
	 */
	public static boolean isListenerRegistered(ActivityListener listener)
	{
		if (listeners.contains(listener))
			return true;
		return false;
	}

	/**
	 * Called when the keyboard is shown on screen.
	 */
	public void onKeyboardShown()
	{
		for (ActivityListener listener : listeners)
		{
			listener.onKeyboardShown();
		}
	}

	/**
	 * Called when the keyboard is hidden from the screen.
	 */
	public void onKeyboardHidden()
	{
		for (ActivityListener listener : listeners)
		{
			listener.onKeyboardShown();
		}
	}

	@Override
	public void onStart()
	{
		super.onStart();
		for (ActivityListener listener : listeners)
		{
			listener.onStart();
		}
	}

	@Override
	public void onResume()
	{
		super.onResume();
		for (ActivityListener listener : listeners)
		{
			listener.onResume();
		}
	}

	@Override
	public void onPause()
	{
		super.onPause();
		for (ActivityListener listener : listeners)
		{
			listener.onPause();
		}
	}

	@Override
	public void onStop()
	{
		super.onStop();
		for (ActivityListener listener : listeners)
		{
			listener.onStop();
		}
	}

	@Override
	public void onDestroy()
	{
		super.onDestroy();
		for (ActivityListener listener : listeners)
		{
			listener.onDestroy();
		}
		//this ensures the static class layout files are properly unloaded
		//android.os.Process.killProcess(android.os.Process.myPid());
	}

	/**
	 * Dims the status bar.
	 */
	public void hideStatusbar()
	{
		contentView.setSystemUiVisibility(View.STATUS_BAR_VISIBLE);
		contentView.setSystemUiVisibility(View.STATUS_BAR_HIDDEN);
	}

	/**
	 * Kill the application. This can be used for cases where Objects in static layout files reference
	 * variables that will be nullified when the application closes - but are not reset by the VM.
	 */
	public void killProcess()
	{
		android.os.Process.killProcess(android.os.Process.myPid());
	}

	/**
	 * This method convets dp unit to equivalent device specific value in pixels.
	 *
	 * @param dp A value in dp(Device independent pixels) unit. Which we need to convert into pixels
	 * @param context Context to get resources and device specific display metrics
	 * @return A float value to represent Pixels equivalent to dp according to device
	 */
	public float convertDpToPixel(float dp)
	{
	    DisplayMetrics metrics = getResources().getDisplayMetrics();
	    float px = dp * (metrics.density/160f);
	    return px;
	}
	/**
	 * This method converts raw pixel value to device specific pixels.
	 *
	 * @param px A value in px (pixels) unit. Which we need to convert into db
	 * @param context Context to get resources and device specific display metrics
	 * @return A float value to represent db equivalent to px value
	 */
	public float convertPixelsToDp(float px){
	    DisplayMetrics metrics = getResources().getDisplayMetrics();
	    float dp = px / (metrics.density / 160f);
	    return dp;
	}

	/**
	 * Converts device raw pixels to device independent pixels
	 * @param dip
	 * @return
	 */
	public static float convertDipToPixels(float dip)
	{
		return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, self.getResources().getDisplayMetrics());
	}

	/**
	 * @return a weak reference to this Activity
	 */
	public static WeakReference<AbLEActivity> obtain()
	{
		return new WeakReference<AbLEActivity>(self);
	}
}

redpajama_set_name: RedPajamaGithub


text:
    package org.opencypher.tools.g4processors;

import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * this has the same name, but slightly different behaviour to the scala equivalent
 */
public class FailingErrorListener extends BaseErrorListener
{

    @SuppressWarnings("unused")
    private static final Logger LOGGER = LoggerFactory.getLogger(FailingErrorListener.class.getName());

    @Override
    public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine,
            String msg, RecognitionException e)
    {
        super.syntaxError(recognizer, offendingSymbol, line, charPositionInLine, msg, e);
//         existing error message will tell us what's wrong
         LOGGER.warn("Syntax error at line {}:{} with '" + offendingSymbol + "'",
         line, charPositionInLine);
         LOGGER.warn("msg: {}", msg);
        throw new IllegalArgumentException("Syntax error:", e);
    }

    // @Override
    // public void reportAmbiguity(Parser recognizer, DFA dfa, int startIndex, int
    // stopIndex, boolean exact,
    // BitSet ambigAlts, ATNConfigSet configs) {
    // super.reportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact,
    // ambigAlts, configs);
    // LOGGER.warn("ambiguity");
    // }
    //
    // @Override
    // public void reportAttemptingFullContext(Parser recognizer, DFA dfa, int
    // startIndex, int stopIndex,
    // BitSet conflictingAlts, ATNConfigSet configs) {
    // super.reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex,
    // conflictingAlts, configs);
    // LOGGER.warn("attemptingFullContext");
    // }
    //
    // @Override
    // public void reportContextSensitivity(Parser recognizer, DFA dfa, int
    // startIndex, int stopIndex, int prediction,
    // ATNConfigSet configs) {
    // super.reportContextSensitivity(recognizer, dfa, startIndex, stopIndex,
    // prediction, configs);
    // LOGGER.warn("contextSensitivity");
    // }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Head First Lounge</title>
    <link type="text/css" rel="stylesheet" href="lounge.css"
	      media="screen and (min-width: 481px)">
    <link type="text/css" rel="stylesheet" href="lounge-mobile.css"
	      media="screen and (max-width: 480px)">
    <link type="text/css" rel="stylesheet" href="lounge-print.css" media="print">

Welcome to the Head First Lounge

      The Head First Lounge is, no doubt, the biggest trendsetter in Webville.
      Stop in to sample the eclectic offering of elixirs, teas, and coffees,
      or, stay a bit longer and enjoy the multicultural culinary menu that
      combines a harmony of taste, texture, and color with the best in fresh
      and healthy ingredients.

      During your stay at the lounge, you'll enjoy a smooth mixture of
      ambient and mystic sounds, filling the lounge and adding an extra dimension
      to your dining experience. The decor surrounds you with the relaxing sentiments
      of sights from eras past. And, don't forget, the lounge offers free wireless
      access to the Internet, so bring your laptop.

      Our guarantee: at the lounge, we're committed to providing you,
      our guest, with an exceptional experience every time you visit.
      Whether you're just stopping by to check in on email over an
      elixir, or are here for an out-of-the-ordinary dinner, you'll
      find our knowledgeable service staff pay attention to every detail.
      If you're not fully satisfied, have a Blueberry Bliss Elixir on us.

      But that's not all; at night, join us in the backroom as our resident
      DJ spins a choice selection of trance and drum&bass beats across
      our spacious tiki-themed dance floor. Or just hang out in one of our
      comfy white vinyl booths at the dance bar. You can have your elixirs
      delivered from the main lounge right to the dance floor. If you've
      had enough of the beat, just head back to the lounge area to relax.
      And, no matter where you find yourself in the lounge, you'll always be
      connected with our wireless Internet access.

      Now that you've experienced the lounge virtually, isn't
      it time to check us out for real? We're located right
      in the heart of Webville, and we've created some
      detailed directions
      to get you here in record time. No reservations necessary;
      come and join us anytime.

Weekly Elixir Specials

Lemon Breeze

      The ultimate healthy drink, this elixir combines
      herbal botanicals, minerals, and vitamins with
      a twist of lemon into a smooth citrus wonder
      that will keep your immune system going all
      day and all night.

Chai Chiller

      Not your traditional chai, this elixir mixes maté
      with chai spices and adds an extra chocolate kick for
      a caffeinated taste sensation on ice.

Black Brain Brew

      Want to boost your memory?  Try our Black Brain Brew
      elixir, made with black oolong tea and just a touch
      of espresso.  Your brain will thank you for the boost.

      Join us any evening for these and all our
      other wonderful
      elixirs.

What's playing at the Lounge

      We're frequently asked about the music we play at the lounge, and no wonder,
      it's great stuff. Just for you, we keep a list here on the site, updated weekly.
      Enjoy.

Buddha Bar, Claude Challe

When It Falls, Zero 7

Earth 7, L.T.J. Bukem

Le Roi Est Mort, Vive Le Roi!, Enigma

Music for Airports, Brian Eno

      © 2012, Head First Lounge

      All trademarks and registered trademarks appearing on this site are
      the property of their respective owners.


text:
var SecureStorageProxy = {

    init: function (win, fail, args) {
        setTimeout(win, 0);
    },

    get: function (win, fail, args) {
        try {
            var service = args[0];
            var key = args[1];

            var vault = new Windows.Security.Credentials.PasswordVault();
            var passwordCredential = vault.retrieve(service, key);

            win(passwordCredential.password);
        } catch (e) {
            fail('Failure in SecureStorage.get() - ' + e.message);
        }
    },

    set: function (win, fail, args) {
        try {
            var service = args[0];
            var key = args[1];
            var value = args[2];

            // Remarks: you can only store up to ten credentials per app in the Credential Locker.
            // If you try to store more than ten credentials, you will encounter an Exception.
            // https://msdn.microsoft.com/en-us/library/windows/apps/hh701231.aspx

            var vault = new Windows.Security.Credentials.PasswordVault();
            vault.add(new Windows.Security.Credentials.PasswordCredential(
                service, key, value));

            win(key);
        } catch (e) {
            fail('Failure in SecureStorage.set() - ' + e.message);
        }
    },

    remove: function (win, fail, args) {
        try {
            var service = args[0];
            var key = args[1];

            var vault = new Windows.Security.Credentials.PasswordVault();
            var passwordCredential = vault.retrieve(service, key);

            if (passwordCredential) {
                vault.remove(passwordCredential);
            }

            win(key);
        } catch (e) {
            fail('Failure in SecureStorage.remove() - ' + e.message);
        }
    },

    keys: function (win, fail, args) {
        try {
            var service = args[0];
            var vault = new Windows.Security.Credentials.PasswordVault();
            var passwordCredentials;

            try {
                passwordCredentials = vault.findAllByResource(service);
            } catch (e) {
                passwordCredentials = [];
            }
            passwordCredentials = passwordCredentials.map(function (passwordCredential) {
                return passwordCredential.userName;
            });

            win(passwordCredentials);
        } catch (e) {
            fail('Failure in SecureStorage.keys() - ' + e.message);
        }
    },

    clear: function (win, fail, args) {
        try {
            var service = args[0];
            var vault = new Windows.Security.Credentials.PasswordVault();
            var passwordCredentials;

            try {
                passwordCredentials = vault.findAllByResource(service);
            } catch (e) {
                passwordCredentials = [];
            }
            passwordCredentials.forEach(function (passwordCredential) {
                vault.remove(passwordCredential);
            });

            win();
        } catch (e) {
            fail('Failure in SecureStorage.clear() - ' + e.message);
        }
    },
};

require("cordova/exec/proxy").add("SecureStorage", SecureStorageProxy);


text:
package com.samskivert.depot.impl;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;
import java.util.Set;

import com.google.common.base.Joiner;

import com.samskivert.depot.Exps;
import com.samskivert.depot.PersistentRecord;
import com.samskivert.depot.annotation.FullTextIndex.Configuration;
import com.samskivert.depot.annotation.FullTextIndex;
import com.samskivert.depot.clause.OrderBy;
import com.samskivert.depot.operator.FullText;
import static com.samskivert.depot.Log.log;

import com.samskivert.depot.impl.expression.DateFun.DatePart.Part;
import com.samskivert.depot.impl.expression.DateFun.DatePart;
import com.samskivert.depot.impl.expression.DateFun.DateTruncate;
import com.samskivert.depot.impl.expression.IntervalExp;
import com.samskivert.depot.impl.expression.RandomExp;
import com.samskivert.depot.impl.jdbc.DatabaseLiaison;
import com.samskivert.depot.impl.jdbc.LiaisonRegistry;

public class PostgreSQLBuilder
    extends SQLBuilder
{
    public class PGBuildVisitor extends BuildVisitor
    {
        @Override public Void visit (RandomExp randomExp) {
            _builder.append("random()");
            return null;
        }

        @Override public Void visit (IntervalExp interval) {
            _builder.append("interval '").append(interval.amount);
            _builder.append(" ").append(interval.unit).append("'");
            return null;
        }

        @Override public Void visit (FullText.Match match) {
            appendIdentifier("ftsCol_" + match.getDefinition().getName());
            _builder.append(" @@ to_tsquery('").
            append(translateFTConfig(getFTIndex(match.getDefinition()).configuration())).
            append("', ");
            bindValue(massageFTQuery(match.getDefinition()));
            _builder.append(")");
            return null;
        }

        @Override public Void visit (FullText.Rank rank) {
            _builder.append("ts_rank(");
            appendIdentifier("ftsCol_" + rank.getDefinition().getName());
            _builder.append(", to_tsquery('").
            append(translateFTConfig(getFTIndex(rank.getDefinition()).configuration())).
            // TODO: The normalization parameter is really quite important, and should
            // TODO: perhaps be configurable, but for the moment we hard-code it to 1:
            // TODO: "divides the rank by the 1 + logarithm of the document length"
            append("', ");
            bindValue(massageFTQuery(rank.getDefinition()));
            _builder.append("), 1)");
            return null;
        }

        @Override public Void visit (DatePart exp)
        {
            String datePart = "'" + translateDatePart(exp.getPart()) + "'";
            return appendFunctionCall("date_part", Exps.literal(datePart), exp.getArg());
        }

        @Override
        public Void visit (DateTruncate exp)
        {
            String field = "'" + exp.getTruncation().toString().toLowerCase() + "'";
            return appendFunctionCall("date_trunc", Exps.literal(field), exp.getArg());
        }

        protected String translateDatePart (Part part)
        {
            switch(part) {
            case DAY_OF_MONTH:
                return "day";
            case DAY_OF_WEEK:
                return "dow";
            case DAY_OF_YEAR:
                return "doy";
            case HOUR:
                return "hour";
            case MINUTE:
                return "minute";
            case MONTH:
                return "month";
            case SECOND:
                return "second";
            case WEEK:
                return "week";
            case YEAR:
                return "year";
            case EPOCH:
                return "epoch";
            }
            throw new IllegalArgumentException("Unknown date part: " + part);
        }

        protected FullTextIndex getFTIndex (FullText definition)
        {
            DepotMarshaller<?> marsh = _types.getMarshaller(definition.getPersistentClass());
            return marsh.getFullTextIndex(definition.getName());
        }

        @Override protected void appendIdentifier (String field) {
            _builder.append("\"").append(field).append("\"");
        }

        @Override protected boolean orderSupported (OrderBy.Order order)
        {
            switch (order) {
            case NULL: case ASC: case DESC: case ASC_NULLS_FIRST: case DESC_NULLS_LAST:
                return true;
            }
            return false;
        }

        protected PGBuildVisitor (DepotTypes types)
        {
            super(types, true);
        }
    }

    public PostgreSQLBuilder (DepotTypes types)
    {
        super(types);
    }

    @Override
    public void getFtsIndexes (
        Iterable<String> columns, Iterable<String> indexes, Set<String> target)
    {
        for (String column : columns) {
            if (column.startsWith("ftsCol_")) {
                target.add(column.substring("ftsCol_".length()));
            }
        }
    }

    @Override
    public <T extends PersistentRecord> boolean addFullTextSearch (
        Connection conn, DepotMarshaller<T> marshaller, FullTextIndex fts)
        throws SQLException
    {
        Class<T> pClass = marshaller.getPersistentClass();
        DatabaseLiaison liaison = LiaisonRegistry.getLiaison(conn);

        String[] fields = fts.fields();

        String table = marshaller.getTableName();
        String column = "ftsCol_" + fts.name();
        String index = table + "_ftsIx_" + fts.name();
        String trigger = table + "_ftsTrig_" + fts.name();

        // build the UPDATE
        StringBuilder initColumn = new StringBuilder("UPDATE ").
            append(liaison.tableSQL(table)).append(" SET ").append(liaison.columnSQL(column)).
            append(" = TO_TSVECTOR('").
            append(translateFTConfig(fts.configuration())).
            append("', ");

        for (int ii = 0; ii < fields.length; ii ++) {
            if (ii > 0) {
                initColumn.append(" || ' ' || ");
            }
            initColumn.append("COALESCE(").
                append(liaison.columnSQL(_types.getColumnName(pClass, fields[ii]))).
                append(", '')");
        }
        initColumn.append(")");

        // build the CREATE TRIGGER
        StringBuilder createTrigger = new StringBuilder("CREATE TRIGGER ").
            append(liaison.columnSQL(trigger)).append(" BEFORE UPDATE OR INSERT ON ").
            append(liaison.tableSQL(table)).
            append(" FOR EACH ROW EXECUTE PROCEDURE tsvector_update_trigger(").
            append(liaison.columnSQL(column)).append(", ").
            append("'").append(translateFTConfig(fts.configuration())).append("', ");

        for (int ii = 0; ii < fields.length; ii ++) {
            if (ii > 0) createTrigger.append(", ");
            createTrigger.append(liaison.columnSQL(_types.getColumnName(pClass, fields[ii])));
        }
        createTrigger.append(")");

        // build the CREATE INDEX
        StringBuilder createIndex = new StringBuilder("CREATE INDEX ").
            append(liaison.columnSQL(index)).append(" ON " ).append(liaison.tableSQL(table)).
            append(" USING GIN(").append(liaison.columnSQL(column)).append(")");

        Statement stmt = conn.createStatement();
        log.info("Adding full-text search column, index and trigger: " + column + ", " +
                 index + ", " + trigger);
        liaison.addColumn(conn, table, column, "TSVECTOR", true);
        stmt.executeUpdate(initColumn.toString());
        stmt.executeUpdate(createIndex.toString());
        stmt.executeUpdate(createTrigger.toString());
        return true;
    }

    @Override
    public boolean isPrivateColumn (String column, Map<String, FullTextIndex> fullTextIndexes)
    {
        // filter out any column that we created as part of FTS support
        for (FullTextIndex fti : fullTextIndexes.values()) {
            if (("ftsCol_" + fti.name()).equals(column)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean isPrivateIndex (String index, Map<String, FullTextIndex> fullTextIndexes)
    {
        // filter out any index that looks like PostgreSQL created it
        if (index.endsWith("_key") || index.endsWith("_pkey")) {
            return true;
        }

        // filter out any index that we created as part of FTS support
        for (FullTextIndex fti : fullTextIndexes.values()) {
            if (index.endsWith("_ftsIx_" + fti.name())) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected BuildVisitor getBuildVisitor ()
    {
        return new PGBuildVisitor(_types);
    }

    @Override
    protected <T> String getColumnType (FieldMarshaller<?> fm, int length)
    {
        return fm.getColumnType(TYPER, length);
    }

    @Override
    protected String getSerialType (Field field)
    {
        return field.getType().equals(Long.TYPE) ? "BIGSERIAL" : "SERIAL";
    }

    protected static String massageFTQuery (FullText fullText)
    {
        // The tsearch2 engine takes queries on the form
        //   (foo&bar)|goop
        // so in this implementation, we take the user query, chop it into words by and combine
        // those together depending on the value of isMatchAll(), like so:
        //   'ho! who goes there?' -> 'ho|who|goes|there' OR 'ho&who&goes&there'
        //
        String[] searchTerms = fullText.getQuery().toLowerCase().trim().split("\\W+");
        String operator = fullText.isMatchAll() ? "&" : "|";
        return Joiner.on(operator).join(searchTerms);
    }

    // Translate the mildly abstracted full-text parser/dictionary configuration support
    // in FullText to actual PostgreSQL configuration identifiers.
    protected static String translateFTConfig (Configuration configuration)
    {
        switch(configuration) {
        case Simple:
            return "pg_catalog.simple";
        case English:
            return "pg_catalog.english";
        default:
            throw new IllegalArgumentException("Unknown full text configuration: " + configuration);
        }
    }

    protected static final FieldMarshaller.ColumnTyper TYPER = new FieldMarshaller.ColumnTyper() {
        public String getBooleanType (int length) {
            return "BOOLEAN";
        }
        public String getByteType (int length) {
            return "SMALLINT";
        }
        public String getShortType (int length) {
            return "SMALLINT";
        }
        public String getIntType (int length) {
            return "INTEGER";
        }
        public String getLongType (int length) {
            return "BIGINT";
        }
        public String getFloatType (int length) {
            return "REAL";
        }
        public String getDoubleType (int length) {
            return "DOUBLE PRECISION";
        }
        public String getStringType (int length) {
            return "VARCHAR(" + length + ")";
        }
        public String getDateType (int length) {
            return "DATE";
        }
        public String getTimeType (int length) {
            return "TIME";
        }
        public String getTimestampType (int length) {
            return "TIMESTAMP";
        }
        public String getBlobType (int length) {
            return "BYTEA";
        }
        public String getClobType (int length) {
            return "TEXT";
        }
    };
}


text:
'use strict';

describe('groupByFilter', function() {
  var filter;

  beforeEach(module('a8m.group-by'));
  beforeEach(inject(function ($filter) {
    filter = $filter('groupBy');
  }));

  it('should get array as collection, property(nested to) as identifier and ' +
    'returns the composed aggregate object.', function() {

    var players = [
      {name: 'Gene', team: 'alpha'},
      {name: 'George', team: 'beta'},
      {name: 'Steve', team: 'gamma'},
      {name: 'Paula', team: 'beta'},
      {name: 'Scruath', team: 'gamma'}
    ];

    expect(filter(players, 'team')).toEqual( {
      alpha: [players[0]],
      beta: [players[1], players[3]],
      gamma: [players[2], players[4]]
    });
  });

  it('should support nested properties to', function() {
    var orders = [
      { id:10, customer: { name: 'foo', id: 1 } },
      { id:11, customer: { name: 'bar', id: 2 } },
      { id:12, customer: { name: 'foo', id: 1 } },
      { id:13, customer: { name: 'bar', id: 2 } },
      { id:14, customer: { name: 'bar', id: 3 } },
      2, null, true
    ];

    expect(filter(orders, 'customer.name')).toEqual( {
      foo: [orders[0], orders[2]],
      bar: [orders[1], orders[3], orders[4]],
      undefined: [2, null, true]
    });
  });

  it('should get object as collection, property(nested to) as identifier and ' +
    'returns the composed aggregate object.', function() {
    var dataObject = {
      0: { id: 1, data: {} },
      1: { id: 1, data: {} },
      2: { id: 2, data: {} },
      3: { id: 2, data: {} }
    };

    expect(filter(dataObject, 'id')).toEqual({
      1: [dataObject[0], dataObject[1]],
      2: [dataObject[2], dataObject[3]]
    });
  });

  it('should get !collection and return it as-is ', function() {
    expect(filter('string')).toEqual('string');
    expect(filter(1)).toEqual(1);
    expect(filter(!1)).toBeFalsy();
    expect(filter(null)).toBeNull();
  });

  describe('inside the DOM', function() {
    it('should not throw and not trigger the infinite digest exception',
      inject(function($rootScope, $compile) {
        var scope = $rootScope.$new();
        scope.players = [
          { name: 'foo', team: 'a' },
          { name: 'lol', team: 'b' },
          { name: 'bar', team: 'b' },
          { name: 'baz', team: 'a' }
        ];
        scope.search = '';
        var elm = angular.element(
          '
' +
            '
' +
              '{{ key }}' +
              '
 {{ v }}
' +
            '
' +
          '
'
        );
        var temp = $compile(elm)(scope);
        expect(function() { scope.$digest() }).not.toThrow();
        expect(temp.children().length).toEqual(2);
      }));
  });
});


text: extern const Image* const movie[];


text:
package com.microsoft.azure.management.network;

import com.fasterxml.jackson.annotation.JsonValue;

/**
 * Defines values for PcError.
 */
public final class PcError {
    /** Static value InternalError for PcError. */
    public static final PcError INTERNAL_ERROR = new PcError("InternalError");

    /** Static value AgentStopped for PcError. */
    public static final PcError AGENT_STOPPED = new PcError("AgentStopped");

    /** Static value CaptureFailed for PcError. */
    public static final PcError CAPTURE_FAILED = new PcError("CaptureFailed");

    /** Static value LocalFileFailed for PcError. */
    public static final PcError LOCAL_FILE_FAILED = new PcError("LocalFileFailed");

    /** Static value StorageFailed for PcError. */
    public static final PcError STORAGE_FAILED = new PcError("StorageFailed");

    private String value;

    /**
     * Creates a custom value for PcError.
     * @param value the custom value
     */
    public PcError(String value) {
        this.value = value;
    }

    @JsonValue
    @Override
    public String toString() {
        return value;
    }

    @Override
    public int hashCode() {
        return value.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof PcError)) {
            return false;
        }
        if (obj == this) {
            return true;
        }
        PcError rhs = (PcError) obj;
        if (value == null) {
            return rhs.value == null;
        } else {
            return value.equals(rhs.value);
        }
    }
}


text:
package circleci

import (
	"fmt"
	"net/http"
	"testing"
)

func TestClient_RecentBuilds__Unauthorized(t *testing.T) {
	startTestServer()
	defer stopTestServer()
	testMux.HandleFunc("/recent-builds", func(w http.ResponseWriter, r *http.Request) {
		checkMethod(t, r, http.MethodGet)
		w.WriteHeader(http.StatusUnauthorized)
		fmt.Fprint(w, `{"message": "You must log in first"}`)
	})
	builds, apiResp := testClient.RecentBuilds(nil)
	if apiResp.Success() {
		t.Errorf("Expected response to not be successful without token")
	}
	if apiResp.Response.StatusCode != http.StatusUnauthorized {
		t.Errorf("Expected unauthorized code but got %v", apiResp.Response.StatusCode)
	}
	if len(builds) != 0 {
		t.Errorf("Expected no builds but got %d", len(builds))
	}
}

func TestClient_RecentBuilds(t *testing.T) {
	startTestServer()
	defer stopTestServer()
	testMux.HandleFunc("/recent-builds", func(w http.ResponseWriter, r *http.Request) {
		checkMethod(t, r, http.MethodGet)
		w.WriteHeader(http.StatusOK)
		fmt.Fprint(w, `[{"build_num": 12345, "branch": "master"}]`)
	})
	builds, apiResp := testClient.RecentBuilds(nil)
	if !apiResp.Success() {
		t.Errorf("Expected a successful response with no errors")
	}
	if apiResp.Response.StatusCode != http.StatusOK {
		t.Errorf("Expected unauthorized code but got %v", apiResp.Response.StatusCode)
	}
	fmt.Printf("%v", builds)
	if len(builds) == 0 {
		t.Errorf("Expected builds but got %d", len(builds))
	}
	build := builds[0]
	if build.BuildNum != 12345 {
		t.Errorf("Expected build number to be %d but got %d", 12345, build.BuildNum)
	}
	if build.Branch != "master" {
		t.Errorf("Expected build branch to be %s but got %d", "master", build.BuildNum)
	}
}


text:
//	This code is a part of 'Common SDK' product.
//	Copyright (C) Scientific Software
//	All rights reserved.

//	File name: String.h
//	Description: Common strings macros and definitions.

#ifndef STRING_H__COMMON__INCLUDED_
#define STRING_H__COMMON__INCLUDED_

/************************************************************************

	Code notes:
		_T(x)	macro must be used to define any string expressions in the code.
		TCHAR	type must be used to declare character variables.
		String	container must be used to operate with string data.

************************************************************************/

#ifdef _T
#undef _T
#endif // _T

#ifdef _TCHAR_DEFINED
#undef _TCHAR_DEFINED
#endif // _TCHAR_DEFINED

#ifdef _UNICODE
//////////////////////////////////////////////////////////////////////////
// Declaring macros for Unicode mode /////////////////////////////////////
//////////////////////////////////////////////////////////////////////////

#ifndef _T
#define _T(x)						L ## x
#endif

#ifndef _TCHAR_DEFINED
#define _TCHAR_DEFINED

typedef wchar_t						TCHAR;

#endif // !__TCHAR_DEFINED

#else // _UNICODE
//////////////////////////////////////////////////////////////////////////
// Declaring macros for MiltiByte mode ///////////////////////////////////
//////////////////////////////////////////////////////////////////////////

#ifndef _T
#define _T(x)						x
#endif

#ifndef _TCHAR_DEFINED
#define _TCHAR_DEFINED

typedef char						TCHAR;

#endif // !__TCHAR_DEFINED

#endif // _UNICODE

#ifndef _WINNT_
// Declaring aditional string types
typedef TCHAR*						LPTSTR;
typedef const TCHAR*				LPCTSTR;

// ANSI string macros
typedef char*						LPSTR;
typedef const char*					LPCSTR;
#endif // !_WINNT_

// Declaring object model main string container
typedef basic_string<TCHAR, char_traits<TCHAR>, allocator<TCHAR> >			String;
typedef basic_string< char, char_traits<char>, allocator<char> >			StringA;
typedef basic_string< wchar_t, char_traits<wchar_t>, allocator<wchar_t> >	StringU;

#endif // !STRING_H__COMMON__INCLUDED_


text:
#ifndef ARROW_H
#define ARROW_H

#include <QGraphicsLineItem>

#include "diagramitem.h"

QT_BEGIN_NAMESPACE
class QGraphicsPolygonItem;
class QGraphicsLineItem;
class QGraphicsScene;
class QRectF;
class QGraphicsSceneMouseEvent;
class QPainterPath;
QT_END_NAMESPACE

//! [0]
class Arrow : public QGraphicsLineItem
{
public:
    enum { Type = UserType + 4 };

    Arrow(DiagramItem *startItem, DiagramItem *endItem,
      QGraphicsItem *parent = 0, QGraphicsScene *scene = 0);

    int type() const
        { return Type; }
    QRectF boundingRect() const;
    QPainterPath shape() const;
    void setColor(const QColor &color)
        { myColor = color; }
    DiagramItem *startItem() const
        { return myStartItem; }
    DiagramItem *endItem() const
        { return myEndItem; }

public slots:
    void updatePosition();

protected:
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
               QWidget *widget = 0);

private:
    DiagramItem *myStartItem;
    DiagramItem *myEndItem;
    QColor myColor;
    QPolygonF arrowHead;
};
//! [0]

#endif


text:
<app-page *ngIf="schedule$ | async as schedule; else loading">

  <app-page-head>
    <app-page-head-back [defaultUrl]="'/tasks/definitions'"></app-page-head-back>
    <app-page-head-title>Create schedule(s)</app-page-head-title>
  </app-page-head>

      Create a schedule for a task, simply provide a name and a CRON expression.

Optionally, you can add properties and arguments.

    <form class="schedule-form task-create" [formGroup]="form" name="form" (submit)="submit(schedule)">

Setup the schedule

              Task Name:

                {{ schedule.taskDefinitions[0] }}

              Schedule name:

                <input id="name" name="name" [formControl]="form.get('names').controls[0]"
                       class="form-control input-sm"/>

The name is required.

The name already exists.

 1">

              Tasks:

                Duplicate schedule name on the form.

                  Task
                  Schedule name

                  {{ item }}

                      <input [formControl]="form.get('names').controls[i]" type="text" class="form-control input-sm"/>

The name is required.

The name already exists.

            Cron Expression:

              <input id="cron" name="cron" formControlName="cron" class="form-control input-sm"/>

                The cron expression is required.
                The cron expression is not valid.

Task Arguments and Properties

              Arguments:

            <app-kv-rich-text [validators]="kvValidators.args" [formControl]="form.get('args')"
                              placeholder="--myarg=myvalue"></app-kv-rich-text>

            One or more arguments are invalid.
Example: myarg=myvalue.

              Parameters:

            <app-kv-rich-text [validators]="kvValidators.props" [formControl]="form.get('props')"
                              placeholder="app.myparam=myvalue"></app-kv-rich-text>

          One or more parameters are invalid.
Example: app.myarg=myvalue.

      <app-page-actions>
        <button (click)="cancel()" type="button" class="btn btn-default">Cancel</button>
        <button id="btn-submit" type="submit" class="btn btn-primary">Schedule the task</button>
      </app-page-actions>
    </form>

</app-page>

<ng-template #popArguments>

    Arguments can be prefixed by -- (optional).

    Example:

--myarg1=value1
--myarg2=value2

</ng-template>

<ng-template #popParameters>

    Parameters should start with an app. or deployer..

    Example:

app.myparam=value1
deployer.myparam2=value2

</ng-template>

<ng-template #loading>
  <app-loader></app-loader>
</ng-template>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Platform admin</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <link href="../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

        <form class="" role="form" id="login" action="/login">

账号登录:

                <input type="text" class="form-control" name="username" required="required" placeholder="请输入账号">

                <input type="password" class="form-control" name="password" required="required" placeholder="请输入密码">

            <button class="btn btn-lg btn-primary btn-block" type="submit">登录</button>
        </form>


text:
import * as React from 'react';
import './../../Styles/index.css';
import {
    ArticleFormState,
} from '../../Evolve/Forms/ArticleForm';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import TextField from 'material-ui/TextField';
import { baseValidatorErrorMessage } from '../../ReduxCore/Util/BaseValidators';

function ArticleForm<T>(props: {
    title: string,
    handlingComponent: T,
    formState: ArticleFormState,
    open: boolean,
    onClose: () => void,
    onSave: () => void,
    onArticleNumberChange: (e: React.FormEvent<{}>, newValue: string) => void;
    onNameChange: (e: React.FormEvent<{}>, newValue: string) => void;
    onPriceChange: (e: React.FormEvent<{}>, newValue: string) => void;
}) {
    const actions = [
        (
            <FlatButton
                label={'Abbrechen'}
                onClick={() => props.onClose()}
            />
        ),
        (
            <FlatButton
                label={'Speichern'}
                onClick={() => props.onSave()}
            />
        )
    ];
    return (
        <Dialog
            actions={actions}
            title={props.title}
            modal={true}
            open={props.open}
        >
            <TextField
                floatingLabelText={'ArtikelNummer'}
                value={props.formState.input.articleNumber}
                onChange={props.onArticleNumberChange}
                errorText={baseValidatorErrorMessage(props.formState.validation.articleNumber)}
            />

            <TextField
                floatingLabelText={'Name'}
                value={props.formState.input.name}
                onChange={props.onNameChange}
                errorText={baseValidatorErrorMessage(props.formState.validation.name)}
            />

            <TextField
                floatingLabelText={'Price'}
                value={props.formState.input.price}
                onChange={props.onPriceChange}
                errorText={baseValidatorErrorMessage(props.formState.validation.price)}
            />
        </Dialog>
    );
}

export default ArticleForm;


text:
<!DOCTYPE html>

<title>Character Test</title>
<link rel="stylesheet" type="text/css" href="characterTest.css">

5 Questions to find your soulmate!

<form>
<input id="username" type="text" value="Enter Your Username">
</form>
<form>

Question 1: What do you do for fun in your spare time?

	<input type="radio" name="q1" value="A" checked>Party and socialize

	<input type="radio" name="q1" value="B">Stay home and watch movies

	<input type="radio" name="q1" value="C">Outdoor activities

	<input type="radio" name="q1" value="D">Work, WORK IS FUN!

Question 2: What would you do if you won $10 million?

	<input type="radio" name="q2" value="A" checked>Change the World

	<input type="radio" name="q2" value="B">Save and Invest

	<input type="radio" name="q2" value="C">Travel and luxury dining

	<input type="radio" name="q2" value="D">Burning cash to keep warm

Question 3: If a friend invited you to Vegas tomorrow and you had work, would you go?

	<input type="radio" name="q3" value="A" checked>Yes! My bags are already packed!

	<input type="radio" name="q3" value="B">No, I have to work

	<input type="radio" name="q3" value="C">If I can get out of work

	<input type="radio" name="q3" value="D">Maybe

Question 4: If your house was on fire, what would you save?

<input type="radio" name="q4" value="A" checked>My important documents

<input type="radio" name="q4" value="B">My favorite photo of my family

<input type="radio" name="q4" value="C">My pets

<input type="radio" name="q4" value="D">Stash of money under my mattress

Question 5: What's in your journal?

<input type="radio" name="q5" value="A" checked>Thoughts on politics, the world, the universe

<input type="radio" name="q5" value="B">Funny things that happened, jokes

<input type="radio" name="q5" value="C">Stuff I don't share with others

<input type="radio" name="q5" value="D">I don't keep a journal

</form>
<form>
<input type="button" value="Submit your Answers" onclick="getAnswers()">
<input type="button" value="Get Results" onclick="getResults()">
</form>


text:
package com.blazebit.persistence.deltaspike.data.base.builder.postprocessor;

import com.blazebit.persistence.FullQueryBuilder;
import com.blazebit.persistence.deltaspike.data.base.handler.CriteriaBuilderQueryCreator;

import javax.persistence.Query;

/**
 * @author Christian Beikov
 * @since 1.2.0
 */
public class CountCriteriaBuilderQueryCreator implements CriteriaBuilderQueryCreator {

    @Override
    public Query createQuery(FullQueryBuilder<?, ?> queryBuilder) {
        return queryBuilder.getCountQuery();
    }
}


text:
package xal.app.orbitcorrect;

import xal.smf.*;
import xal.smf.impl.BPM;
import xal.tools.data.*;

import java.util.*;

/**
 * SnapshotOrbitSource
 * @author   tap
 * @since    Aug 23, 2004
 */
public class SnapshotOrbitSource extends OrbitSource {
	/** the Snapshot BPM record data */
	protected List<BpmRecord> _bpmRecords;

	/** orbit */
	protected Orbit _orbit;

	/**
	 * Primary Constructor
	 * @param label       Label for this orbit source.
	 * @param bpmRecords  The BPM records which define the orbit
	 * @param sequence    The sequence for which this orbit source supplies orbits.
	 * @param bpmAgents   The BPM agents to include in the Orbit.
	 */
	public SnapshotOrbitSource( final String label, final List<BpmRecord> bpmRecords, final AcceleratorSeq sequence, final List<BpmAgent> bpmAgents ) {
		super( label, sequence, bpmAgents );

		setSnapshot( bpmRecords );
	}

	/**
	 * Constructor
	 * @param label       the orbit source's label
	 * @param bpmRecords  the records from which to generate the orbit
	 */
	public SnapshotOrbitSource( final String label, final List<BpmRecord> bpmRecords ) {
		this( label, bpmRecords, null, null );
	}

	/**
	 * Constructor
	 * @param label  the orbit source's label
	 * @param orbit  the orbit from which to get the BPM records of the Snapshot orbit
	 */
	public SnapshotOrbitSource( final String label, final Orbit orbit ) {
		this( label, orbit.getRecords() );
	}

	/**
	 * Constructor
	 * @param label  the orbit source's label
	 */
	public SnapshotOrbitSource( final String label ) {
		this( label, Collections.<BpmRecord>emptyList() );
	}

    /** Create a new instance from a data adaptor */
    static public SnapshotOrbitSource getInstance( final DataAdaptor snapshotSourceAdaptor, final AcceleratorSeq sequence, final List<BpmAgent> bpmAgents ) {
        final SnapshotOrbitSource orbitSource = new SnapshotOrbitSource( "" );
        orbitSource.setSequence( sequence, bpmAgents );
        orbitSource.update( snapshotSourceAdaptor );
        return orbitSource;
    }

	/**
	 * Generate a snapshot orbit from the list of BPMs and initialized to zero displacement.
	 * @param label the orbit source's label
	 * @param bpmAgents	the bpms for which the orbit is specified
	 */
	static public SnapshotOrbitSource getInstanceWithBPMs( final String label, final List<BpmAgent> bpmAgents, final AcceleratorSeq sequence ) {
		final SnapshotOrbitSource source = new SnapshotOrbitSource( label );

		final List<BpmRecord> records = new ArrayList<BpmRecord>( bpmAgents.size() );
		for ( BpmAgent bpmAgent : bpmAgents ) {
			records.add( new BpmRecord( bpmAgent ) );
		}

		return new SnapshotOrbitSource( label, records, sequence, bpmAgents );
	}

	/**
	 * Set the sequence and its BPMs.
	 * @param sequence  the accelerator sequence which the orbit covers
	 * @param bpmAgents the list of BPM agents to monitor
	 */
	public void setSequence( final AcceleratorSeq sequence, final List<BpmAgent> bpmAgents ) {
        super.setSequence( sequence, bpmAgents );

        // perform the notification outside the state synchronization
        _proxy.sequenceChanged( this, sequence, bpmAgents );
	}

    /** Subclasses may implement this method to perform action immediately after sequence assignment */
    protected void afterSequenceAssignment( final AcceleratorSeq sequence, final List<BpmAgent> bpmAgents ) {
        generateOrbit();
    }

	/**
	 * Set the orbit snapshot data.
	 * @param bpmRecords   the BPM records of the snapshot orbit
	 */
	public void setSnapshot( final List<BpmRecord> bpmRecords ) {
		_bpmRecords = new ArrayList<BpmRecord>( bpmRecords );
		generateOrbit();
	}

	/**
	 * Set the orbit snapshot data.
	 * @param orbit   the orbit to snapshot
	 */
	public void setSnapshot( final Orbit orbit ) {
		setSnapshot( orbit.getRecords() );
	}

	/**
	 * Get the latest orbit.
	 * @return   the latest orbit.
	 */
	public Orbit getOrbit() {
        synchronized ( STATE_LOCK ) {
            return _orbit;
        }
	}

	/** Generate a new orbit from the BPM records for the specified sequence.  */
	protected void generateOrbit() {
		final MutableOrbit orbit = new MutableOrbit( _sequence );

		if ( ( _sequence != null ) && ( _bpmAgents != null ) && ( _bpmRecords != null ) ) {
			// since BPM agents may be different we need to get the records which match the BPMs
			final Map<BPM,BpmAgent> bpmAgentTable = new HashMap<BPM,BpmAgent>( _bpmAgents.size() );
			for ( final BpmAgent bpmAgent : _bpmAgents ) {
				bpmAgentTable.put( bpmAgent.getBPM(), bpmAgent );
			}

			for ( final BpmRecord record : _bpmRecords ) {
				final BpmAgent bpmAgent = bpmAgentTable.get( record.getBpmAgent().getBPM() );
				if ( bpmAgent != null ) {
					orbit.addRecord( record );
				}
			}
		}

		_orbit = orbit.getOrbit();
		_proxy.orbitChanged( this, _orbit );
	}

    /**
	 * Update the data based on the information provided by the data provider.
     * @param adaptor The adaptor from which to update the data
     */
    public void update( final DataAdaptor adaptor ) {
		super.update( adaptor );

		final Map<String,BpmAgent> bpmAgents = new HashMap<String,BpmAgent>( _bpmAgents.size() );
		for ( BpmAgent bpmAgent : _bpmAgents ) {
			bpmAgents.put( bpmAgent.getID(), bpmAgent );
		}

		final List<DataAdaptor> recordAdaptors = adaptor.childAdaptors( BpmRecord.DATA_LABEL );
		final List<BpmRecord> records = new ArrayList<BpmRecord>( recordAdaptors.size() );
		for ( DataAdaptor recordAdaptor : recordAdaptors ) {
			final BpmAgent bpmAgent = bpmAgents.get( recordAdaptor.stringValue( "BPM" ) );
			if ( bpmAgent != null ) {
				final BpmRecord record = new BpmRecord( bpmAgent );
				record.update( recordAdaptor );
				records.add( record );
			}
		}
		setSnapshot( records );
	}

    /**
	 * Write data to the data adaptor for storage.
     * @param adaptor The adaptor to which the receiver's data is written
     */
    public void write( final DataAdaptor adaptor ) {
		adaptor.setValue( "type", "snapshot" );
		super.write( adaptor );
		adaptor.writeNodes( _bpmRecords );
	}
}


text:
qc::schedule_start
==================

part of [Docs](../index.md)

Usage
-----
`qc::schedule_start proc_name`

Description
-----------
Start schedule

----------------------------------
*[Qcode Software Limited] [qcode]*

[qcode]: http://www.qcode.co.uk "Qcode Software"


text:
require 'helper'

describe Guh::Plugin do

  it "should return a list of all loaded plugins" do
    response = Guh::Plugin.all

    response.should be_an_instance_of(Array)
  end

  it "should add params to the Plugin config" do
    pending("Implement after difference between PluginConfig & PluginParams is clear")
  end

end