text:
from __future__ import print_function

import abc
import copy
import functools
import hashlib
import os
import pathlib2

from verta.external import six
from verta import _blob

from .._protos.public.modeldb.versioning import Dataset_pb2 as _DatasetService

from .._internal_utils import (
    _file_utils,
    _request_utils,
    _utils,
)

DEFAULT_DOWNLOAD_DIR = "mdb-data-download"  # to be in cwd

class _Dataset(_blob.Blob):
    """
    Base class for dataset versioning. Not for human consumption.

    """
    _CANNOT_DOWNLOAD_ERROR = RuntimeError(
        "this dataset cannot be used for downloads;"
        " consider using `dataset_version.get_content()"
        " to obtain a download-capable dataset"
        " if ModelDB-managed versioning was enabled"
    )

    def __init__(self, paths=None, enable_mdb_versioning=False):
        super(_Dataset, self).__init__()

        self._components_map = dict()  # paths to Component objects

        self._mdb_versioned = enable_mdb_versioning

        # to enable download() with ModelDB-managed versioning
        # using dataset_version.get_content()
        self._dataset_version = None

    def __repr__(self):
        lines = ["{} Version".format(self.__class__.__name__)]

        components = self._components_map.values()
        components = sorted(components, key=lambda component: component.path)
        for component in components:
            lines.extend(repr(component).splitlines())

        return "\n    ".join(lines)

    def __add__(self, other):
        if not isinstance(other, type(self)):
            return NotImplemented

        new = copy.deepcopy(self)
        return new.__iadd__(other)

    def __iadd__(self, other):
        if not isinstance(other, type(self)):
            return NotImplemented

        self_keys = set(self._components_map.keys())
        other_keys = set(other._components_map.keys())
        intersection = list(self_keys & other_keys)
        if intersection:
            raise ValueError("dataset already contains paths: {}".format(intersection))

        if self._mdb_versioned != other._mdb_versioned:
            raise ValueError("datasets must have same value for `enable_mdb_versioning`")

        self._add_components(other._components_map.values())
        return self

    @classmethod
    def _create_empty(cls):
        return cls([])

    def _add_components(self, components):
        self._components_map.update({
            component.path: component
            for component
            in components
        })

    @abc.abstractmethod
    def _prepare_components_to_upload(self):
        pass

    @abc.abstractmethod
    def _clean_up_uploaded_components(self):
        pass

    def _set_dataset_version(self, dataset_version):
        """
        Associate this blob with a dataset version to enable downloads.

        Parameters
        ----------
        dataset_version : :class:`~verta.dataset.entities.DatasetVersion`
            Dataset version this blob was gotten from.

        """
        self._dataset_version = dataset_version

    @property
    def _is_downloadable(self):
        """
        Whether this has a linked dataset version to download from.

        """
        if self._dataset_version:
            return True
        else:
            return False

    @property
    def _conn(self):
        """
        Co-opts the ``_conn`` from associated dataset version.

        """
        if self._dataset_version:
            return self._dataset_version._conn
        else:
            raise self._CANNOT_DOWNLOAD_ERROR

    def _get_url_for_artifact(self, path, method):
        if self._dataset_version:
            return self._dataset_version._get_url_for_artifact(path, method)
        else:
            raise self._CANNOT_DOWNLOAD_ERROR

    # TODO: there is too much happening in this method's body
    def _get_components_to_download(self, component_path=None, download_to_path=None):
        """
        Identify components to be downloaded, along with their local destination paths.

        Parameters
        ----------
        component_path : str, optional
            Path to directory or file within blob.
        download_to_path : str, optional
            Local path to download to.

        Returns
        -------
        components_to_download : dict
            Map of component paths to local destination paths.
        downloaded_to_path : str
            Absolute path where file(s) were downloaded to. Matches `download_to_path` if it was
            provided as an argument.

        """
        implicit_download_to_path = download_to_path is None

        if component_path is not None:
            # look for an exact match with `component_path` as a file
            for path in self.list_paths():
                if path == component_path:
                    if implicit_download_to_path:
                        # default to filename from `component_path`, in cwd
                        local_path = os.path.basename(component_path)

                        # avoid collision with existing file
                        local_path = _file_utils.without_collision(local_path)
                    else:
                        # exactly where the user requests
                        local_path = download_to_path

                    return ({path: local_path}, os.path.abspath(local_path))
        # no exact match, so it's a folder download (or nonexistent path)

        # figure out where files are going to be downloaded to
        if implicit_download_to_path:
            if component_path is None:
                downloaded_to_path = DEFAULT_DOWNLOAD_DIR

                # avoid collision with existing directory
                downloaded_to_path = _file_utils.without_collision(downloaded_to_path)
            else:  # need to automatically determine directory
                # NOTE: if `component_path` == "s3://" with any trailing slashes, it becomes "s3:"
                downloaded_to_path = pathlib2.Path(component_path).name  # final path component

                if downloaded_to_path in {".", "..", "/", "s3:"}:
                    # rather than dump everything into cwd, use new child dir
                    downloaded_to_path = DEFAULT_DOWNLOAD_DIR

                # avoid collision with existing directory
                downloaded_to_path = _file_utils.without_collision(downloaded_to_path)
        else:
            # exactly where the user requests
            downloaded_to_path = download_to_path

        # collect paths in blob and map them to download locations
        components_to_download = dict()
        if component_path is None:
            # download all
            for path in self.list_paths():
                local_path = os.path.join(
                    downloaded_to_path,
                    _file_utils.remove_prefix_dir(path, "s3:"),
                )

                components_to_download[path] = local_path
        else:
            # look for files contained in `component_path` as a directory
            component_path_as_dir = component_path if component_path.endswith('/') else component_path+'/'
            for path in self.list_paths():
                if path.startswith(component_path_as_dir):
                    # rebase from `component_path` onto `downloaded_to_path`
                    #     Implicit `download_to_path` example:
                    #         component_blob.path = "coworker/downloads/data/info.csv"
                    #         component_path      = "coworker/downloads"
                    #         downloaded_to_path  =          "downloads" or "downloads 1", etc.
                    #         local_path          =          "downloads/data/info.csv"
                    #     Explicit `download_to_path` example:
                    #         component_blob.path = "coworker/downloads/data/info.csv"
                    #         component_path      = "coworker/downloads"
                    #         downloaded_to_path  =            "my-data"
                    #         local_path          =            "my-data/data/info.csv"
                    local_path = os.path.join(
                        downloaded_to_path,
                        _file_utils.remove_prefix_dir(path, prefix_dir=component_path),
                    )

                    components_to_download[path] = local_path

        if not components_to_download:
            raise KeyError("no components found for path {}".format(component_path))

        return (components_to_download, os.path.abspath(downloaded_to_path))

    @staticmethod
    def _is_hidden_to_spark(path):
        # PySpark ignores certain files and raises a "does not exist" error
        # https://stackoverflow.com/a/38479545
        return os.path.basename(path).startswith(('_', '.'))

    @classmethod
    def with_spark(cls, sc, paths):
        """
        Creates a dataset blob with a SparkContext instance.

        Parameters
        ----------
        sc : pyspark.SparkContext
            SparkContext instance.
        paths : list of strs
            List of paths to binary input data file(s).

        Returns
        -------
        dataset : :mod:`~verta.dataset`
            Dataset blob capturing the metadata of the binary files.

        """
        if isinstance(paths, six.string_types):
            paths = [paths]

        rdds = list(map(sc.binaryFiles, paths))
        rdd = functools.reduce(lambda a,b: a.union(b), rdds)

        def get_component(entry):
            filepath, content = entry
            return Component(
                path=filepath,
                size=len(content),
                # last_modified=metadata['modificationTime'], # handle timezone?
                md5=hashlib.md5(content).hexdigest(),
            )

        result = rdd.map(get_component)
        result = result.collect()
        obj = cls._create_empty()
        obj._add_components(result)
        return obj

    @abc.abstractmethod
    def add(self, paths):
        pass

    def download(self, component_path=None, download_to_path=None):
        """
        Downloads `component_path` from this dataset if ModelDB-managed versioning was enabled.

        Parameters
        ----------
        component_path : str, optional
            Original path of the file or directory in this dataset to download. If not provided,
            all files will be downloaded.
        download_to_path : str, optional
            Path to download to. If not provided, the file(s) will be downloaded into a new path in
            the current directory. If provided and the path already exists, it will be overwritten.

        Returns
        -------
        downloaded_to_path : str
            Absolute path where file(s) were downloaded to. Matches `download_to_path` if it was
            provided as an argument.

        """
        if not self._is_downloadable:
            raise self._CANNOT_DOWNLOAD_ERROR

        implicit_download_to_path = download_to_path is None

        components_to_download, downloaded_to_path = self._get_components_to_download(
            component_path,
            download_to_path,
        )
        for path in components_to_download:  # component paths
            local_path = components_to_download[path]  # dict will be updated near end of iteration

            # create parent dirs
            pathlib2.Path(local_path).parent.mkdir(parents=True, exist_ok=True)
            # TODO: clean up empty parent dirs if something later fails

            url = self._get_url_for_artifact(path, "GET").url

            # stream download to avoid overwhelming memory
            with _utils.make_request("GET", url, self._conn, stream=True) as response:
                _utils.raise_for_http_error(response)

                print("downloading {} from ModelDB".format(path))
                if (implicit_download_to_path
                        and len(components_to_download) == 1):  # single file download
                    # update `downloaded_to_path` in case changed to avoid overwrite
                    downloaded_to_path = _request_utils.download_file(response, local_path, overwrite_ok=False)
                else:
                    # don't update `downloaded_to_path` here because we are either downloading:
                    #     - single file with an explicit destination, so `local_path` won't change
                    #     - directory, so individual path's `local_path` isn't important
                    _request_utils.download_file(response, local_path, overwrite_ok=True)

        return os.path.abspath(downloaded_to_path)

    def list_paths(self):
        """
        Returns the paths of all components in this dataset.

        Returns
        -------
        component_paths : list of str
            Paths of all components.

        """
        return list(sorted(
            component.path
            for component
            in self._components_map.values()
        ))

    def list_components(self):
        """
        Returns the components in this dataset.

        Returns
        -------
        components : list of :class:`~verta.dataset.Component`
            Components.

        """
        components = self._components_map.values()
        return list(sorted(components, key=lambda component: component.path))

class Component(object):
    """
    A dataset component returned by ``dataset.list_components()``.

    Attributes
    ----------
    path : str
        File path.
    base_path : str
        Prefix of `path`.
    size : int
        File size.
    last_modified : int
        Unix time when this file was last modified.
    sha256 : str
        SHA-256 checksum.
    md5 : str
        MD5 checksum.

    """
    def __init__(
            self,
            path, size=None, last_modified=None,
            sha256=None, md5=None,
            base_path=None,
            internal_versioned_path=None, local_path=None):
        # metadata
        self.path = path
        self.size = size
        self.last_modified = last_modified

        # checksums
        self.sha256 = sha256
        self.md5 = md5

        # base path
        self.base_path = base_path

        # ModelDB versioning
        self._internal_versioned_path = internal_versioned_path
        self._local_path = local_path

    def __repr__(self):
        lines = [self.path]

        if self.base_path:
            lines.append("base path: {}".format(self.base_path))
        if self.size:
            lines.append("{} bytes".format(self.size))
        if self.last_modified:
            lines.append("last modified: {}".format(_utils.timestamp_to_str(self.last_modified)))
        if self.sha256:
            lines.append("SHA-256 checksum: {}".format(self.sha256))
        if self.md5:
            lines.append("MD5 checksum: {}".format(self.md5))

        return "\n    ".join(lines)

    def __eq__(self, other):
        if not isinstance(other, type(self)):
            return NotImplemented

        return self.__dict__ == other.__dict__

    @classmethod
    def _from_proto(cls, component_msg):
        return cls(
            path=component_msg.path,
            size=component_msg.size or None,
            last_modified=component_msg.last_modified_at_source or None,
            sha256=component_msg.sha256 or None,
            md5=component_msg.md5 or None,
            internal_versioned_path=component_msg.internal_versioned_path or None,
            base_path=component_msg.base_path,
        )

    def _as_proto(self):
        return _DatasetService.PathDatasetComponentBlob(
            path=self.path or "",
            size=self.size or 0,
            last_modified_at_source=self.last_modified or 0,
            sha256=self.sha256 or "",
            md5=self.md5 or "",
            internal_versioned_path=self._internal_versioned_path or "",
            base_path=self.base_path or "",
        )

class S3Component(Component):
    def __init__(self, s3_version_id=None, **kwargs):
        super(S3Component, self).__init__(**kwargs)

        # S3 versioning
        self.s3_version_id = s3_version_id

    def __repr__(self):
        repr_str = super(S3Component, self).__repr__()
        lines = repr_str.split("\n    ")

        if self.s3_version_id:
            lines.append("S3 version ID: {}".format(self.s3_version_id))

        return "\n    ".join(lines)

    @classmethod
    def _from_proto(cls, s3_component_msg):
        obj = super(S3Component, cls)._from_proto(s3_component_msg.path)
        obj.s3_version_id = s3_component_msg.s3_version_id

        return obj

    def _as_proto(self):
        s3_component_msg = _DatasetService.S3DatasetComponentBlob()
        s3_component_msg.path.CopyFrom(super(S3Component, self)._as_proto())
        s3_component_msg.s3_version_id = self.s3_version_id or ""

        return s3_component_msg


text:
ushort WIDTH_RES;
ushort HEIGHT_RES;

typedef struct ori_color24
{
    uchar b;
    uchar g;
    uchar r;
} color24;

typedef struct ori_color32
{
    color24 c;
    uchar a;    //0: totally intransparent
} color32;

color24 rgb(uchar r,uchar g,uchar b);
color32 rgba(uchar r, uchar g, uchar b, uchar a);

color24 mingle(color24 c1, color32 c2);

void initGraphMode();   //Invoke it before anyother graphbase function.
void setPixelColor(uint x, uint y,color24 color);
color24 getPixelColor(uint x, uint y);
void setRangeColor(color24 *src, uint len, uint x, uint y);
void sync();

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:id="@+id/activity_main"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:paddingBottom="@dimen/activity_vertical_margin"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="@dimen/activity_vertical_margin"
                tools:context="com.transfar.smarttool.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <Button
            android:id="@+id/btn_enter"
            android:text="进入SDK"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <Button
            android:id="@+id/btn_half"
            android:text="部分遮盖"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <Button
            android:id="@+id/btn_all"
            android:text="全部遮盖"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <Button
            android:id="@+id/btn_throw_exception"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="抛出异常"/>
        <Button
            android:id="@+id/btn_network"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="发送网络请求"
            />
    </LinearLayout>
</RelativeLayout>


text:
<?php
/* @var $this MstMatakuliahController */
/* @var $data MstMatakuliah */
?>

	<?php echo CHtml::encode($data->getAttributeLabel('id')); ?>:
	<?php echo CHtml::link(CHtml::encode($data->id), array('view', 'id'=>$data->id)); ?>

	<?php echo CHtml::encode($data->getAttributeLabel('matakuliah')); ?>:
	<?php echo CHtml::encode($data->matakuliah); ?>

	<?php echo CHtml::encode($data->getAttributeLabel('sks')); ?>:
	<?php echo CHtml::encode($data->sks); ?>

	<?php echo CHtml::encode($data->getAttributeLabel('semester')); ?>:
	<?php echo CHtml::encode($data->semester); ?>

	<?php echo CHtml::encode($data->getAttributeLabel('jenis')); ?>:
	<?php echo CHtml::encode($data->jenis); ?>


text:
package util.log;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;

public class MyLogger{

	final public static String DEBUG = "DEBUG";
	final public static String INFO = "INFO";
	final public static String TRACE = "TRACE";
	final public static String ERROR = "ERROR";
	final public static String ALL = "ALL";

	final public static int OS_Err = 0x01;
	final public static int OS_OUT = 0x02;
	final public static int OS_FILE = 0x03;

	private Marker markerFilter;
	private int outputStyle;
	public Logger coreLogger; // logger for implement of my logger

	public MyLogger(String loggerName) {

		this.coreLogger = LoggerFactory.getLogger(loggerName);
		this.outputStyle = OS_Err;
		markerFilter = null;
	}

	public MyLogger(Class<?> loggerName) {
		this.coreLogger = LoggerFactory.getLogger(loggerName);
		this.outputStyle = OS_Err;
		markerFilter = null;
	}

	public MyLogger(String loggerName, Marker filter) {
		this(loggerName);
		this.markerFilter = filter;

	}

	public MyLogger(Class<?> loggerName, Marker filter) {
		this(loggerName);
		this.markerFilter = filter;
	}

	public void setMarkerFilter(Marker filter) {
		this.markerFilter = filter;
	}

	public void setOutputStyle(int style) {
		this.outputStyle = style;
	}

	public void debug(String log) {

		switch (outputStyle) {
		case OS_Err:
			this.coreLogger.debug(log);
			break;
		case OS_OUT:
			// non-implement
			System.out.println("not implemented");
			break;
		case OS_FILE:
			// non-implement
			System.out.println("not implemented");
			break;

		default:
			break;
		}
	}

	public void debug(Marker marker, String log) {
		if (this.markerFilter == null)
			debug(log);
		else if (this.markerFilter.contains(marker))
			debug(log);
	}

	public void info(String log) {
		switch (outputStyle) {
		case OS_Err:
			this.coreLogger.info(log);
			break;
		case OS_OUT:
			// non-implement
			System.out.println("not implemented");
			break;
		case OS_FILE:
			// non-implement
			System.out.println("not implemented");
			break;

		default:
			break;
		}
	}

	public void info(Marker marker, String log) {
		if (this.markerFilter == null)
			info(log);
		else if (this.markerFilter.contains(marker))
			info(log);

	}

	public void error(String log) {
		switch (outputStyle) {
		case OS_Err:
			this.coreLogger.error(log);
			break;
		case OS_OUT:
			// non-implement
			System.out.println("not implemented");
			break;
		case OS_FILE:
			// non-implement
			System.out.println("not implemented");
			break;

		default:
			break;
		}
	}

	public void error(Marker marker, String log) {
		if (this.markerFilter == null)
			error(log);
		else if (this.markerFilter.contains(marker))
			error(log);

	}

	public void trace(String log) {
		switch (outputStyle) {
		case OS_Err:
			this.coreLogger.trace(log);
			break;
		case OS_OUT:
			// non-implement
			System.out.println("not implemented");
			break;
		case OS_FILE:
			// non-implement
			System.out.println("not implemented");
			break;

		default:
			break;
		}
	}

	public void trace(Marker marker, String log) {
		if (this.markerFilter == null)
			trace(log);
		else if (this.markerFilter.contains(marker))
			trace(log);

	}

	public static void setLevel(String level){
		String l = level;
		if(level == MyLogger.ALL) l = MyLogger.TRACE;
		System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, l);

	}

	public static void main(String[] args){
		MyLogger.setLevel(MyLogger.ALL);
		MyLogger logger = new MyLogger("test");
		logger.debug("test");
		logger.info("test");
	}

}


text:
File: 		conf.lua
Author: 	Daniel "lytedev" Flanagan
Website:	http://dmf.me

Sets the default configuration values for the LOVE2D framework
Defines the main loop of our LOVE application
Contains various helper functions

-- TODO: Global helper functions are a silly idea. Should consider putting them
-- at least in some kind of "namespace" or object somewhere.

]]--

function love.conf(t)
    --
    io.stdout:setvbuf("no")

    -- Create a global variable "config" for direct access to these variables
	config = t

    -- Change these to fit your game
	t.title = "LOVE2D Boilerplate"
	t.author = "Author Name"
	t.url = "http://lytedev.com/love2d-boilerplate"
	t.identity = "love2d_boilerplate"

	-- Unrelated to this boilerplate's in-game console - see conf.lua documentation
    t.console = false

    -- Game Version
	t.titleVersion = "0.2.0"

    -- Required LOVE Version
	t.version = "0.9.1"

    -- http://semver.org

    -- Graphics and display settings
    t.window.title = t.title .. " " .. t.titleVersion
    t.window.icon = nil
    t.window.width = 640
    t.window.height = 360
    t.window.borderless = false
    t.window.resizable = false
    t.window.minwidth = 320
    t.window.minheight = 180
    t.window.fullscreen = false
    t.window.fullscreentype = "normal"
    t.window.vsync = true
    t.window.fsaa = 0
    t.window.display = 1

    -- LOVE modules
    t.modules.audio = true
    t.modules.event = true
    t.modules.graphics = true
    t.modules.image = true
    t.modules.joystick = true
    t.modules.keyboard = true
    t.modules.math = true
    t.modules.mouse = true
    t.modules.physics = true
    t.modules.sound = true
    t.modules.system = true
    t.modules.timer = true
    t.modules.window = true
    t.modules.thread = true

    -- Network updates per second
	t.networkUPS = 10

    -- To hold custom settings
	t.settings = {}
end

-- Our main loop
function love.run()
    if love.math then
        love.math.setRandomSeed(os.time())
    end

    if love.event then
        love.event.pump()
    end

    if love.load then love.load(arg) end

    if love.timer then love.timer.step() end

    local dt = 0

    while true do
        if love.event then
            love.event.pump()
            for e,a,b,c,d in love.event.poll() do
                if e == "quit" then
                    if not love.quit or not love.quit() then
                        if love.audio then
                            love.audio.stop()
                        end
                        return
                    end
                end
                love.handlers[e](a,b,c,d)
            end
        end

        if love.timer then
            love.timer.step()
            dt = love.timer.getDelta()
        end

        if love.update then love.update(dt) end

        if love.window and love.graphics and love.window.isCreated() then
            love.graphics.clear()
            love.graphics.origin()
            if love.draw then love.draw() end
            love.graphics.present()
        end

        if love.timer then love.timer.sleep(0.001) end
    end
end

-- Helper functions

-- Credit for the next two functions:
-- http://stackoverflow.com/questions/5241799/lua-dealing-with-non-ascii-byte-streams-byteorder-change/5244306#5244306
function bytes_to_int(str, endian, signed)
    local t = {str:byte(1, -1)}
    if endian == "big" then --reverse bytes
        local tt = {}
        for k = 1, #t do
            tt[#t - k + 1] = t[k]
        end
        t = tt
    end
    local n = 0
    for k = 1, #t do
        n = n + t[k] * 2 ^ ((k - 1) * 8)
    end
    if signed then
        n = (n > 2 ^ (#t - 1) -1) and (n - 2 ^ #t) or n -- if last bit set, negative.
    end
    return n
end

function int_to_bytes(num, endian, signed)
    if num < 0 and not signed then num = -num end
    local res = {}
    local n = math.ceil(select(2, math.frexp(num)) / 8)
    if signed and num < 0 then
        num = num + 2 ^ n
    end
    for k = n, 1, -1 do -- 256 = 2^8 bits per char.
        local mul = 2 ^ (8 * (k - 1))
        res[k] = math.floor(num / mul)
        num = num - res[k] * mul
    end
    assert(num == 0)
    if endian == "big" then
        local t = {}
        for k = 1, n do
            t[k] = res[n - k + 1]
        end
        res = t
    end
    return string.char(unpack(res))
end

function string.trim(str)
    return string.match(str, '^%s*(.-)%s*$') or ''
end

function string.insert(str, s2, i)
	local i = i or string.len(str)
	local s = string.sub(str, 1, i) .. tostring(s2) .. string.sub(str, i + 1, string.len(str))
	return s
end

function string_bytes(str, sep)
    local sep = sep or " "
	local dstr = {string.byte(str, 1, string.len(str))}
	s = ""
	for i = 1, #dstr, 1 do
		s = s .. tostring(dstr[i]) .. sep
	end
	return s
end

-- For running files or strings through the interpreter/console
function dofile(file, name)
	local ok, chunk = pcall(love.filesystem.load, file)
	if not ok then
		print("Error: " .. tostring(chunk))
	else
		local result
		ok, result = pcall(chunk)
		if not ok then
			print("Error: " .. tostring(result))
		else
			-- print("Console: " .. tostring(result))
			-- Scripts do not have a result printed
		end
	end
end

function dostring(str)
	local ok, f, e = pcall(loadstring, str)
	if not ok then
		print("Error: " .. tostring(f))
	else
		local result
		ok, result = pcall(f)
		if not ok then
			print("Error: " .. tostring(result))
		else
			print("Console: " .. tostring(result))
		end
	end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">android-observable-list-example-v4</string>

</resources>


text:
namespace mojo {
namespace test {

TEST(UnionTest, PlainOldDataGetterSetter) {
  PodUnionPtr pod(PodUnion::New());

  pod->set_f_int8(10);
  EXPECT_EQ(10, pod->get_f_int8());
  EXPECT_TRUE(pod->is_f_int8());
  EXPECT_FALSE(pod->is_f_int8_other());
  EXPECT_EQ(pod->which(), PodUnion::Tag::F_INT8);

  pod->set_f_uint8(11);
  EXPECT_EQ(11, pod->get_f_uint8());
  EXPECT_TRUE(pod->is_f_uint8());
  EXPECT_FALSE(pod->is_f_int8());
  EXPECT_EQ(pod->which(), PodUnion::Tag::F_UINT8);

  pod->set_f_int16(12);
  EXPECT_EQ(12, pod->get_f_int16());
  EXPECT_TRUE(pod->is_f_int16());
  EXPECT_EQ(pod->which(), PodUnion::Tag::F_INT16);

  pod->set_f_uint16(13);
  EXPECT_EQ(13, pod->get_f_uint16());
  EXPECT_TRUE(pod->is_f_uint16());
  EXPECT_EQ(pod->which(), PodUnion::Tag::F_UINT16);

  pod->set_f_int32(14);
  EXPECT_EQ(14, pod->get_f_int32());
  EXPECT_TRUE(pod->is_f_int32());
  EXPECT_EQ(pod->which(), PodUnion::Tag::F_INT32);

  pod->set_f_uint32(static_cast<uint32_t>(15));
  EXPECT_EQ(static_cast<uint32_t>(15), pod->get_f_uint32());
  EXPECT_TRUE(pod->is_f_uint32());
  EXPECT_EQ(pod->which(), PodUnion::Tag::F_UINT32);

  pod->set_f_int64(16);
  EXPECT_EQ(16, pod->get_f_int64());
  EXPECT_TRUE(pod->is_f_int64());
  EXPECT_EQ(pod->which(), PodUnion::Tag::F_INT64);

  pod->set_f_uint64(static_cast<uint64_t>(17));
  EXPECT_EQ(static_cast<uint64_t>(17), pod->get_f_uint64());
  EXPECT_TRUE(pod->is_f_uint64());
  EXPECT_EQ(pod->which(), PodUnion::Tag::F_UINT64);

  pod->set_f_float(1.5);
  EXPECT_EQ(1.5, pod->get_f_float());
  EXPECT_TRUE(pod->is_f_float());
  EXPECT_EQ(pod->which(), PodUnion::Tag::F_FLOAT);

  pod->set_f_double(1.9);
  EXPECT_EQ(1.9, pod->get_f_double());
  EXPECT_TRUE(pod->is_f_double());
  EXPECT_EQ(pod->which(), PodUnion::Tag::F_DOUBLE);

  pod->set_f_bool(true);
  EXPECT_TRUE(pod->get_f_bool());
  pod->set_f_bool(false);
  EXPECT_FALSE(pod->get_f_bool());
  EXPECT_TRUE(pod->is_f_bool());
  EXPECT_EQ(pod->which(), PodUnion::Tag::F_BOOL);

  pod->set_f_enum(AN_ENUM_SECOND);
  EXPECT_EQ(AN_ENUM_SECOND, pod->get_f_enum());
  EXPECT_TRUE(pod->is_f_enum());
  EXPECT_EQ(pod->which(), PodUnion::Tag::F_ENUM);
}

TEST(UnionTest, PodEquals) {
  PodUnionPtr pod1(PodUnion::New());
  PodUnionPtr pod2(PodUnion::New());

  pod1->set_f_int8(10);
  pod2->set_f_int8(10);
  EXPECT_TRUE(pod1.Equals(pod2));

  pod2->set_f_int8(11);
  EXPECT_FALSE(pod1.Equals(pod2));

  pod2->set_f_int8_other(10);
  EXPECT_FALSE(pod1.Equals(pod2));
}

TEST(UnionTest, PodClone) {
  PodUnionPtr pod(PodUnion::New());
  pod->set_f_int8(10);

  PodUnionPtr pod_clone = pod.Clone();
  EXPECT_EQ(10, pod_clone->get_f_int8());
  EXPECT_TRUE(pod_clone->is_f_int8());
  EXPECT_EQ(pod_clone->which(), PodUnion::Tag::F_INT8);
}

TEST(UnionTest, PodSerialization) {
  PodUnionPtr pod1(PodUnion::New());
  pod1->set_f_int8(10);

  size_t size = GetSerializedSize_(pod1, false);
  EXPECT_EQ(16U, size);

  mojo::internal::FixedBufferForTesting buf(size);
  internal::PodUnion_Data* data = nullptr;
  SerializeUnion_(std::move(pod1), &buf, &data, false);

  PodUnionPtr pod2;
  Deserialize_(data, &pod2, nullptr);

  EXPECT_EQ(10, pod2->get_f_int8());
  EXPECT_TRUE(pod2->is_f_int8());
  EXPECT_EQ(pod2->which(), PodUnion::Tag::F_INT8);
}

TEST(UnionTest, EnumSerialization) {
  PodUnionPtr pod1(PodUnion::New());
  pod1->set_f_enum(AN_ENUM_SECOND);

  size_t size = GetSerializedSize_(pod1, false);
  EXPECT_EQ(16U, size);

  mojo::internal::FixedBufferForTesting buf(size);
  internal::PodUnion_Data* data = nullptr;
  SerializeUnion_(std::move(pod1), &buf, &data, false);

  PodUnionPtr pod2;
  Deserialize_(data, &pod2, nullptr);

  EXPECT_EQ(AN_ENUM_SECOND, pod2->get_f_enum());
  EXPECT_TRUE(pod2->is_f_enum());
  EXPECT_EQ(pod2->which(), PodUnion::Tag::F_ENUM);
}

TEST(UnionTest, PodValidation) {
  PodUnionPtr pod(PodUnion::New());
  pod->set_f_int8(10);

  size_t size = GetSerializedSize_(pod, false);
  EXPECT_EQ(16U, size);

  mojo::internal::FixedBufferForTesting buf(size);
  internal::PodUnion_Data* data = nullptr;
  SerializeUnion_(std::move(pod), &buf, &data, false);
  std::vector<Handle> handles;
  data->EncodePointersAndHandles(&handles);
  EXPECT_TRUE(handles.empty());

  void* raw_buf = buf.Leak();
  mojo::internal::BoundsChecker bounds_checker(data,
                                               static_cast<uint32_t>(size), 0);
  EXPECT_TRUE(
      internal::PodUnion_Data::Validate(raw_buf, &bounds_checker, false));
  free(raw_buf);
}

TEST(UnionTest, SerializeNotNull) {
  PodUnionPtr pod(PodUnion::New());
  pod->set_f_int8(0);
  size_t size = GetSerializedSize_(pod, false);
  mojo::internal::FixedBufferForTesting buf(size);
  internal::PodUnion_Data* data = nullptr;
  SerializeUnion_(std::move(pod), &buf, &data, false);
  EXPECT_FALSE(data->is_null());
}

TEST(UnionTest, SerializeIsNullInlined) {
  PodUnionPtr pod;
  size_t size = GetSerializedSize_(pod, false);
  EXPECT_EQ(16U, size);
  mojo::internal::FixedBufferForTesting buf(size);
  internal::PodUnion_Data* data = internal::PodUnion_Data::New(&buf);

  // Check that dirty output buffers are handled correctly by serialization.
  data->size = 16U;
  data->tag = PodUnion::Tag::F_UINT16;
  data->data.f_f_int16 = 20;

  SerializeUnion_(std::move(pod), &buf, &data, true);
  EXPECT_TRUE(data->is_null());

  PodUnionPtr pod2;
  Deserialize_(data, &pod2, nullptr);
  EXPECT_TRUE(pod2.is_null());
}

TEST(UnionTest, SerializeIsNullNotInlined) {
  PodUnionPtr pod;
  size_t size = GetSerializedSize_(pod, false);
  EXPECT_EQ(16U, size);
  mojo::internal::FixedBufferForTesting buf(size);
  internal::PodUnion_Data* data = nullptr;
  SerializeUnion_(std::move(pod), &buf, &data, false);
  EXPECT_EQ(nullptr, data);
}

TEST(UnionTest, NullValidation) {
  void* buf = nullptr;
  mojo::internal::BoundsChecker bounds_checker(buf, 0, 0);
  EXPECT_TRUE(internal::PodUnion_Data::Validate(buf, &bounds_checker, false));
}

TEST(UnionTest, OutOfAlignmentValidation) {
  size_t size = sizeof(internal::PodUnion_Data);
  // Get an aligned object and shift the alignment.
  mojo::internal::FixedBufferForTesting aligned_buf(size + 1);
  void* raw_buf = aligned_buf.Leak();
  char* buf = reinterpret_cast<char*>(raw_buf) + 1;

  internal::PodUnion_Data* data =
      reinterpret_cast<internal::PodUnion_Data*>(buf);
  mojo::internal::BoundsChecker bounds_checker(data,
                                               static_cast<uint32_t>(size), 0);
  EXPECT_FALSE(internal::PodUnion_Data::Validate(buf, &bounds_checker, false));
  free(raw_buf);
}

TEST(UnionTest, OOBValidation) {
  size_t size = sizeof(internal::PodUnion_Data) - 1;
  mojo::internal::FixedBufferForTesting buf(size);
  internal::PodUnion_Data* data = internal::PodUnion_Data::New(&buf);
  mojo::internal::BoundsChecker bounds_checker(data,
                                               static_cast<uint32_t>(size), 0);
  void* raw_buf = buf.Leak();
  EXPECT_FALSE(
      internal::PodUnion_Data::Validate(raw_buf, &bounds_checker, false));
  free(raw_buf);
}

TEST(UnionTest, UnknownTagValidation) {
  size_t size = sizeof(internal::PodUnion_Data);
  mojo::internal::FixedBufferForTesting buf(size);
  internal::PodUnion_Data* data = internal::PodUnion_Data::New(&buf);
  data->tag = static_cast<internal::PodUnion_Data::PodUnion_Tag>(0xFFFFFF);
  mojo::internal::BoundsChecker bounds_checker(data,
                                               static_cast<uint32_t>(size), 0);
  void* raw_buf = buf.Leak();
  EXPECT_FALSE(
      internal::PodUnion_Data::Validate(raw_buf, &bounds_checker, false));
  free(raw_buf);
}

TEST(UnionTest, StringGetterSetter) {
  ObjectUnionPtr pod(ObjectUnion::New());

  String hello("hello world");
  pod->set_f_string(hello);
  EXPECT_EQ(hello, pod->get_f_string());
  EXPECT_TRUE(pod->is_f_string());
  EXPECT_EQ(pod->which(), ObjectUnion::Tag::F_STRING);
}

TEST(UnionTest, StringEquals) {
  ObjectUnionPtr pod1(ObjectUnion::New());
  ObjectUnionPtr pod2(ObjectUnion::New());

  pod1->set_f_string("hello world");
  pod2->set_f_string("hello world");
  EXPECT_TRUE(pod1.Equals(pod2));

  pod2->set_f_string("hello universe");
  EXPECT_FALSE(pod1.Equals(pod2));
}

TEST(UnionTest, StringClone) {
  ObjectUnionPtr pod(ObjectUnion::New());

  String hello("hello world");
  pod->set_f_string(hello);
  ObjectUnionPtr pod_clone = pod.Clone();
  EXPECT_EQ(hello, pod_clone->get_f_string());
  EXPECT_TRUE(pod_clone->is_f_string());
  EXPECT_EQ(pod_clone->which(), ObjectUnion::Tag::F_STRING);
}

TEST(UnionTest, StringSerialization) {
  ObjectUnionPtr pod1(ObjectUnion::New());

  String hello("hello world");
  pod1->set_f_string(hello);

  size_t size = GetSerializedSize_(pod1, false);
  mojo::internal::FixedBufferForTesting buf(size);
  internal::ObjectUnion_Data* data = nullptr;
  SerializeUnion_(std::move(pod1), &buf, &data, false);

  std::vector<Handle> handles;
  data->EncodePointersAndHandles(&handles);
  data->DecodePointersAndHandles(&handles);

  ObjectUnionPtr pod2;
  Deserialize_(data, &pod2, nullptr);
  EXPECT_EQ(hello, pod2->get_f_string());
  EXPECT_TRUE(pod2->is_f_string());
  EXPECT_EQ(pod2->which(), ObjectUnion::Tag::F_STRING);
}

TEST(UnionTest, NullStringValidation) {
  size_t size = sizeof(internal::ObjectUnion_Data);
  mojo::internal::FixedBufferForTesting buf(size);
  internal::ObjectUnion_Data* data = internal::ObjectUnion_Data::New(&buf);
  data->tag = internal::ObjectUnion_Data::ObjectUnion_Tag::F_STRING;
  data->data.unknown = 0x0;
  mojo::internal::BoundsChecker bounds_checker(data,
                                               static_cast<uint32_t>(size), 0);
  void* raw_buf = buf.Leak();
  EXPECT_FALSE(
      internal::ObjectUnion_Data::Validate(raw_buf, &bounds_checker, false));
  free(raw_buf);
}

TEST(UnionTest, StringPointerOverflowValidation) {
  size_t size = sizeof(internal::ObjectUnion_Data);
  mojo::internal::FixedBufferForTesting buf(size);
  internal::ObjectUnion_Data* data = internal::ObjectUnion_Data::New(&buf);
  data->tag = internal::ObjectUnion_Data::ObjectUnion_Tag::F_STRING;
  data->data.unknown = 0xFFFFFFFFFFFFFFFF;
  mojo::internal::BoundsChecker bounds_checker(data,
                                               static_cast<uint32_t>(size), 0);
  void* raw_buf = buf.Leak();
  EXPECT_FALSE(
      internal::ObjectUnion_Data::Validate(raw_buf, &bounds_checker, false));
  free(raw_buf);
}

TEST(UnionTest, StringValidateOOB) {
  size_t size = 32;
  mojo::internal::FixedBufferForTesting buf(size);
  internal::ObjectUnion_Data* data = internal::ObjectUnion_Data::New(&buf);
  data->tag = internal::ObjectUnion_Data::ObjectUnion_Tag::F_STRING;

  data->data.f_f_string.offset = 8;
  char* ptr = reinterpret_cast<char*>(&data->data.f_f_string);
  mojo::internal::ArrayHeader* array_header =
      reinterpret_cast<mojo::internal::ArrayHeader*>(ptr + *ptr);
  array_header->num_bytes = 20;  // This should go out of bounds.
  array_header->num_elements = 20;
  mojo::internal::BoundsChecker bounds_checker(data, 32, 0);
  void* raw_buf = buf.Leak();
  EXPECT_FALSE(
      internal::ObjectUnion_Data::Validate(raw_buf, &bounds_checker, false));
  free(raw_buf);
}

// TODO(azani): Move back in array_unittest.cc when possible.
// Array tests
TEST(UnionTest, PodUnionInArray) {
  SmallStructPtr small_struct(SmallStruct::New());
  small_struct->pod_union_array = Array<PodUnionPtr>(2);
  small_struct->pod_union_array[0] = PodUnion::New();
  small_struct->pod_union_array[1] = PodUnion::New();

  small_struct->pod_union_array[0]->set_f_int8(10);
  small_struct->pod_union_array[1]->set_f_int16(12);

  EXPECT_EQ(10, small_struct->pod_union_array[0]->get_f_int8());
  EXPECT_EQ(12, small_struct->pod_union_array[1]->get_f_int16());
}

TEST(UnionTest, PodUnionInArraySerialization) {
  Array<PodUnionPtr> array(2);
  array[0] = PodUnion::New();
  array[1] = PodUnion::New();

  array[0]->set_f_int8(10);
  array[1]->set_f_int16(12);
  EXPECT_EQ(2U, array.size());

  size_t size = GetSerializedSize_(array);
  EXPECT_EQ(40U, size);

  mojo::internal::FixedBufferForTesting buf(size);
  mojo::internal::Array_Data<internal::PodUnion_Data>* data;
  mojo::internal::ArrayValidateParams validate_params(0, false, nullptr);
  SerializeArray_(std::move(array), &buf, &data, &validate_params);

  Array<PodUnionPtr> array2;
  Deserialize_(data, &array2, nullptr);

  EXPECT_EQ(2U, array2.size());

  EXPECT_EQ(10, array2[0]->get_f_int8());
  EXPECT_EQ(12, array2[1]->get_f_int16());
}

TEST(UnionTest, PodUnionInArraySerializationWithNull) {
  Array<PodUnionPtr> array(2);
  array[0] = PodUnion::New();

  array[0]->set_f_int8(10);
  EXPECT_EQ(2U, array.size());

  size_t size = GetSerializedSize_(array);
  EXPECT_EQ(40U, size);

  mojo::internal::FixedBufferForTesting buf(size);
  mojo::internal::Array_Data<internal::PodUnion_Data>* data;
  mojo::internal::ArrayValidateParams validate_params(0, true, nullptr);
  SerializeArray_(std::move(array), &buf, &data, &validate_params);

  Array<PodUnionPtr> array2;
  Deserialize_(data, &array2, nullptr);

  EXPECT_EQ(2U, array2.size());

  EXPECT_EQ(10, array2[0]->get_f_int8());
  EXPECT_TRUE(array2[1].is_null());
}

// TODO(azani): Move back in struct_unittest.cc when possible.
// Struct tests
TEST(UnionTest, Clone_Union) {
  SmallStructPtr small_struct(SmallStruct::New());
  small_struct->pod_union = PodUnion::New();
  small_struct->pod_union->set_f_int8(10);

  SmallStructPtr clone = small_struct.Clone();
  EXPECT_EQ(10, clone->pod_union->get_f_int8());
}

// Serialization test of a struct with a union of plain old data.
TEST(UnionTest, Serialization_UnionOfPods) {
  SmallStructPtr small_struct(SmallStruct::New());
  small_struct->pod_union = PodUnion::New();
  small_struct->pod_union->set_f_int32(10);

  size_t size = GetSerializedSize_(small_struct);

  mojo::internal::FixedBufferForTesting buf(size);
  internal::SmallStruct_Data* data = nullptr;
  Serialize_(std::move(small_struct), &buf, &data);

  SmallStructPtr deserialized;
  Deserialize_(data, &deserialized, nullptr);

  EXPECT_EQ(10, deserialized->pod_union->get_f_int32());
}

// Serialization test of a struct with a union of structs.
TEST(UnionTest, Serialization_UnionOfObjects) {
  SmallObjStructPtr obj_struct(SmallObjStruct::New());
  obj_struct->obj_union = ObjectUnion::New();
  String hello("hello world");
  obj_struct->obj_union->set_f_string(hello);

  size_t size = GetSerializedSize_(obj_struct);

  mojo::internal::FixedBufferForTesting buf(size);
  internal::SmallObjStruct_Data* data = nullptr;
  Serialize_(std::move(obj_struct), &buf, &data);

  std::vector<Handle> handles;
  data->EncodePointersAndHandles(&handles);
  data->DecodePointersAndHandles(&handles);

  SmallObjStructPtr deserialized;
  Deserialize_(data, &deserialized, nullptr);

  EXPECT_EQ(hello, deserialized->obj_union->get_f_string());
}

// Validation test of a struct with a union.
TEST(UnionTest, Validation_UnionsInStruct) {
  SmallStructPtr small_struct(SmallStruct::New());
  small_struct->pod_union = PodUnion::New();
  small_struct->pod_union->set_f_int32(10);

  size_t size = GetSerializedSize_(small_struct);

  mojo::internal::FixedBufferForTesting buf(size);
  internal::SmallStruct_Data* data = nullptr;
  Serialize_(std::move(small_struct), &buf, &data);

  std::vector<Handle> handles;
  data->EncodePointersAndHandles(&handles);
  EXPECT_TRUE(handles.empty());

  void* raw_buf = buf.Leak();
  mojo::internal::BoundsChecker bounds_checker(data,
                                               static_cast<uint32_t>(size), 0);
  EXPECT_TRUE(internal::SmallStruct_Data::Validate(raw_buf, &bounds_checker));
  free(raw_buf);
}

// Validation test of a struct union fails due to unknown union tag.
TEST(UnionTest, Validation_PodUnionInStruct_Failure) {
  SmallStructPtr small_struct(SmallStruct::New());
  small_struct->pod_union = PodUnion::New();
  small_struct->pod_union->set_f_int32(10);

  size_t size = GetSerializedSize_(small_struct);

  mojo::internal::FixedBufferForTesting buf(size);
  internal::SmallStruct_Data* data = nullptr;
  Serialize_(std::move(small_struct), &buf, &data);
  data->pod_union.tag = static_cast<internal::PodUnion_Data::PodUnion_Tag>(100);

  std::vector<Handle> handles;
  data->EncodePointersAndHandles(&handles);
  EXPECT_TRUE(handles.empty());

  void* raw_buf = buf.Leak();
  mojo::internal::BoundsChecker bounds_checker(data,
                                               static_cast<uint32_t>(size), 0);
  EXPECT_FALSE(internal::SmallStruct_Data::Validate(raw_buf, &bounds_checker));
  free(raw_buf);
}

// Validation fails due to non-nullable null union in struct.
TEST(UnionTest, Validation_NullUnion_Failure) {
  SmallStructNonNullableUnionPtr small_struct(
      SmallStructNonNullableUnion::New());

  size_t size = GetSerializedSize_(small_struct);

  mojo::internal::FixedBufferForTesting buf(size);
  internal::SmallStructNonNullableUnion_Data* data =
      internal::SmallStructNonNullableUnion_Data::New(&buf);

  void* raw_buf = buf.Leak();
  mojo::internal::BoundsChecker bounds_checker(data,
                                               static_cast<uint32_t>(size), 0);
  EXPECT_FALSE(internal::SmallStructNonNullableUnion_Data::Validate(
      raw_buf, &bounds_checker));
  free(raw_buf);
}

// Validation passes with nullable null union.
TEST(UnionTest, Validation_NullableUnion) {
  SmallStructPtr small_struct(SmallStruct::New());

  size_t size = GetSerializedSize_(small_struct);

  mojo::internal::FixedBufferForTesting buf(size);
  internal::SmallStruct_Data* data = nullptr;
  Serialize_(std::move(small_struct), &buf, &data);

  std::vector<Handle> handles;
  data->EncodePointersAndHandles(&handles);
  EXPECT_TRUE(handles.empty());

  void* raw_buf = buf.Leak();
  mojo::internal::BoundsChecker bounds_checker(data,
                                               static_cast<uint32_t>(size), 0);
  EXPECT_TRUE(internal::SmallStruct_Data::Validate(raw_buf, &bounds_checker));
  free(raw_buf);
}

// TODO(azani): Move back in map_unittest.cc when possible.
// Map Tests
TEST(UnionTest, PodUnionInMap) {
  SmallStructPtr small_struct(SmallStruct::New());
  small_struct->pod_union_map = Map<String, PodUnionPtr>();
  small_struct->pod_union_map.insert("one", PodUnion::New());
  small_struct->pod_union_map.insert("two", PodUnion::New());

  small_struct->pod_union_map["one"]->set_f_int8(8);
  small_struct->pod_union_map["two"]->set_f_int16(16);

  EXPECT_EQ(8, small_struct->pod_union_map["one"]->get_f_int8());
  EXPECT_EQ(16, small_struct->pod_union_map["two"]->get_f_int16());
}

TEST(UnionTest, PodUnionInMapSerialization) {
  Map<String, PodUnionPtr> map;
  map.insert("one", PodUnion::New());
  map.insert("two", PodUnion::New());

  map["one"]->set_f_int8(8);
  map["two"]->set_f_int16(16);

  size_t size = GetSerializedSize_(map);
  EXPECT_EQ(120U, size);

  mojo::internal::FixedBufferForTesting buf(size);
  mojo::internal::Map_Data<mojo::internal::String_Data*,
                           internal::PodUnion_Data>* data;
  mojo::internal::ArrayValidateParams validate_params(0, false, nullptr);
  SerializeMap_(std::move(map), &buf, &data, &validate_params);

  Map<String, PodUnionPtr> map2;
  Deserialize_(data, &map2, nullptr);

  EXPECT_EQ(8, map2["one"]->get_f_int8());
  EXPECT_EQ(16, map2["two"]->get_f_int16());
}

TEST(UnionTest, PodUnionInMapSerializationWithNull) {
  Map<String, PodUnionPtr> map;
  map.insert("one", PodUnion::New());
  map.insert("two", nullptr);

  map["one"]->set_f_int8(8);

  size_t size = GetSerializedSize_(map);
  EXPECT_EQ(120U, size);

  mojo::internal::FixedBufferForTesting buf(size);
  mojo::internal::Map_Data<mojo::internal::String_Data*,
                           internal::PodUnion_Data>* data;
  mojo::internal::ArrayValidateParams validate_params(0, true, nullptr);
  SerializeMap_(std::move(map), &buf, &data, &validate_params);

  Map<String, PodUnionPtr> map2;
  Deserialize_(data, &map2, nullptr);

  EXPECT_EQ(8, map2["one"]->get_f_int8());
  EXPECT_TRUE(map2["two"].is_null());
}

TEST(UnionTest, StructInUnionGetterSetterPasser) {
  DummyStructPtr dummy(DummyStruct::New());
  dummy->f_int8 = 8;

  ObjectUnionPtr obj(ObjectUnion::New());
  obj->set_f_dummy(std::move(dummy));

  EXPECT_EQ(8, obj->get_f_dummy()->f_int8);
}

TEST(UnionTest, StructInUnionSerialization) {
  DummyStructPtr dummy(DummyStruct::New());
  dummy->f_int8 = 8;

  ObjectUnionPtr obj(ObjectUnion::New());
  obj->set_f_dummy(std::move(dummy));

  size_t size = GetSerializedSize_(obj, false);
  EXPECT_EQ(32U, size);

  mojo::internal::FixedBufferForTesting buf(size);
  internal::ObjectUnion_Data* data = nullptr;
  SerializeUnion_(std::move(obj), &buf, &data, false);

  std::vector<Handle> handles;
  data->EncodePointersAndHandles(&handles);
  data->DecodePointersAndHandles(&handles);

  ObjectUnionPtr obj2;
  Deserialize_(data, &obj2, nullptr);
  EXPECT_EQ(8, obj2->get_f_dummy()->f_int8);
}

TEST(UnionTest, StructInUnionValidation) {
  DummyStructPtr dummy(DummyStruct::New());
  dummy->f_int8 = 8;

  ObjectUnionPtr obj(ObjectUnion::New());
  obj->set_f_dummy(std::move(dummy));

  size_t size = GetSerializedSize_(obj, false);

  mojo::internal::FixedBufferForTesting buf(size);
  internal::ObjectUnion_Data* data = nullptr;
  SerializeUnion_(std::move(obj), &buf, &data, false);

  std::vector<Handle> handles;
  data->EncodePointersAndHandles(&handles);
  EXPECT_TRUE(handles.empty());

  void* raw_buf = buf.Leak();
  mojo::internal::BoundsChecker bounds_checker(data,
                                               static_cast<uint32_t>(size), 0);
  EXPECT_TRUE(
      internal::ObjectUnion_Data::Validate(raw_buf, &bounds_checker, false));
  free(raw_buf);
}

TEST(UnionTest, StructInUnionValidationNonNullable) {
  DummyStructPtr dummy(nullptr);

  ObjectUnionPtr obj(ObjectUnion::New());
  obj->set_f_dummy(std::move(dummy));

  size_t size = GetSerializedSize_(obj, false);

  mojo::internal::FixedBufferForTesting buf(size);
  internal::ObjectUnion_Data* data = nullptr;
  SerializeUnion_(std::move(obj), &buf, &data, false);

  std::vector<Handle> handles;
  data->EncodePointersAndHandles(&handles);
  EXPECT_TRUE(handles.empty());

  void* raw_buf = buf.Leak();
  mojo::internal::BoundsChecker bounds_checker(data,
                                               static_cast<uint32_t>(size), 0);
  EXPECT_FALSE(
      internal::ObjectUnion_Data::Validate(raw_buf, &bounds_checker, false));
  free(raw_buf);
}

TEST(UnionTest, StructInUnionValidationNullable) {
  DummyStructPtr dummy(nullptr);

  ObjectUnionPtr obj(ObjectUnion::New());
  obj->set_f_nullable(std::move(dummy));

  size_t size = GetSerializedSize_(obj, false);

  mojo::internal::FixedBufferForTesting buf(size);
  internal::ObjectUnion_Data* data = nullptr;
  SerializeUnion_(std::move(obj), &buf, &data, false);

  std::vector<Handle> handles;
  data->EncodePointersAndHandles(&handles);
  EXPECT_TRUE(handles.empty());

  void* raw_buf = buf.Leak();
  mojo::internal::BoundsChecker bounds_checker(data,
                                               static_cast<uint32_t>(size), 0);
  EXPECT_TRUE(
      internal::ObjectUnion_Data::Validate(raw_buf, &bounds_checker, false));
  free(raw_buf);
}

TEST(UnionTest, ArrayInUnionGetterSetter) {
  Array<int8_t> array(2);
  array[0] = 8;
  array[1] = 9;

  ObjectUnionPtr obj(ObjectUnion::New());
  obj->set_f_array_int8(std::move(array));

  EXPECT_EQ(8, obj->get_f_array_int8()[0]);
  EXPECT_EQ(9, obj->get_f_array_int8()[1]);
}

TEST(UnionTest, ArrayInUnionSerialization) {
  Array<int8_t> array(2);
  array[0] = 8;
  array[1] = 9;

  ObjectUnionPtr obj(ObjectUnion::New());
  obj->set_f_array_int8(std::move(array));

  size_t size = GetSerializedSize_(obj, false);
  EXPECT_EQ(32U, size);

  mojo::internal::FixedBufferForTesting buf(size);
  internal::ObjectUnion_Data* data = nullptr;
  SerializeUnion_(std::move(obj), &buf, &data, false);

  std::vector<Handle> handles;
  data->EncodePointersAndHandles(&handles);
  data->DecodePointersAndHandles(&handles);

  ObjectUnionPtr obj2;
  Deserialize_(data, &obj2, nullptr);

  EXPECT_EQ(8, obj2->get_f_array_int8()[0]);
  EXPECT_EQ(9, obj2->get_f_array_int8()[1]);
}

TEST(UnionTest, ArrayInUnionValidation) {
  Array<int8_t> array(2);
  array[0] = 8;
  array[1] = 9;

  ObjectUnionPtr obj(ObjectUnion::New());
  obj->set_f_array_int8(std::move(array));

  size_t size = GetSerializedSize_(obj, false);
  mojo::internal::FixedBufferForTesting buf(size);
  internal::ObjectUnion_Data* data = nullptr;
  SerializeUnion_(std::move(obj), &buf, &data, false);

  std::vector<Handle> handles;
  data->EncodePointersAndHandles(&handles);

  void* raw_buf = buf.Leak();
  mojo::internal::BoundsChecker bounds_checker(data,
                                               static_cast<uint32_t>(size), 0);

  EXPECT_TRUE(
      internal::ObjectUnion_Data::Validate(raw_buf, &bounds_checker, false));
  free(raw_buf);
}

TEST(UnionTest, MapInUnionGetterSetter) {
  Map<String, int8_t> map;
  map.insert("one", 1);
  map.insert("two", 2);

  ObjectUnionPtr obj(ObjectUnion::New());
  obj->set_f_map_int8(std::move(map));

  EXPECT_EQ(1, obj->get_f_map_int8()["one"]);
  EXPECT_EQ(2, obj->get_f_map_int8()["two"]);
}

TEST(UnionTest, MapInUnionSerialization) {
  Map<String, int8_t> map;
  map.insert("one", 1);
  map.insert("two", 2);

  ObjectUnionPtr obj(ObjectUnion::New());
  obj->set_f_map_int8(std::move(map));

  size_t size = GetSerializedSize_(obj, false);
  EXPECT_EQ(112U, size);

  mojo::internal::FixedBufferForTesting buf(size);
  internal::ObjectUnion_Data* data = nullptr;
  SerializeUnion_(std::move(obj), &buf, &data, false);

  std::vector<Handle> handles;
  data->EncodePointersAndHandles(&handles);
  data->DecodePointersAndHandles(&handles);

  ObjectUnionPtr obj2;
  Deserialize_(data, &obj2, nullptr);

  EXPECT_EQ(1, obj2->get_f_map_int8()["one"]);
  EXPECT_EQ(2, obj2->get_f_map_int8()["two"]);
}

TEST(UnionTest, MapInUnionValidation) {
  Map<String, int8_t> map;
  map.insert("one", 1);
  map.insert("two", 2);

  ObjectUnionPtr obj(ObjectUnion::New());
  obj->set_f_map_int8(std::move(map));

  size_t size = GetSerializedSize_(obj, false);
  EXPECT_EQ(112U, size);

  mojo::internal::FixedBufferForTesting buf(size);
  internal::ObjectUnion_Data* data = nullptr;
  SerializeUnion_(std::move(obj), &buf, &data, false);

  std::vector<Handle> handles;
  data->EncodePointersAndHandles(&handles);
  EXPECT_TRUE(handles.empty());

  void* raw_buf = buf.Leak();
  mojo::internal::BoundsChecker bounds_checker(data,
                                               static_cast<uint32_t>(size), 0);

  EXPECT_TRUE(
      internal::ObjectUnion_Data::Validate(raw_buf, &bounds_checker, false));
  free(raw_buf);
}

TEST(UnionTest, UnionInUnionGetterSetter) {
  PodUnionPtr pod(PodUnion::New());
  pod->set_f_int8(10);

  ObjectUnionPtr obj(ObjectUnion::New());
  obj->set_f_pod_union(std::move(pod));

  EXPECT_EQ(10, obj->get_f_pod_union()->get_f_int8());
}

TEST(UnionTest, UnionInUnionSerialization) {
  PodUnionPtr pod(PodUnion::New());
  pod->set_f_int8(10);

  ObjectUnionPtr obj(ObjectUnion::New());
  obj->set_f_pod_union(std::move(pod));

  size_t size = GetSerializedSize_(obj, false);
  EXPECT_EQ(32U, size);

  mojo::internal::FixedBufferForTesting buf(size);
  internal::ObjectUnion_Data* data = nullptr;
  SerializeUnion_(std::move(obj), &buf, &data, false);

  std::vector<Handle> handles;
  data->EncodePointersAndHandles(&handles);
  data->DecodePointersAndHandles(&handles);

  ObjectUnionPtr obj2;
  Deserialize_(data, &obj2, nullptr);
  EXPECT_EQ(10, obj2->get_f_pod_union()->get_f_int8());
}

TEST(UnionTest, UnionInUnionValidation) {
  PodUnionPtr pod(PodUnion::New());
  pod->set_f_int8(10);

  ObjectUnionPtr obj(ObjectUnion::New());
  obj->set_f_pod_union(std::move(pod));

  size_t size = GetSerializedSize_(obj, false);
  EXPECT_EQ(32U, size);

  mojo::internal::FixedBufferForTesting buf(size);
  internal::ObjectUnion_Data* data = nullptr;
  SerializeUnion_(std::move(obj), &buf, &data, false);

  std::vector<Handle> handles;
  data->EncodePointersAndHandles(&handles);
  EXPECT_TRUE(handles.empty());

  void* raw_buf = buf.Leak();
  mojo::internal::BoundsChecker bounds_checker(data,
                                               static_cast<uint32_t>(size), 0);
  EXPECT_TRUE(
      internal::ObjectUnion_Data::Validate(raw_buf, &bounds_checker, false));
  free(raw_buf);
}

TEST(UnionTest, UnionInUnionValidationNonNullable) {
  PodUnionPtr pod(nullptr);

  ObjectUnionPtr obj(ObjectUnion::New());
  obj->set_f_pod_union(std::move(pod));

  size_t size = GetSerializedSize_(obj, false);

  mojo::internal::FixedBufferForTesting buf(size);
  internal::ObjectUnion_Data* data = nullptr;
  SerializeUnion_(std::move(obj), &buf, &data, false);
  std::vector<Handle> handles;
  data->EncodePointersAndHandles(&handles);

  void* raw_buf = buf.Leak();
  mojo::internal::BoundsChecker bounds_checker(data,
                                               static_cast<uint32_t>(size), 0);
  EXPECT_FALSE(
      internal::ObjectUnion_Data::Validate(raw_buf, &bounds_checker, false));
  free(raw_buf);
}

TEST(UnionTest, HandleInUnionGetterSetter) {
  ScopedMessagePipeHandle pipe0;
  ScopedMessagePipeHandle pipe1;

  CreateMessagePipe(nullptr, &pipe0, &pipe1);

  HandleUnionPtr handle(HandleUnion::New());
  handle->set_f_message_pipe(std::move(pipe1));

  std::string golden("hello world");
  WriteTextMessage(pipe0.get(), golden);

  std::string actual;
  ReadTextMessage(handle->get_f_message_pipe().get(), &actual);

  EXPECT_EQ(golden, actual);
}

TEST(UnionTest, HandleInUnionSerialization) {
  ScopedMessagePipeHandle pipe0;
  ScopedMessagePipeHandle pipe1;

  CreateMessagePipe(nullptr, &pipe0, &pipe1);

  HandleUnionPtr handle(HandleUnion::New());
  handle->set_f_message_pipe(std::move(pipe1));

  size_t size = GetSerializedSize_(handle, false);
  EXPECT_EQ(16U, size);

  mojo::internal::FixedBufferForTesting buf(size);
  internal::HandleUnion_Data* data = nullptr;
  SerializeUnion_(std::move(handle), &buf, &data, false);

  std::vector<Handle> handles;
  data->EncodePointersAndHandles(&handles);
  EXPECT_EQ(1U, handles.size());
  data->DecodePointersAndHandles(&handles);

  HandleUnionPtr handle2(HandleUnion::New());
  Deserialize_(data, &handle2, nullptr);

  std::string golden("hello world");
  WriteTextMessage(pipe0.get(), golden);

  std::string actual;
  ReadTextMessage(handle2->get_f_message_pipe().get(), &actual);

  EXPECT_EQ(golden, actual);
}

TEST(UnionTest, HandleInUnionValidation) {
  ScopedMessagePipeHandle pipe0;
  ScopedMessagePipeHandle pipe1;

  CreateMessagePipe(nullptr, &pipe0, &pipe1);

  HandleUnionPtr handle(HandleUnion::New());
  handle->set_f_message_pipe(std::move(pipe1));

  size_t size = GetSerializedSize_(handle, false);
  EXPECT_EQ(16U, size);

  mojo::internal::FixedBufferForTesting buf(size);
  internal::HandleUnion_Data* data = nullptr;
  SerializeUnion_(std::move(handle), &buf, &data, false);

  std::vector<Handle> handles;
  data->EncodePointersAndHandles(&handles);

  void* raw_buf = buf.Leak();
  mojo::internal::BoundsChecker bounds_checker(data,
                                               static_cast<uint32_t>(size), 1);
  EXPECT_TRUE(
      internal::HandleUnion_Data::Validate(raw_buf, &bounds_checker, false));
  free(raw_buf);
}

TEST(UnionTest, HandleInUnionValidationNull) {
  ScopedMessagePipeHandle pipe;
  HandleUnionPtr handle(HandleUnion::New());
  handle->set_f_message_pipe(std::move(pipe));

  size_t size = GetSerializedSize_(handle, false);
  EXPECT_EQ(16U, size);

  mojo::internal::FixedBufferForTesting buf(size);
  internal::HandleUnion_Data* data = nullptr;
  SerializeUnion_(std::move(handle), &buf, &data, false);

  std::vector<Handle> handles;
  data->EncodePointersAndHandles(&handles);

  void* raw_buf = buf.Leak();
  mojo::internal::BoundsChecker bounds_checker(data,
                                               static_cast<uint32_t>(size), 1);
  EXPECT_FALSE(
      internal::HandleUnion_Data::Validate(raw_buf, &bounds_checker, false));
  free(raw_buf);
}

class SmallCacheImpl : public SmallCache {
 public:
  explicit SmallCacheImpl(const base::Closure& closure)
      : int_value_(0), closure_(closure) {}
  ~SmallCacheImpl() override {}
  int64_t int_value() const { return int_value_; }

 private:
  void SetIntValue(int64_t int_value) override {
    int_value_ = int_value;
    closure_.Run();
  }
  void GetIntValue(const GetIntValueCallback& callback) override {
    callback.Run(int_value_);
  }

  int64_t int_value_;
  base::Closure closure_;
};

TEST(UnionTest, InterfaceInUnion) {
  base::MessageLoop message_loop(common::MessagePumpMojo::Create());
  base::RunLoop run_loop;
  SmallCacheImpl impl(run_loop.QuitClosure());
  SmallCachePtr ptr;
  Binding<SmallCache> bindings(&impl, GetProxy(&ptr));

  HandleUnionPtr handle(HandleUnion::New());
  handle->set_f_small_cache(std::move(ptr));

  handle->get_f_small_cache()->SetIntValue(10);
  run_loop.Run();
  EXPECT_EQ(10, impl.int_value());
}

TEST(UnionTest, InterfaceInUnionSerialization) {
  base::MessageLoop message_loop(common::MessagePumpMojo::Create());
  base::RunLoop run_loop;
  SmallCacheImpl impl(run_loop.QuitClosure());
  SmallCachePtr ptr;
  Binding<SmallCache> bindings(&impl, GetProxy(&ptr));

  HandleUnionPtr handle(HandleUnion::New());
  handle->set_f_small_cache(std::move(ptr));
  size_t size = GetSerializedSize_(handle, false);
  EXPECT_EQ(16U, size);

  mojo::internal::FixedBufferForTesting buf(size);
  internal::HandleUnion_Data* data = nullptr;
  SerializeUnion_(std::move(handle), &buf, &data, false);

  std::vector<Handle> handles;
  data->EncodePointersAndHandles(&handles);
  EXPECT_EQ(1U, handles.size());
  data->DecodePointersAndHandles(&handles);

  HandleUnionPtr handle2(HandleUnion::New());
  Deserialize_(data, &handle2, nullptr);

  handle2->get_f_small_cache()->SetIntValue(10);
  run_loop.Run();
  EXPECT_EQ(10, impl.int_value());
}

class UnionInterfaceImpl : public UnionInterface {
 public:
  UnionInterfaceImpl() {}
  ~UnionInterfaceImpl() override {}

 private:
  void Echo(PodUnionPtr in, const EchoCallback& callback) override {
    callback.Run(std::move(in));
  }
};

TEST(UnionTest, UnionInInterface) {
  base::MessageLoop run_loop(common::MessagePumpMojo::Create());
  UnionInterfaceImpl impl;
  UnionInterfacePtr ptr;
  Binding<UnionInterface> bindings(&impl, GetProxy(&ptr));

  PodUnionPtr pod(PodUnion::New());
  pod->set_f_int16(16);

  ptr->Echo(std::move(pod),
            [](PodUnionPtr out) { EXPECT_EQ(16, out->get_f_int16()); });
  run_loop.RunUntilIdle();
}

}  // namespace test
}  // namespace mojo


text:
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from '../../../biosys-core/services/auth.service';

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(protected authService: AuthService, protected router: Router) {
    }

    canActivate() {
        if (!this.authService.isLoggedIn()) {
            this.router.navigate(['/login']);

            return false;
        }

        return true;
    }
}


text:
package android.support.v4.view;

import android.view.View;

// Referenced classes of package android.support.v4.view:
//            ViewPropertyAnimatorCompat, ViewPropertyAnimatorCompatKK, ViewPropertyAnimatorUpdateListener

static class  extends
{

    public void setUpdateListener(ViewPropertyAnimatorCompat viewpropertyanimatorcompat, View view, ViewPropertyAnimatorUpdateListener viewpropertyanimatorupdatelistener)
    {
        ViewPropertyAnimatorCompatKK.setUpdateListener(view, viewpropertyanimatorupdatelistener);
    }

    ()
    {
    }
}


text:
(function () {
    var modal = highed.OverlayModal(false, {
            showOnInit: false,
            zIndex: 11000,
            width: 300,
            height: 400
        })
    ;

    highed.dom.ap(modal.body,
        highed.dom.cr('span', '', 'License info goes here')
    );

    highed.licenseInfo = {
        /** Show license information modal
         *  @namespace highed.licenseInfo
         *  @type function
         */
        show: modal.show
    };

})();


text:
import React, { useContext } from 'react';

export const SkeletonContext = React.createContext();

export const useSkeleton = () => useContext(SkeletonContext);


text:
from django.contrib import admin

import reversion

from .models import Page

class PageAdmin(reversion.VersionAdmin):

    pass

admin.site.register(Page, PageAdmin)


text:
<?php //-->

/**
 * Yahoo API factory. This is a factory class with
 * methods that will load up different Yahoo classes.
 *
 * @package    Eden
 * @category   Yahoo
 * @author     Christian Symon M. Buenavista sbuenavista@openovate.com
 */
class eden_yahoo extends Eden_Class
{
    /* Constants
    -------------------------------*/
    /* Public Properties
    -------------------------------*/
    /* Protected Properties
    -------------------------------*/
    /* Private Properties
    -------------------------------*/
    /* Get
    -------------------------------*/
    public static function i()
    {
        return self::_getSingleton(__CLASS__);
    }

    /* Magic
    -------------------------------*/
    /* Public Methods
    -------------------------------*/
    /**
     * Returns FQL
     *
     * @return Eden_Yahoo_Yql
     */
    public function yql()
    {
        return Eden_Yahoo_Yql::i();
    }

    /**
     * Returns Yahoo Oauth
     *
     * @return Eden_Yahoo_Oauth
     */
    public function oauth($key, $secret)
    {
        return Eden_Yahoo_Oauth::i($key, $secret);
    }

    /* Protected Methods
    -------------------------------*/
    /* Private Methods
    -------------------------------*/
}


text:
cmapi.map.message.complete.builder[emp.intents.control.SELECTION_SET] = {

    // oTransaction will have a transaction property
    build: function (oTransaction) {
        var oMsgCompletion = new cmapi.typeLibrary.MessageComplete(oTransaction);
        var oFeatures = oTransaction.items;
        var oDetails = {
            features: []
        };
        var feature;

        for (var iIndex = 0; iIndex < oFeatures.length; iIndex++)
        {
            if (oFeatures[iIndex].featureId) {
              feature = emp.storage.findObject(oFeatures[iIndex].coreId);

              if (feature) {
                oDetails.features.push({
                  featureId: feature.options.featureId,
                  name: feature.options.name,
                  format: feature.options.format,
                  feature: feature.options.data,
                  properties: feature.options.properties,
                  symbolCode: feature.options.symbolCode
                });
              }
            }
        }

        oMsgCompletion.details = oDetails;

        return oMsgCompletion;
    }
};


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use backend\models\Province;

/* @var $this yii\web\View */
/* @var $model app\models\City */
/* @var $form yii\widgets\ActiveForm */

?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'province_id')->dropDownList(Province::getProvinceList()) ?>

    <?= $form->field($model, 'name')->textInput(['maxlength' => 255]) ?>

    <?= $form->field($model, 'status')->dropDownList($model->getStatusArray()) ?>

    <?= $form->field($model, 'seo_title')->textInput(['maxlength' => 255]) ?>

    <?= $form->field($model, 'seo_keyword')->textInput(['maxlength' => 255]) ?>

    <?= $form->field($model, 'seo_desc')->textarea(['rows' => 6]) ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
	/////// //////////////////
	/////// PROJECT: MTA iLife - German Fun Reallife Gamemode
	/////// VERSION: 1.7.2
	/////// DEVELOPERS: See DEVELOPERS.md in the top folder
	/////// LICENSE: See LICENSE.md in the top folder
	/////// /////////////////
]]

cWebRadio = {}

function cWebRadio:constructor(iID, strName, strURL)
	self.iID = iID
	self.strName = strName
	self.strURL = strURL
end

function cWebRadio:destructor()

end
--[[
function cWebRadio:play()

end

function cWebRadio:play3D()

end

function cWebRadio:stop()

end

function cWebRadio:setPaused()

end]]


text:
var request = require('request'),
    mail = require('nodemailer').mail,
    fs = require('fs'),
    cheerio = require('cheerio'),
    builder   = require('xmlbuilder'),
    Table = require('cli-table'),
    _ = require('lodash');

function Litmus(options){
  this.options = options;
  this.initVars();
}

// Initialize variables
Litmus.prototype.initVars = function() {

  this.reqObj = {
    auth: {
      user: this.options.username || '',
      pass: this.options.password || ''
    }
  };
};

// Run test
Litmus.prototype.run = function(html, title, next) {
  this.title = title;
  this.delay = this.options.delay || 3500;

  if( (this.title === undefined) || (this.title.trim().length === 0) ){
    this.title = title;
  }

  this.html = html;
  this.getTests(function(body){
    var id = this.getId(body);
    this.sendTest(id);
    setTimeout(next, this.delay);
  });

};

// Grab tests from Litmus
Litmus.prototype.getTests = function(fn) {
  var self = this,
      opts = this.reqObj;
  opts.url = this.options.url + '/tests.xml';
  request.get(opts, function(err, res, body){
    if(err) { throw err; }
    fn.call(self, body);
  });
};

// Grab the name of email and set id if it matches title/subject line
Litmus.prototype.getId = function(body) {
  var $ = cheerio.load(body, {xmlMode: true}),
      $allNameTags = $('name'),
      subjLine = this.title,
      id,
      $matchedName = $allNameTags.filter(function(){
        return $(this).text() === subjLine;
      });

  if($matchedName.length){
    id = $matchedName.first().parent().children('id').text();
  }

  return id;
};

// Calculate and get the average time for test to complete
Litmus.prototype.getAvgTime = function(body) {
  var $ = cheerio.load(body, { xmlMode: true });
  var avgTimes = $('average_time_to_process');
  var count = 0;
  avgTimes.each(function(i, el){
    count += +$(this).text();
  });

  if(count < 60){
    return count + ' secs';
  }else{
    return  Math.round((count/avgTimes.length)/60) + ' mins';
  }
};

// Log status of test
Litmus.prototype.getStatus = function(body) {
  var $ = cheerio.load(body, { xmlMode: true }),
      statuses = $('status'),
      delayed = [],
      unavailable = [],
      statusCode,
      application;

  statuses.each(function(i, el){

    var $this = $(this);
    statusCode = +$this.text();
    application = $this.parent().children('application_long_name').text();

    if(statusCode === 1){ delayed.push(application); }

    if(statusCode === 2){ unavailable.push(application); }

  });

  return {
    delayed: delayed.join('\n'),
    unavailable: unavailable.join('\n')
  };

};

Litmus.prototype.logStatusTable = function(body) {
  var table = new Table(),
      delayed = this.getStatus(body).delayed,
      unavailable = this.getStatus(body).unavailable,
      avgTime = this.getAvgTime(body),
      values = [];

  table.options.head = ['Avg. Time to Complete'.bold];
  values.push(avgTime);

  if(delayed.length > 0){
    table.options.head.push('Delayed'.bold);
    values.push(delayed);
  }

  if(unavailable.length > 0){
    table.options.head.push('Unavailable'.bold);
    values.push(unavailable);
  }

  table.push(values);

  console.log(table.toString());
};

// Send a new version if id is availabe otherwise send a new test
Litmus.prototype.sendTest = function(id) {
  var self = this;
  var opts = _.clone(this.reqObj);

  opts.headers = { 'Content-type': 'application/xml', 'Accept': 'application/xml' };
  opts.body = this.getBuiltXml(this.html, this.title);

  if(id){
    this.log('Sending new version: '.bold + this.title);
    opts.url = this.options.url + '/tests/'+ id + '/versions.xml';
    request.post(opts, this.mailNewVersion.bind(this));
  }else{
    this.log('Sending new test: '.bold + this.title);
    opts.url = this.options.url + '/emails.xml';
    request.post(opts, this.logHeaders.bind(this));
  }
};

// Logs headers of response once email is sent
Litmus.prototype.logHeaders = function(err, res, body) {
  if(err){ throw err; }

  var headers = res.headers;
  var status = parseFloat(headers.status, 10);

  Object.keys(headers).forEach(function(key){
    console.log(key.toUpperCase().bold + ': ' + headers[key]);
  });

  console.log('---------------------\n' + body);

  if(status > 199 && status < 300){
    this.logSuccess('Test sent!');
    this.logStatusTable(body);
  } else {
    throw new Error(headers.status);
  }

};

// Mail a new test using test email Litmus provides
Litmus.prototype.mailNewVersion = function(err, res, body) {
  if(err){ throw err; }

  var $ = cheerio.load(body),
      guid = $('url_or_guid').text();

  mail({
      from: 'no-reply@test.com',
      to: guid,
      subject: this.title,
      text: '',
      html: this.html
  });
  this.logSuccess('New version sent!');
  this.logStatusTable(body);

};

Litmus.prototype.getBuiltXml = function(html, title) {

  var xml = builder.create('test_set').ele('applications').att('type', 'array')

  _.each(this.options.clients, function(app) {
    xml = xml.ele('application').ele('code', app).up().up()
  });

  xml = xml.up()
    .ele('save_defaults', 'false').up()
    .ele('use_defaults', 'false').up()
    .ele('email_source')
      .ele('body').dat(html).up()
      .ele('subject', title)
    .end({pretty: true});

  return xml;
};

// Logging helpers
Litmus.prototype.log = function(str) {
  return console.log(str.cyan);
};

Litmus.prototype.logSuccess = function(str) {
  return console.log(str.green);
};

module.exports = Litmus;


text:
can.Component.extend({
  tag: "assessment-generator-button",
  template: "{{{> /static/mustache/base_objects/generate_assessments_button.mustache}}}",
  scope: {
    audit: null
  },
  events: {
    'a click': function() {
      if (this.scope.loading) {
        return;
      }
      this._generate_control_assessments();
    },

    _generate_control_assessments: function(controls) {
      var assessments_list = this.scope.audit.get_binding("related_control_assessments").list,
          controls_list = this.scope.audit.get_binding("program_controls").list,
          assessments_dfd = this._refresh(assessments_list),
          controls_dfd = this._refresh(controls_list),
          ignore_controls, dfd, inner_dfd = new $.Deferred().resolve();

      dfd = $.when(assessments_dfd, controls_dfd).then(function (assessments, controls) {
        ignore_controls = _.map(assessments, function(ca) {
          return ca.control.id;
        });

        return $.when.apply($, can.map(controls, function(control) {
          if (_.includes(ignore_controls, control.id)) {
            return;
          }
          // We are rewriting inner_dfd to make sure _generate calls are
          // daisy chained
          inner_dfd = this._generate(control, inner_dfd);
          return  inner_dfd;
        }.bind(this)));
      }.bind(this));
      this._enter_loading_state(dfd);
      dfd.always(this._notify.bind(this));
    },

    _refresh: function (bindings) {
      var refresh_queue = new RefreshQueue();
      can.each(bindings, function(binding) {
          refresh_queue.enqueue(binding.instance);
      });
      return refresh_queue.trigger();
    },

    _generate: function (control, dfd) {
      var assessment,
          index,
          title = control.title + ' assessment for ' + this.scope.audit.title,
          data = {
            audit: this.scope.audit,
            control: control.stub(),
            context: this.scope.audit.context,
            owners: [CMS.Models.Person.findInCacheById(GGRC.current_user.id)],
            test_plan: control.test_plan
          };
      return dfd.then(function() {
        return GGRC.Models.Search.counts_for_types(title, ['ControlAssessment']);
      }).then(function (result) {
        index = result.getCountFor('ControlAssessment') + 1;
        data.title = title + ' ' + index;
        return new CMS.Models.ControlAssessment(data).save();
      }.bind(this));
    },

    _notify: function() {
      this._exit_loading_state();

      var assessments = arguments,
        count = _.filter(assessments, function(assessment) {
          return  !_.isNull(assessment) && !(assessment.state && assessment.state() === "rejected");
        }).length,
        errors = _.filter(assessments, function(assessment) {
          return assessment.state && assessment.state() === "rejected";
        }).length,
        msg;

      if (errors < 1) {
        if (count === 0) {
          msg = {
            success: "Every Control already has a Control Assessment!"
          };
        } else {
          msg = {
            success: "" + count + " Control Assessments successfully created."
          };
        }
      } else {
        msg = {
          error: "An error occured when creating Control Assessments."
        };
      }

      $(document.body).trigger("ajax:flash", msg);
    },

    _enter_loading_state: function (deferred) {
      var $i = this.element.find("a > i"),
          icon = $i.attr("class");

      $i.attr("class", "grcicon-loading");
      $(document.body).trigger("ajax:flash",
                               {warning: "Generating Control Assessments"});

      this.scope.icon = icon;
      this.scope.loading = true;
      GGRC.delay_leaving_page_until(deferred);
    },

    _exit_loading_state: function () {
      this.element.find("a > i")
            .attr("class", this.scope.icon);

      this.scope.loading = false;
    }
  }
});