text:
#include <iostream>
#include <string>
#include <map>
#include <vector>

#include <getopt/getopt.h>

#include <utils/EntityManager.h>
#include <utils/Path.h>

#include <filament/Engine.h>
#include <filament/IndexBuffer.h>
#include <filament/Material.h>
#include <filament/Scene.h>
#include <filament/LightManager.h>
#include <filament/Renderer.h>
#include <filament/RenderableManager.h>
#include <filament/TransformManager.h>
#include <filament/VertexBuffer.h>

#include <math/norm.h>
#include <utils/Log.h>
#include <filament/View.h>

#include <filamentapp/Config.h>
#include <filamentapp/FilamentApp.h>
#include <filamentapp/MeshAssimp.h>
#include <filamentapp/Cube.h>
#include <filamentapp/IcoSphere.h>
#include <filamentapp/Sphere.h>

#include "generated/resources/resources.h"

using namespace filament::math;
using namespace filament;
using namespace filamat;
using namespace utils;

static std::vector<Path> g_filenames;

std::map<std::string, MaterialInstance*> g_materialLibrary;
std::unique_ptr<MeshAssimp> g_meshSet;
std::unique_ptr<Cube> g_meshAabb;

static std::vector<Sphere> g_spheres;
static std::vector<Entity> g_lights;

static Entity g_discoBallEntity;
static float g_discoAngle = 0;
static float g_discoAngularSpeed = 0.25f * float(M_PI);  // rad/s

static Config g_config;
static bool g_moreLights = false;
static bool g_shadowPlane = false;
static bool g_discoBall = false;

static void printUsage(char* name) {
    std::string exec_name(Path(name).getName());
    std::string usage(
            "LIGHTBULB is a command-line tool for testing the filament engine\n"
            "Usage:\n"
            "    LIGHTBULB [options] <mesh files>\n"
            "Options:\n"
            "   --help, -h\n"
            "       Prints this message\n\n"
            "   --api, -a\n"
            "       Specify the backend API: opengl (default), vulkan, or metal\n\n"
            "   --ibl=<path>, -i <path>\n"
            "       Applies an IBL\n\n"
            "       path can either be a directory containing IBL data files generated by cmgen,\n"
            "       or, a .hdr equiretangular image file\n\n"
            "   --split-view, -v\n"
            "       Splits the window into 4 views\n\n"
            "   --scale=[number], -s [number]\n"
            "       Applies uniform scale\n\n"
            "   --more-lights, -m\n"
            "       Adds a few more lights\n\n"
            "   --disco, -d\n"
            "       Add a disco ball\n\n"
            "   --shadow-plane, -p\n"
            "       Enable shadow plane\n\n"
    );
    const std::string from("LIGHTBULB");
    for (size_t pos = usage.find(from); pos != std::string::npos; pos = usage.find(from, pos)) {
        usage.replace(pos, from.length(), exec_name);
    }
    std::cout << usage;
}

static int handleCommandLineArgments(int argc, char* argv[], Config* config) {
    static constexpr const char* OPTSTR = "hi:vs:mdcpa:";
    static const struct option OPTIONS[] = {
            { "help",         no_argument,       nullptr, 'h' },
            { "api",          required_argument, nullptr, 'a' },
            { "ibl",          required_argument, nullptr, 'i' },
            { "split-view",   no_argument,       nullptr, 'v' },
            { "scale",        required_argument, nullptr, 's' },
            { "more-lights",  no_argument,       nullptr, 'm' },
            { "disco",        no_argument,       nullptr, 'd' },
            { "clear-coat",   no_argument,       nullptr, 'c' },
            { "shadow-plane", no_argument,       nullptr, 'p' },
            { nullptr, 0, nullptr, 0 }  // termination of the option list
    };
    int opt;
    int option_index = 0;
    while ((opt = getopt_long(argc, argv, OPTSTR, OPTIONS, &option_index)) >= 0) {
        std::string arg(optarg != nullptr ? optarg : "");
        switch (opt) {
            default:
            case 'h':
                printUsage(argv[0]);
                exit(0);
            case 'a':
                if (arg == "opengl") {
                    config->backend = Engine::Backend::OPENGL;
                } else if (arg == "vulkan") {
                    config->backend = Engine::Backend::VULKAN;
                } else if (arg == "metal") {
                    config->backend = Engine::Backend::METAL;
                } else {
                    std::cerr << "Unrecognized backend. Must be 'opengl'|'vulkan'|'metal'." << std::endl;
                }
                break;
            case 'i':
                config->iblDirectory = arg;
                break;
            case 's':
                try {
                    config->scale = std::stof(arg);
                } catch (std::invalid_argument& e) {
                    // keep scale of 1.0
                } catch (std::out_of_range& e) {
                    // keep scale of 1.0
                }
                break;
            case 'v':
                config->splitView = true;
                break;
            case 'm':
                g_moreLights = true;
                break;
            case 'd':
                g_discoBall = true;
                break;
            case 'p':
                g_shadowPlane = true;
                break;
        }
    }

    return optind;
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
static void cleanup(Engine* engine, View* view, Scene* scene) {
    for (auto& item : g_materialLibrary) {
        auto materialInstance = item.second;
        engine->destroy(materialInstance);
    }
    g_meshSet.reset(nullptr);
    g_meshAabb.reset(nullptr);

    auto& em = EntityManager::get();

    g_spheres.clear();

    for (Entity e : g_lights) {
        engine->destroy(e);
        em.destroy(e);
    }
    if (g_discoBallEntity) {
        em.destroy(g_discoBallEntity);
    }
}
#pragma clang diagnostic pop

static void preRender(filament::Engine* engine, filament::View* view, filament::Scene*,
        filament::Renderer* renderer) {

    // Without an IBL, we must clear the swapchain to black before each frame.
    renderer->setClearOptions({
            .clearColor = { 0.0f, 0.0f, 0.0f, 1.0f },
            .clear = !FilamentApp::get().getIBL()  });

}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
static void setup(Engine* engine, View* view, Scene* scene) {
    g_meshSet.reset(new MeshAssimp(*engine));
    for (auto& filename : g_filenames) {
        g_meshSet->addFromFile(filename, g_materialLibrary);
    }

    auto& lcm = engine->getLightManager();

    // set the transform on the root node only
    auto& tcm = engine->getTransformManager();
    auto ti = tcm.getInstance(g_meshSet->getRenderables()[0]);
    tcm.setTransform(ti, mat4f{ mat3f(g_config.scale), float3(0.0f, 0.0f, -4.0f) } *
                         tcm.getWorldTransform(ti));

    auto& rcm = engine->getRenderableManager();
    for (auto renderable : g_meshSet->getRenderables()) {
        if (rcm.hasComponent(renderable)) {
            auto ri = rcm.getInstance(renderable);
            auto blendingMode = rcm.getMaterialInstanceAt(ri, 0)->getMaterial()->getBlendingMode();
            rcm.setCastShadows(ri,
                    blendingMode == BlendingMode::OPAQUE || blendingMode == BlendingMode::MASKED);
            scene->addEntity(renderable);
        }
    }

    auto& em = EntityManager::get();
    g_lights.push_back(em.create());

    LightManager::Builder(LightManager::Type::SUN)
            .color(Color::toLinear<ACCURATE>(sRGBColor(0.98f, 0.92f, 0.89f)))
            .intensity(110000)
            .direction({ 0.7, -1, -0.8 })
            .sunAngularRadius(1.9f)
            .castShadows(true)
            .build(*engine, g_lights.back());
    scene->addEntity(g_lights.back());

    lcm.setShadowOptions(lcm.getInstance(g_lights[0]), {
            .screenSpaceContactShadows = true });

    view->setAmbientOcclusionOptions({ .enabled = true });
    view->setBloomOptions({ .enabled = true });

    if (g_moreLights) {
       g_lights.push_back(em.create());
        LightManager::Builder(LightManager::Type::POINT)
                .color(Color::toLinear<ACCURATE>(sRGBColor(0.98f, 0.92f, 0.89f)))
                .intensity(1000.0f, LightManager::EFFICIENCY_LED)
                .position({ 0.0f, -0.2f, -3.0f })
                .falloff(4.0f)
                .build(*engine, g_lights.back());

        g_lights.push_back(em.create());
        LightManager::Builder(LightManager::Type::FOCUSED_SPOT)
                .color(Color::toLinear<ACCURATE>(sRGBColor(0.98f, 0.12f, 0.19f)))
                .intensity(2000.0f, LightManager::EFFICIENCY_LED)
                .position({ 0.6f, 0.6f, -3.2f })
                .direction({ -1.0f, 0.0f, 0.0f })
                .spotLightCone(static_cast<float>(M_PI / 8), static_cast<float>((M_PI / 8) * 1.1))
                .falloff(4.0f)
                .castShadows(true)
                .build(*engine, g_lights.back());

        g_lights.push_back(em.create());
        LightManager::Builder(LightManager::Type::POINT)
                .color(Color::toLinear<ACCURATE>(sRGBColor(0.18f, 0.12f, 0.89f)))
                .intensity(1000.0f, LightManager::EFFICIENCY_LED)
                .position({ -0.6f, 0.3f, -3.2f })
                .falloff(2.0f)
                .build(*engine, g_lights.back());

        g_lights.push_back(em.create());
        LightManager::Builder(LightManager::Type::POINT)
                .color(Color::toLinear<ACCURATE>(sRGBColor(0.88f, 0.82f, 0.29f)))
                .intensity(1000.0f, LightManager::EFFICIENCY_LED)
                .position({ 0.0f, 1.5f, -3.5f })
                .falloff(2.0f)
                .build(*engine, g_lights.back());

        g_lights.push_back(em.create());
        LightManager::Builder(LightManager::Type::FOCUSED_SPOT)
                .color(Color::toLinear<ACCURATE>(sRGBColor(0.12f, 0.98f, 0.19f)))
                .intensity(2000.0f, LightManager::EFFICIENCY_LED)
                .position({ 0.0f, 0.6f, -3.2f })
                .direction({  1.0f, 0.0f, 0.0f })
                .spotLightCone(static_cast<float>(M_PI / 8), static_cast<float>((M_PI / 8) * 1.1))
                .falloff(4.0f)
                .castShadows(true)
                .build(*engine, g_lights.back());

        for (const auto& light : g_lights) {
            scene->addEntity(light);
            const LightManager::Instance& instance = lcm.getInstance(light);
            if (!lcm.isDirectional(instance)) {
                g_spheres.emplace_back(*engine, FilamentApp::get().getDefaultMaterial());
                g_spheres.back()
                         .setRadius(0.025f)
                         .setPosition(lcm.getPosition(instance));

                auto mi = g_spheres.back().getMaterialInstance();
                mi->setParameter("baseColor", RgbaType::LINEAR, LinearColorA{ lcm.getColor(instance), 100.0f });
                mi->setParameter("roughness", 0.2f);
                mi->setParameter("metallic", 0.0f);
            }
        }

        for (const auto& sphere : g_spheres) {
            scene->addEntity(sphere.getSolidRenderable());
        }
    }

    if (g_discoBall) {
        IcoSphere sphere(2);
        auto const& vertices = sphere.getVertices();
        auto n = vertices.size();
        g_lights.resize(g_lights.size() + n);
        slog.d << "light count = " << n << io::endl;

        Entity discoBall = em.create();
        tcm.create(discoBall, {}, mat4f::translation(float3{ 0, 3, -14 }));
        auto parent = tcm.getInstance(discoBall);

        for (size_t i = 0, c = n; i < c; i++) {
            g_lights.push_back(em.create());
            LightManager::Builder(LightManager::Type::FOCUSED_SPOT)
                    .color(abs(vertices[i]))
                    .intensity(1000.0f, LightManager::EFFICIENCY_HALOGEN)
                    .direction(vertices[i])
                    .spotLightCone(0.0174f * 0.5f, 0.0174f * 2.0f)
                    .falloff(20.0f)
                    .build(*engine, g_lights.back());

            tcm.create(g_lights.back(), parent);

            scene->addEntity(g_lights.back());
        }
        g_discoBallEntity = discoBall;

        g_spheres.emplace_back(*engine, FilamentApp::get().getDefaultMaterial());
        g_spheres.back().setRadius(0.2f);
        auto mi = g_spheres.back().getMaterialInstance();
        mi->setParameter("baseColor", RgbaType::LINEAR, LinearColorA{ 1, 1, 1, 1 });
        mi->setParameter("roughness", 0.01f);
        mi->setParameter("metallic", 1.0f);
        scene->addEntity(g_spheres.back().getSolidRenderable());
        // parent the sphere representing the disco ball to the discoball transform -- w00t.
        tcm.setParent(tcm.getInstance(g_spheres.back().getSolidRenderable()), tcm.getInstance(discoBall));
    }

    g_meshAabb.reset(new Cube(*engine, FilamentApp::get().getTransparentMaterial(), {0,0,1}));

    // First object in the scene
    Entity object = g_meshSet->getRenderables()[1];

    // Get its AABB and add it to the scene
    RenderableManager::Instance ri = rcm.getInstance(object);
    if (ri) {
        g_meshAabb->mapAabb(*engine, rcm.getAxisAlignedBoundingBox(ri));
        scene->addEntity(g_meshAabb->getWireFrameRenderable());
        scene->addEntity(g_meshAabb->getSolidRenderable());
    }

    // now transform the aabb's renderable by the object's transform
    tcm.setParent(tcm.getInstance(g_meshAabb->getSolidRenderable()),  tcm.getInstance(object));
    tcm.setParent(tcm.getInstance(g_meshAabb->getWireFrameRenderable()),  tcm.getInstance(object));
    rcm.setLayerMask(rcm.getInstance(g_meshAabb->getSolidRenderable()), 0x3, 0x2);
    rcm.setLayerMask(rcm.getInstance(g_meshAabb->getWireFrameRenderable()), 0x3, 0x2);

    if (g_shadowPlane) {
        Material* shadowMaterial = Material::Builder()
                .package(RESOURCES_GROUNDSHADOW_DATA, RESOURCES_GROUNDSHADOW_SIZE)
                .build(*engine);
        shadowMaterial->setDefaultParameter("strength", 0.7f);

        const static uint32_t indices[] = {
                0, 1, 2, 2, 3, 0
        };

        const static filament::math::float3 vertices[] = {
                { -10, 0, -10 },
                { -10, 0,  10 },
                {  10, 0,  10 },
                {  10, 0, -10 },
        };

        short4 tbn = filament::math::packSnorm16(
                mat3f::packTangentFrame(
                        filament::math::mat3f{
                                float3{ 1.0f, 0.0f, 0.0f },
                                float3{ 0.0f, 0.0f, 1.0f },
                                float3{ 0.0f, 1.0f, 0.0f }
                        }
                ).xyzw);

        const static filament::math::short4 normals[] { tbn, tbn, tbn, tbn };

        VertexBuffer* vertexBuffer = VertexBuffer::Builder()
                .vertexCount(4)
                .bufferCount(2)
                .attribute(VertexAttribute::POSITION, 0, VertexBuffer::AttributeType::FLOAT3)
                .attribute(VertexAttribute::TANGENTS, 1, VertexBuffer::AttributeType::SHORT4)
                .normalized(VertexAttribute::TANGENTS)
                .build(*engine);

        vertexBuffer->setBufferAt(*engine, 0, VertexBuffer::BufferDescriptor(
                vertices, vertexBuffer->getVertexCount() * sizeof(vertices[0])));
        vertexBuffer->setBufferAt(*engine, 1, VertexBuffer::BufferDescriptor(
                normals, vertexBuffer->getVertexCount() * sizeof(normals[0])));

        IndexBuffer* indexBuffer = IndexBuffer::Builder()
                .indexCount(6)
                .build(*engine);

        indexBuffer->setBuffer(*engine, IndexBuffer::BufferDescriptor(
                indices, indexBuffer->getIndexCount() * sizeof(uint32_t)));

        Entity planeRenderable = em.create();
        RenderableManager::Builder(1)
                .boundingBox({{ 0, 0, 0 },
                              { 10, 1e-4f, 10 }})
                .material(0, shadowMaterial->getDefaultInstance())
                .geometry(0, RenderableManager::PrimitiveType::TRIANGLES,
                        vertexBuffer, indexBuffer, 0, 6)
                .culling(false)
                .receiveShadows(true)
                .castShadows(false)
                .build(*engine, planeRenderable);

        scene->addEntity(planeRenderable);

        tcm.setTransform(tcm.getInstance(planeRenderable),
                filament::math::mat4f::translation(float3{ 0, -1, -4 }));
    }
}
#pragma clang diagnostic pop

int main(int argc, char* argv[]) {
    int option_index = handleCommandLineArgments(argc, argv, &g_config);
    int num_args = argc - option_index;
    if (num_args < 1) {
        printUsage(argv[0]);
        return 1;
    }

    for (int i = option_index; i < argc; i++) {
        utils::Path filename = argv[i];
        if (!filename.exists()) {
            std::cerr << "file " << argv[i] << " not found!" << std::endl;
            return 1;
        }
        g_filenames.push_back(filename);
    }

    g_config.title = "Lightbulb";
    FilamentApp& filamentApp = FilamentApp::get();

    double lastTime = 0;
    if (g_discoBall) {
        filamentApp.animate([lastTime](filament::Engine* engine, filament::View*, double now) mutable {
            auto& tcm = engine->getTransformManager();
            tcm.setTransform(tcm.getInstance(g_discoBallEntity),
                    mat4f::translation(float3{ 0, 2, -4, }) *
                                                            mat4f::rotation(g_discoAngle,
                                                                    float3{ 0, 1, 0 })
            );
            if (lastTime != 0) {
                double dT = now - lastTime;
                g_discoAngle += g_discoAngularSpeed * dT;
            }
            lastTime = now;
        });
    }

    filamentApp.run(g_config, setup, cleanup, {}, preRender);

    return 0;
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.openni.android</title>
<meta name="date" content="2014-07-17">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

org.openni.android

Interfaces

OpenNIHelper.DeviceOpenListener

Classes

OpenNIHelper

OpenNIView

redpajama_set_name: RedPajamaGithub


text:
var path = require("path");
var dirname = path.dirname;
var loaderUtils = require("loader-utils");
var nodeResolve = require("resolve").sync;
var walk = require('pug-walk');

module.exports = function(source) {
	this.cacheable && this.cacheable();

	var modulePaths = {};
	modulePaths.pug = require.resolve("pug");
	modulePaths.load = nodeResolve("pug-load", {basedir: dirname(modulePaths.pug)});
	modulePaths.runtime = nodeResolve("pug-runtime", {basedir: dirname(modulePaths.pug)});

	var pug = require(modulePaths.pug);
	var load = require(modulePaths.load);

	var req = loaderUtils.getRemainingRequest(this).replace(/^!/, "");

	var query = loaderUtils.getOptions(this) || {};

	var loadModule = this.loadModule;
	var resolve = this.resolve;
	var loaderContext = this;
	var callback;

	var fileContents = {};
	var filePaths = {};

	var missingFileMode = false;
	function getFileContent(context, request) {
		request = loaderUtils.urlToRequest(request, query.root)
		var baseRequest = request;
		var filePath;

		filePath = filePaths[context + " " + request];
		if(filePath) return filePath;

		var isSync = true;
		resolve(context, request, function(err, _request) {
			if(err) {
				resolve(context, request, function(err2, _request) {
					if(err2) return callback(err2);

					request = _request;
					next();
				});
				return;
			}

			request = _request;
			next();
			function next() {
				loadModule("-!" + path.join(__dirname, "stringify.loader.js") + "!" + request, function(err, source) {
					if(err) return callback(err);

					filePaths[context + " " + baseRequest] = request;
					fileContents[request] = JSON.parse(source);

					if(!isSync) {
						run();
					}
				});
			}
		});

		filePath = filePaths[context + " " + baseRequest];
		if(filePath) return filePath;

		isSync = false;
		missingFileMode = true;
		throw "continue";
	}

	var plugin = loadModule ? {
		postParse: function (ast) {
			return walk(ast, function (node) {
				if ([
					"Mixin",
					"MixinBlock",
					"NamedBlock"
				].indexOf(node.type) !== -1) {
					ast._mustBeInlined = true;
				}
			});
		},
		resolve: function (request, source) {
			if (!callback) {
				callback = loaderContext.async();
			}

			if (!callback) {
				return load.resolve(request, source);
			}

			var context = dirname(source.split("!").pop());
			return getFileContent(context, request);
		},
		read: function (path) {
			if (!callback) {
				return load.read(path);
			}

			return fileContents[path];
		},
		postLoad: function postLoad(ast) {
			return walk(ast, function (node, replace) {
				if (node.file && node.file.ast) {
					postLoad(node.file.ast);
				}

				if (node.type === "Include") {
					if (node.file.ast._mustBeInlined) {
						ast._mustBeInlined = true;
					}
				}
			}, function (node, replace) {
				if (node.type === "Include" && !(node.block && node.block.nodes.length) && !node.file.ast._mustBeInlined) {
					replace({
						type: "Code",
						val: "require(" + loaderUtils.stringifyRequest(loaderContext, node.file.fullPath) + ").call(this, locals)",
						buffer: true,
						mustEscape: false,
						isInline: false,
						line: node.line,
						filename: node.filename
					});
				}
			});
		}
	} : {};

	run();
	function run() {
		try {
			var tmplFunc = pug.compileClient(source, {
				filename: req,
				doctype: query.doctype || "html",
				pretty: query.pretty,
				self: query.self,
				compileDebug: loaderContext.debug || false,
				globals: ["require"].concat(query.globals || []),
				name: "template",
				inlineRuntimeFunctions: false,
				filters: query.filters,
				plugins: [
					plugin
				].concat(query.plugins || [])
			});
		} catch(e) {
			if(missingFileMode) {
				// Ignore, it'll continue after async action
				missingFileMode = false;
				return;
			}
			loaderContext.callback(e);
			return;
		}
		var runtime = "var pug = require(" + loaderUtils.stringifyRequest(loaderContext, "!" + modulePaths.runtime) + ");\n\n";
		loaderContext.callback(null, runtime + tmplFunc.toString() + ";\nmodule.exports = template;");
	}
}


text:
AnswerPage::AnswerPage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AnswerPage)
{
    ui->setupUi(this);
}

AnswerPage::~AnswerPage()
{
    delete ui;
}

AnswerStatus AnswerPage::load(
        const Section& section, const Solution& solution, int caseIndex)
{
    this->caseIndex = caseIndex;
    const Case& caseValue = section.cases[caseIndex];
    ui->titleLabel->setText("Кейс \"" + caseValue.name + "\"");
    if (caseIndex == 0)
        ui->prevButton->setEnabled(false);
    if (caseIndex == section.cases.size() - 1)
        ui->nextButton->setEnabled(false);

    auto sectionDir = section.dir();
    bool hasErrors = false;
    auto questionHTML = readHTML(sectionDir.absoluteFilePath(caseValue.questionFileName));
    if (questionHTML.isEmpty()) {
        hasErrors = true;
        ui->questionBrowser->setPlainText("Произошла ошибка при загрузке текста вопроса.");
    } else {
        setImageAndHTML(section.dir(), caseValue.questionImage,
                        questionHTML, ui->questionBrowser);
    }

    TextExplorer* answerExplorer = new TextExplorer(this);
    answerExplorer->setTitle("Ответ пользователя");
    Answer answer = solution.answer(caseValue);
    bool hasFinalAnswer = answer.isFinal();
    if (hasFinalAnswer) {
        if (!answerExplorer->load(
                solution.dir().absoluteFilePath(answer.fileName))) {
            hasErrors = true;
            answerExplorer->setPlainText("Произошла ошибка при загрузке ответа пользователя.");
        }
    } else {
        answerExplorer->setPlainText("Пользователь еще не ответил на данный вопрос.");
    }
    ui->tabWidget->addTab(answerExplorer, "Ответ пользователя");

    TextExplorer* mentrorAnswerExplorer = new TextExplorer(this);
    mentrorAnswerExplorer->setTitle("Ответ наставника");
    if (!mentrorAnswerExplorer->load(
            sectionDir, caseValue.answerFileName, caseValue.answerImage)) {
        hasErrors = true;
        mentrorAnswerExplorer->setPlainText("Произошла ошибка при загрузке ответа наставника.");
    }
    ui->tabWidget->addTab(mentrorAnswerExplorer, "Ответ наставника");

    if (hasErrors)
        return AnswerStatus::Error;
    return hasFinalAnswer ? AnswerStatus::OK : AnswerStatus::Absent;
}

void AnswerPage::on_prevButton_clicked()
{
    emit requestedCase(caseIndex - 1);
}

void AnswerPage::on_nextButton_clicked()
{
    emit requestedCase(caseIndex + 1);
}


text:
<?php
use yii\helpers\Url;
/* @var $this yii\web\View */
$this->title = 'RDRPS';
?>

        <img alt="RDRPS logo" src="<?= Url::base() ?>/<?= Url::to('images/RDRLogo.gif') ?>">

Royal Deeside Railway Preservation Society

        <a href="<?= Url::to(['project/index']) ?>" class="btn btn-default btn-lg">View Project Statuses
        <a href="<?= Url::to(['user/volunteer']) ?>" class="btn btn-default btn-lg">Register Volunteering Interest
        <a href="<?= Url::to(['project-activity/index']) ?>" class="btn btn-default btn-lg">View Upcoming Activities


text:
This project contains an example of an application for iPhone and iPad that employs the [Lightstreamer iOS Client library](http://www.lightstreamer.com/docs/client_ios_api/index.html), with use of mobile push notifications (MPN).

A simpler version, without mobile push notifications support, is also available: [Lightstreamer - Stock-List Demo - iOS Client](https://github.com/Weswit/Lightstreamer-example-StockList-client-ios).

## Live Demo

[![screenshot](screenshot_newlarge.png)](https://itunes.apple.com/us/app/lightstreamer-stock-list-apns/id430328811?mt=8)

###[![](http://demos.lightstreamer.com/site/img/play.png) View live demo](https://itunes.apple.com/us/app/lightstreamer-stock-list-apns/id430328811?mt=8)

## Details

This app, compatible with both iPhone and iPad, is an Objective-C version of the [Stock-List Demos](https://github.com/Weswit/Lightstreamer-example-Stocklist-client-javascript).

This app uses the iOS Client API for Lightstreamer to handle the communications with Lightstreamer Server. A simple user interface is implemented to display the real-time data received from Lightstreamer Server. Additionally, the user interface provides means to activate and deactivate mobile push notifications for specific stock quotes.

## Install

Binaries for the application are not provided, but it may be downloaded from the App Store at [this address](https://itunes.apple.com/us/app/lightstreamer-stock-list-apns/id430328811?mt=8). The downloaded app will connect to Lightstreamer's online demo server.

## Build

A full Xcode project specification, ready for compilation of the app sources, is provided. Please recall that you need a valid iOS Developer Program membership to run or debug your app on a test device.

### Getting Started

Before you can build this demo, you should complete this project with the Lighstreamer iOS Client library. Follow these steps:

* Drop into the `Lightstreamer client for iOS/lib` folder of this project the *Lightstreamer_iOS_client.a* file from the `/DOCS-SDKs/sdk_client_ios/lib` of [Lightstreamer distribution version 6.0 or greater](http://www.lightstreamer.com/download).
* Drop into the `Lightstreamer client for iOS/include` folder of this project all the include files from the `/DOCS-SDKs/sdk_client_ios/include` of [Lightstreamer distribution version 6.0 or greater](http://www.lightstreamer.com/download).

Done this, the project should compile with no errors.

### Compile and Run

A full local deploy of this app requires a Lightstreamer Server 6.0 or greater installation with appropriate Mobile Push Notifications (MPN) module configuration. A detailed step by step guide for setting up the server and configuring the client is available in the README of the following project:

* [Lightstreamer - MPN Stock-List Demo Metadata - Java Adapter](https://github.com/Weswit/Lightstreamer-example-MPNStockListMetadata-adapter-java)

## See Also

### Lightstreamer Adapters Needed by This Demo Client

* [Lightstreamer - Stock- List Demo - Java Adapter](https://github.com/Weswit/Lightstreamer-example-Stocklist-adapter-java)
* [Lightstreamer - MPN Stock-List Demo Metadata - Java Adapter](https://github.com/Weswit/Lightstreamer-example-MPNStockListMetadata-adapter-java)

### Related Projects

* [Lightstreamer - Stock-List Demos - HTML Clients](https://github.com/Weswit/Lightstreamer-example-Stocklist-client-javascript)
* [Lightstreamer - Stock-List Demo - iOS Client](https://github.com/Weswit/Lightstreamer-example-StockList-client-ios)
* [Lightstreamer - Stock-List Demo with GCM Push Notifications - Android Client](https://github.com/Weswit/Lightstreamer-example-MPNStockList-client-android)
* [Lightstreamer - Basic Stock-List Demo - OS X Client](https://github.com/Weswit/Lightstreamer-example-StockList-client-osx)
* [Lightstreamer - Basic Stock-List Demo - Windows Phone Client](https://github.com/Weswit/Lightstreamer-example-StockList-client-winphone)

## Lightstreamer Compatibility Notes

* Compatible with Lightstreamer iOS Client Library version 1.4 or newer.
* For Lightstreamer Allegro (+ iOS Client API support), Presto, Vivace, version 6.0 or greater.


text:
@interface SDLDeviceStatus : SDLRPCStruct {}

-(id) init;
-(id) initWithDictionary:(NSMutableDictionary*) dict;

@property(strong) NSNumber* voiceRecOn;
@property(strong) NSNumber* btIconOn;
@property(strong) NSNumber* callActive;
@property(strong) NSNumber* phoneRoaming;
@property(strong) NSNumber* textMsgAvailable;
@property(strong) SDLDeviceLevelStatus* battLevelStatus;
@property(strong) NSNumber* stereoAudioOutputMuted;
@property(strong) NSNumber* monoAudioOutputMuted;
@property(strong) SDLDeviceLevelStatus* signalLevelStatus;
@property(strong) SDLPrimaryAudioSource* primaryAudioSource;
@property(strong) NSNumber* eCallEventActive;

@end


text:
package fr.pilato.elasticsearch.crawler.fs.beans;

/**
 * Represents a folder we have visited
 */
public class Folder {

    public static final String CONTENT_TYPE = "text/directory";

    private Path path;
    private File file;

    public Folder() {
        path = new Path();
        file = new File();
        file.setContentType(CONTENT_TYPE);
    }

    /**
     * Build a folder with a single ctor call
     * @param name      The folder name
     * @param root      Root of the folder
     * @param real      The full path to the folder
     * @param virtual   The virtual path from the root
     */
    public Folder(String name, String root, String real, String virtual) {
        path = new Path();
        path.setRoot(root);
        path.setReal(real);
        path.setVirtual(virtual);
        file = new File();
        file.setFilename(name);
        file.setContentType(CONTENT_TYPE);
    }

    public Path getPath() {
        return path;
    }

    public void setPath(Path path) {
        this.path = path;
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }
}


text:
demo: main.o utils.o interface.o
	gcc -o demo main.o utils.o interface.o

main.o: utils.h interface.h
utils.o: utils.h defs.h
interface.o: interface.h defs.h

# WARNING
# How does make know to use the C compiler to make utils.o?
# An overly simplified  answer is that it looks in the directory for a
# file whose basename is utils and then looks at the extension and applies
# the rule. If there had been a file named utils.F instead of utils.c, it would
# have used the Fortran compiler. If you have two source files, say one named
# utils.F and the other named utils.c, it will use the C compiler, because the
# rule for '.c' files precedes the rule for 'F' files in its list f rules.
# You should make sure you never have this situation.


text:
- *click_to_focus* is now a button name. Specifying a boolean is deprecated but will still work (`true` is equivalent to `button1`).

## Additions

- `node -r` now accepts a relative fraction argument.
- An option was added to `query -{M,D,N}` in order to output names instead of IDs: `--names`.
- New rule consequence: `rectangle=WxH+X+Y`.
- New settings: `swallow_first_click` and `directional_focus_tightness`.

# From 0.9.1 to 0.9.2

## Changes

- Monitors, desktops and nodes have unique IDs, `bspc query -{N,D,M}` returns IDs and events reference objects by ID instead of name.
- `bspc` fails verbosely and only returns a single non-zero exit code.
- The `DIR` descriptor is based on [right-window](https://github.com/ntrrgc/right-window).
- The `CYCLE_DIR` descriptor isn't limited to the current desktop/monitor anymore. (You can emulate the previous behavior by appending a `.local` modifier to the selector.)
- `bspc query -{N,D,M}` accepts an optional reference argument used by certain descriptors/modifiers.
- Monitors are ordered visually by default.
- The following settings: `border_width`, `window_gap` and `*_padding` behave as expected.
- External rules also receives the monitor, desktop and node selectors computed from the built-in rules stage as subsequent arguments.
- The `focus_follows_pointer` setting is implemented via enter notify events.

## Additions

- Nodes can be hidden/shown via the new `hidden` flag.
- Node receptacles can be inserted with `node -i`. An example is given in `git show e8aa679`.
- Non-tiled nodes can be moved/resized via `node -{v,z}`.
- The reference of a selector can be set via the `{NODE,DESKTOP,MONITOR}_SEL#` prefix, example: `bspc node 0x0080000c#south -c` will close the node at the south of `0x0080000c`.
- Node descriptors: `<node_id>`, `pointed`.
- Node modifiers: `hidden`, `descendant_of`, `ancestor_of`, `window`, `active`. Example: `bspc query -N 0x00400006 -n .descendant_of` returns the descendants of `0x00400006`.
- Desktop descriptor: `<desktop_id>`.
- Monitor descriptor: `<monitor_id>`.
- Settings: `pointer_motion_interval`, `pointer_modifier`, `pointer_action{1,2,3}`, `click_to_focus`, `honor_size_hints`.
- Event: `pointer_action`.
- ICCCM/EWMH atoms: `WM_STATE`, `_NET_WM_STRUT_PARTIAL`.
- `bspc` shell completions for `fish`.

## Removals

- The `pointer` domain. Pointer actions are handled internally. You need to remove any binding that uses this domain from your `sxhkdrc`.
- Settings: `history_aware_focus`, `focus_by_distance`. Both settings are merged into the new `DIR` implementation.
- `monitor -r|--remove-desktops`: use `desktop -r|--remove` instead.
- `wm -r|--remove-monitor`: use `monitor -r|--remove` instead.

# From 0.9 to 0.9.1

## Overview

All the commands that acted on leaves can now be applied on internal nodes (including focusing and preselection). Consequently, the *window* domain is now a *node* domain. Please note that some commands are applied to the leaves of the tree rooted at the selected node and not to the node itself.

## Changes

- All the commands that started with `window` now start with `node`.
- `-W|--windows`, `-w|--window`, `-w|--to-window` are now `-N|--nodes`, `-n|--node`, `-n|--to-node`.
- We now use cardinal directions: `west,south,north,east` instead of `left,down,up,right` (in fact the latter is just plain wrong: the `up,down` axis is perpendicular to the screen).
- The `WINDOW_SEL` becomes `NODE_SEL` and now contains a `PATH` specifier to select internal nodes.
- The `control` domain is renamed to `wm`.
- `restore -{T,H,S}` was unified into `wm -l|--load-state` and `query -{T,H,S}` into `wm -d|--dump-state`.
- `control --subscribe` becomes `subscribe`.
- `node --toggle` (previously `window --toggle`) is split into `node --state` and `node --flag`.
- The preselection direction (resp. ratio) is now set with `node --presel-dir|-p` (resp. `node --presel-ratio|-o`).
- The following desktop commands: `--rotate`, `--flip`, `--balance`, `--equalize`, `--circulate` are now node commands.
- `query -T ...` outputs JSON.
- `query -{M,D,N}`: the descriptor part of the selector is now optional (e.g.: `query -D -d .urgent`).
- Many new modifiers were added, some were renamed. The opposite of a modifier is now expressed with the `!` prefix (e.g.: `like` becomes `same_class`, `unlike` becomes `!same_class`, etc.).
- Modifiers can now be applied to any descriptor (e.g.: `query -N -n 0x80000d.floating`).
- `wm -l` (previously `restore -T`) will now destroy the existing tree and restore from scratch instead of relying on existing monitors and desktops.
- `subscribe` (previously `control --subscribe`) now accepts arguments and can receive numerous events from different domains (see the *EVENTS* section of the manual).
- `rule -a`: it is now possible to specify the class name *and* instance name (e.g.: `rule -a Foo:bar`).
- `presel_border_color` is now `presel_feedback_color`.
- `bspwm -v` yields an accurate version.
- The monitors are sorted, by default, according to the natural visual hierarchy.

## Additions

### Settings

- `single_monocle`.
- `paddingless_monocle`.

### Commands

- `{node,desktop} --activate`.
- `node --layer`.
- `desktop --bubble`.
- `wm {--add-monitor,--remove-monitor}`.
- `monitor --rectangle`.

## Removals

### Commands

- `desktop --toggle`
- `desktop --cancel-presel`
- `control --toggle-visibility`.

### Settings

- `apply_floating_atom`.
- `auto_alternate`.
- `auto_cancel`.
- `focused_locked_border_color`
- `active_locked_border_color`
- `normal_locked_border_color`
- `focused_sticky_border_color`
- `active_sticky_border_color`
- `normal_sticky_border_color`
- `focused_private_border_color`
- `active_private_border_color`
- `normal_private_border_color`
- `urgent_border_color`

## Message Translation Guide

0.9                                      | 0.9.1
-----------------------------------------|----------------------------------
`{left,down,up,right}`                   | `{west,south,north,east}`
`window -r`                              | `node -o` (`node -r` also exists)
`window -e DIR RATIO`                    | `node @DIR -r RATIO`
`window -R DIR DEG`                      | `node @DIR -R DEG`
`window -w`                              | `node -n`
`desktop DESKTOP_SEL -R DEG`             | `node @DESKTOP_SEL:/ -R DEG`
`desktop DESKTOP_SEL -E`                 | `node @DESKTOP_SEL:/ -E`
`desktop DESKTOP_SEL -B`                 | `node @DESKTOP_SEL:/ -B`
`desktop DESKTOP_SEL -C forward|backward`| `node @DESKTOP_SEL:/ -C forward|backward`
`desktop DESKTOP_SEL --cancel-presel`    | `bspc query -N -d DESKTOP_SEL | xargs -I id -n 1 bspc node id -p cancel`
`window -t floating`                     | `node -t ~floating`
`query -W -w`                            | `query -N -n .leaf`
`query -{T,H,S}`                         | `wm -d`
`restore -{T,H,S}`                       | `wm -l`


text:
package org.apache.tinkerpop.gremlin.process.traversal;

import java.util.function.BiPredicate;

/**
 * Predefined {@code Predicate} values that can be used as {@code String} filters.
 *
 * @author Daniel Kuppitz (http://gremlin.guru)
 */
public class TextP extends P<String> {

    @SuppressWarnings("WeakerAccess")
    public TextP(final BiPredicate<String, String> biPredicate, final String value) {
        super(biPredicate, value);
    }

    @Override
    public boolean equals(final Object other) {
        return other instanceof TextP && super.equals(other);
    }

    @Override
    public String toString() {
        return null == this.originalValue ? this.biPredicate.toString() : this.biPredicate.toString() + "(" + this.originalValue + ")";
    }

    @Override
    public TextP negate() {
        return new TextP(this.biPredicate.negate(), this.originalValue);
    }

    public TextP clone() {
        return (TextP) super.clone();
    }

    //////////////// statics

    /**
     * Determines if String does start with the given value.
     *
     * @since 3.4.0
     */
    public static TextP startingWith(final String value) {
        return new TextP(Text.startingWith, value);
    }

    /**
     * Determines if String does not start with the given value.
     *
     * @since 3.4.0
     */
    public static TextP notStartingWith(final String value) {
        return new TextP(Text.notStartingWith, value);
    }

    /**
     * Determines if String does start with the given value.
     *
     * @since 3.4.0
     */
    public static TextP endingWith(final String value) {
        return new TextP(Text.endingWith, value);
    }

    /**
     * Determines if String does not start with the given value.
     *
     * @since 3.4.0
     */
    public static TextP notEndingWith(final String value) {
        return new TextP(Text.notEndingWith, value);
    }

    /**
     * Determines if String does contain the given value.
     *
     * @since 3.4.0
     */
    public static TextP containing(final String value) {
        return new TextP(Text.containing, value);
    }

    /**
     * Determines if String does not contain the given value.
     *
     * @since 3.4.0
     */
    public static TextP notContaining(final String value) {
        return new TextP(Text.notContaining, value);
    }
}


text:
'use strict';

const path = require('path');
const electron = require('electron');
const {app, globalShortcut, ipcMain, BrowserWindow} = electron;
const addon = require('./../build/Release/addon.node');

let win, screenCaptureMode = false;

app.on('ready', () => {
  globalShortcut.register('CmdOrCtrl+Insert', () => {
    if (screenCaptureMode) {
      return;
    }

    /**
    globalShortcut.register('Esc', () => {
      console.log('fdg');
    });
    */

    screenCaptureMode = true;
    //let displays = electron.screen.getCursorScreenPoint();
    //console.log('X:' + displays.x + ' Y:' + displays.y);
    win.minimize();
    console.log(`screencall: ${addon.CaptureScreen()}`);
    screenCaptureMode = false;

    //globalShortcut.unregister('Esc');
  });

  ipcMain.on('restart', function() {
    app.relaunch();
    app.quit();
  });
  ipcMain.on('window-minimize', function() {
    win.minimize();
  });
  ipcMain.on('window-maximize', function() {
    win.maximize();
  });
  ipcMain.on('quit', function() {
    app.quit();
  });

  win = new BrowserWindow({
    height: 500,
    width: 450,
    'minHeight': 300,
    'minWidth': 400,
    titleBarStyle : 'hidden-inset',
    frame: false,
    icon: path.join(__dirname, '..', 'public', 'images', 'logo.png')
  });
  win.setMenuBarVisibility(false);
  win.loadURL('file://' + path.join(__dirname, '..', 'view', 'index.html'));
  win.on('closed', () => {
    win = null
  });
  win.once('ready-to-show', () => {
    win.show()
  });
  win.openDevTools();
});


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <title>What is Arduino? | CHEM 370 Lab Manual</title>
  <meta name="description" content="Lab Manual for CHEM 370: Instrumental Analysis Laboratory" />
  <meta name="generator" content="bookdown 0.12 and GitBook 2.6.7" />

  <meta property="og:title" content="What is Arduino? | CHEM 370 Lab Manual" />
  <meta property="og:type" content="book" />

  <meta property="og:image" content="images/cover-image-mass-spec.png" />
  <meta property="og:description" content="Lab Manual for CHEM 370: Instrumental Analysis Laboratory" />

  <meta name="twitter:card" content="summary" />
  <meta name="twitter:title" content="What is Arduino? | CHEM 370 Lab Manual" />

  <meta name="twitter:description" content="Lab Manual for CHEM 370: Instrumental Analysis Laboratory" />
  <meta name="twitter:image" content="images/cover-image-mass-spec.png" />

<meta name="author" content="Al Fischer, PhD" />

  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="apple-mobile-web-app-capable" content="yes" />
  <meta name="apple-mobile-web-app-status-bar-style" content="black" />

<link rel="prev" href="preface.html">
<link rel="next" href="ok-but-what-is-teensy.html">

<link href="libs/gitbook-2.6.7/css/style.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-table.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-bookdown.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-highlight.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-search.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-fontsettings.css" rel="stylesheet" />

<link rel="stylesheet" href="css/style.css" type="text/css" />

CHEM 370 Main Page

Preface

What is Arduino?

OK, but what is Teensy?

Using this Book

Code

Notes and Warnings

Is this work dangerous?

Additional Resources

1 UV-visible Spectroscopy

Introduction

Methods

1.0.1 Standards

1.0.2 Samples

1.0.3 Instrumentation

Reference

Materials

2 Gas Chromatography with Thermal Conductivity Detection (GC-TCD)

Introduction

3 Rotation A: e-Cigarette Liquid

Introduction

GC-MS

3.0.1 Sample Preparation

Instrumentation

HPLC

Standard Preparation

Instrumentation: Standards

Sample Preparation

Instrumentation: Samples

Flame AA

FT-IR

Data Processing

3.0.2 HPLC

3.0.3 Standard Curve

3.0.4 Samples

4 Rotation B: Acetaminophen

Introduction

4.1 HPLC

Safety

Standard Preparation

Sample Preparation

Instrumentation

Waste Disposal and Cleanup

Data Processing

4.2 FT-IR

Safety

Sample Preparation

Instrumentation

Waste Disposal and Cleanup

Data Processing

4.3 GC-MS

4.4 Flame AA

5 Octave (MATLAB) Cookbook

Introduction

Import Data from CSV

Find Peak Area

. Published with bookdown
 <link href="https://fonts.googleapis.com/css?family=IBM+Plex+Sans:200&display=swap" rel="stylesheet">

            CHEM 370 Lab Manual

What is Arduino?

Arduino is an open-source platform for developing interactive electronic devices. Arduinos of various flavors are used for all variety of things, from controlling motors and lights to reading data from sensors. Exercise 1 will provide a more thorough overview of Arduino, and you will get experience programming Arduino using the online utility provided by Tinkercad.


text:
#import "IDEViewController.h"

#import "DVTReplacementViewDelegate-Protocol.h"
#import "DVTStatefulObject-Protocol.h"

@class DVTBorderedView, DVTChooserView, DVTExtension, DVTObservingToken, DVTReplacementView, IDEDocContentAreaViewController, IDENavigableItem, NSArrayController, NSIndexSet, NSString;

@interface IDEDocNavigatorArea : IDEViewController <DVTReplacementViewDelegate, DVTStatefulObject>
{
    DVTChooserView *_chooserView;
    DVTBorderedView *_borderedView;
    DVTReplacementView *_replacementView;
    NSArrayController *_choicesController;
    DVTExtension *_currentExtension;
    DVTObservingToken *_selectedItemToken;
    IDENavigableItem *_selectedNavigableItem;
    NSIndexSet *_chooserViewSelectionIndexes;
    NSString *_UUID;
    id _selectedItem;
    IDEDocContentAreaViewController *_contentAreaViewController;
}

+ (long long)version;
+ (void)configureStateSavingObjectPersistenceByName:(id)arg1;
+ (id)keyPathsForValuesAffectingCurrentNavigator;
@property __weak IDEDocContentAreaViewController *contentAreaViewController; // @synthesize contentAreaViewController=_contentAreaViewController;
@property(retain) id selectedItem; // @synthesize selectedItem=_selectedItem;
@property(retain, nonatomic) NSString *UUID; // @synthesize UUID=_UUID;
@property(copy) NSIndexSet *chooserViewSelectionIndexes; // @synthesize chooserViewSelectionIndexes=_chooserViewSelectionIndexes;
@property(retain) DVTBorderedView *borderedView; // @synthesize borderedView=_borderedView;
@property(retain) DVTReplacementView *replacementView; // @synthesize replacementView=_replacementView;
@property(retain) DVTChooserView *chooserView; // @synthesize chooserView=_chooserView;
@property(retain, nonatomic) DVTExtension *currentExtension; // @synthesize currentExtension=_currentExtension;
@property(retain) NSArrayController *choicesController; // @synthesize choicesController=_choicesController;
- (void).cxx_destruct;
- (void)commitStateToDictionary:(id)arg1;
- (void)revertStateWithDictionary:(id)arg1;
- (void)_setCurrentExtensionIdentifier:(id)arg1;
- (id)_currentExtensionIdentifier;
- (void)replacementView:(id)arg1 willCloseViewController:(id)arg2;
- (void)replacementView:(id)arg1 didInstallViewController:(id)arg2;
- (void)setStateToken:(id)arg1;
- (void)showBookmarksArea:(id)arg1;
- (void)showExploreAreaAndSelectDocSetNode:(id)arg1;
- (void)showSearchArea:(id)arg1;
- (void)showExploreArea:(id)arg1;
- (void)updateWithURL:(id)arg1 node:(id)arg2 webView:(id)arg3;
- (void)primitiveInvalidate;
- (id)currentNavigator;
- (void)showNavigatorWithIdentifier:(id)arg1;
- (void)viewDidInstall;
- (void)loadView;

@end


text:
//
//  AwardCoinController.m
//  QiPinTong
//
//  Created by 企聘通 on 2017/5/19.
//  Copyright © 2017年 ShiJiJiaLian. All rights reserved.
//

#import "AwardCoinController.h"
#import "CommentCell.h"
#import "ComentLayout.h"
@interface AwardCoinController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,strong) UITableView *awardTable;

@property (nonatomic ,strong) NSMutableArray *awardArray;

@end

@implementation AwardCoinController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.view addSubview:self.awardTable];

#warning mark----------添加提示图片的方法调用
    //是否数组为空,若为空则显示提示图片
//    [self crectPromptViewForUserWith:self.awardArray.count == 0 andView:self.awardTable image:@""];

    // Do any additional setup after loading the view.
}

#pragma mark ----tableViewDelegate&&dataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    CommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[CommentCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

    }

    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ComentLayout *lay = [[ComentLayout alloc]initCommentCell];

    return lay.commentHeight;
}

#pragma mark ----懒加载
//tableView
-(UITableView *)awardTable
{
    if (!_awardTable) {
        _awardTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStylePlain];
        _awardTable.delegate = self;
        _awardTable.dataSource = self;
        _awardTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _awardTable.backgroundColor = whiteC;
    }
    return _awardTable;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
<html>
<title>positiveUseBeanNext</title>
<body>
<!-- Declaring the bean with out body -->

<!-- Accessing the property thru a scriptlet -->

90336
APPLE

</body>
</html>


text:
"use strict";
var foo = require("bar").foo;


text:
<?php

/**
 * sfObjectRoute represents a route that is bound to PHP object(s).
 *
 * An object route can represent a single object or a list of objects.
 *
 * @package    symfony
 * @subpackage routing
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id: sfObjectRoute.class.php 20784 2009-08-04 20:53:57Z Kris.Wallsmith $
 */
class sfPropel15Route extends sfRequestRoute
{
  protected
    $object  = false,
    $objects = false;

  /**
   * Constructor.
   *
   * @param string $pattern       The pattern to match
   * @param array  $defaults      An array of default parameter values
   * @param array  $requirements  An array of requirements for parameters (regexes)
   * @param array  $options       An array of options
   *
   * @see sfRoute
   */
  public function __construct($pattern, array $defaults = array(), array $requirements = array(), array $options = array())
  {
    if (!isset($options['model']))
    {
      throw new InvalidArgumentException(sprintf('You must pass a "model" option for a %s object (%s).', get_class($this), $pattern));
    }

    if (!isset($options['type']))
    {
      throw new InvalidArgumentException(sprintf('You must pass a "type" option for a %s object (%s).', get_class($this), $pattern));
    }

    if (!in_array($options['type'], array('object', 'list')))
    {
      throw new InvalidArgumentException(sprintf('The "type" option can only be "object" or "list", "%s" given (%s).', $options['type'], $pattern));
    }

    parent::__construct($pattern, $defaults, $requirements, $options);
  }

  /**
   * Returns true if the parameters matches this route, false otherwise.
   *
   * @param  mixed  $params  The parameters
   * @param  array  $context The context
   *
   * @return Boolean         true if the parameters matches this route, false otherwise.
   */
  public function matchesParameters($params, $context = array())
  {
    return parent::matchesParameters('object' == $this->options['type'] ? $this->convertObjectToArray($params) : $params);
  }

  /**
   * Generates a URL from the given parameters.
   *
   * @param  mixed   $params    The parameter values
   * @param  array   $context   The context
   * @param  Boolean $absolute  Whether to generate an absolute URL
   *
   * @return string The generated URL
   */
  public function generate($params, $context = array(), $absolute = false)
  {
    return parent::generate('object' == $this->options['type'] ? $this->convertObjectToArray($params) : $params, $context, $absolute);
  }

  /**
   * Gets the object related to the current route and parameters.
   *
   * This method is only accessible if the route is bound and of type "object".
   *
   * @return Object The related object
   */
  public function getObject()
  {
    if (!$this->isBound())
    {
      throw new LogicException('The route is not bound.');
    }

    if ('object' != $this->options['type'])
    {
      throw new LogicException(sprintf('The route "%s" is not of type "object".', $this->pattern));
    }

    if (false !== $this->object)
    {
      return $this->object;
    }

    // check the related object
    $this->object = $this->getQuery()->findOne();

    if (!$this->object && (!isset($this->options['allow_empty']) || !$this->options['allow_empty']))
    {
      throw new sfError404Exception(sprintf('Unable to find the %s object with the following parameters "%s").', $this->options['model'], str_replace("\n", '', var_export($this->filterParameters($this->parameters), true))));
    }

    return $this->object;
  }

  /**
   * Gets the list of objects related to the current route and parameters.
   *
   * This method is only accessible if the route is bound and of type "list".
   *
   * @return array And array of related objects
   */
  public function getObjects()
  {
    if (!$this->isBound())
    {
      throw new LogicException('The route is not bound.');
    }

    if ('list' != $this->options['type'])
    {
      throw new LogicException(sprintf('The route "%s" is not of type "list".', $this->pattern));
    }

    if (false !== $this->objects)
    {
      return $this->objects;
    }

    $this->objects = $this->getQuery()->find();

    if (!count($this->objects) && isset($this->options['allow_empty']) && !$this->options['allow_empty'])
    {
      throw new sfError404Exception(sprintf('No %s object found for the following parameters "%s").', $this->options['model'], str_replace("\n", '', var_export($this->filterParameters($this->parameters), true))));
    }

    return $this->objects;
  }

  protected function getQuery()
  {
    $query = PropelQuery::from($this->options['model']);
    if (isset($this->options['query_methods']))
    {
      foreach ($this->options['query_methods'] as $methodName) {
        $query->$methodName();
      }
    }
    $query->filterByArray($this->getModelParameters($this->parameters));
    return $query;
  }

  protected function getModelParameters($parameters)
  {
  	if (!is_array($parameters))
    {
      return $parameters;
    }
    $parameters = $this->filterParameters($parameters);
    $peerName = constant($this->options['model'] . '::PEER');
    $params = array();
    foreach ($this->getRealVariables() as $variable)
    {
    	try
      {
        $column = call_user_func(array($peerName, 'translateFieldName'), $variable, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME);
      }
      catch (Exception $e)
      {
        $column = sfInflector::camelize($variable);
      }
      $params[$column] = $parameters[$variable];
    }

    return $params;
  }

  protected function filterParameters($parameters)
  {
  	if (!is_array($parameters))
    {
      return $parameters;
    }

    $params = array();
    foreach (array_keys($this->variables) as $variable)
    {
      $params[$variable] = $parameters[$variable];
    }

    return $params;
  }

  protected function convertObjectToArray($object)
  {
    if (!$this->compiled)
    {
      $this->compile();
    }

    if (is_array($object))
    {
      if (!isset($object['sf_subject']))
      {
        return $object;
      }

      $parameters = $object;
      $object = $parameters['sf_subject'];
      unset($parameters['sf_subject']);
    }
    else
    {
      $parameters = array();
    }

    return array_merge($parameters, $this->doConvertObjectToArray($object));
  }

  protected function doConvertObjectToArray($object)
  {
    if (isset($this->options['convert']) || method_exists($object, 'toParams'))
    {
      return parent::doConvertObjectToArray($object);
    }

    $peerName = constant($this->options['model'] . '::PEER');

    $parameters = array();
    foreach ($this->getRealVariables() as $variable)
    {
      try
      {
        $method = 'get'.call_user_func(array($peerName, 'translateFieldName'), $variable, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME);
      }
      catch (Exception $e)
      {
        $method = 'get'.sfInflector::camelize($variable);
      }

      $parameters[$variable] = $object->$method();
    }

    return $parameters;
  }

  protected function getRealVariables()
  {
    $variables = array();

    foreach (array_keys($this->variables) as $variable)
    {
      if (0 === strpos($variable, 'sf_') || in_array($variable, array('module', 'action')))
      {
        continue;
      }

      $variables[] = $variable;
    }

    return $variables;
  }

  public function __call($name, $arguments)
  {
    if($name == 'get' . $this->options['model'])
    {
      return call_user_func_array(array($this, 'getObject'), $arguments);
    }
    throw new Exception(sprintf('Call to undefined method sfPropel15Route::%s.', $name));
  }
}


text:
import pickle
from flask import url_for
from werkzeug.exceptions import NotFound
from custom_exceptions import DataValidationError
from . import app

######################################################################
# Shopcart Model for database
#   This class must be initialized with use_db(redis) before using
#   where redis is a value connection to a Redis database
######################################################################

class Shopcart(object):
    __redis = None

    def __init__(self, uid=0, sid=0,subtotal=0.0,products=[]):
        self.uid = int(uid)
        self.sid = int(sid)
        self.subtotal = float(subtotal)
        self.products = products

    def save(self):
        if self.sid == 0:
            self.sid = self.__next_index()
        Shopcart.__redis.set(self.sid, pickle.dumps(self.serialize()))

    def delete(self):
        Shopcart.__redis.delete(self.sid)

    def __next_index(self):
        return Shopcart.__redis.incr('index')

    def self_url(self,urltype):
        return url_for('get_shopcart', sid=self.sid, _external=True)

    def serialize(self):
        return { "uid": self.uid, "sid": self.sid, "subtotal": self.subtotal, "products": self.products }

    def deserialize_products(self,data):
        for i in range(0,len(data)):
            if len(self.products) == 1:
                if self.products[0] == []:
                    self.products.remove(self.products[0])
            self.products.append(data[i])

    def deserialize(self, data):
        if "sid" in data:
            self.sid = data['sid']
        self.uid = data['uid']
        if 'sid' in data:
            self.sid = data['sid']
        self.subtotal = data['subtotal']
        self.products = data['products']
        if 'subtotal' not in data:
            self.subtotal = 0.0
        else:
            self.subtotal = data['subtotal']
        return self

######################################################################
#  S T A T I C   D A T A B S E   M E T H O D S
######################################################################

    @staticmethod
    def use_db(redis):
        Shopcart.__redis = redis

    @staticmethod
    def remove_all():
        Shopcart.__redis.flushall()

    @staticmethod
    def all():
        results = []
        for key in Shopcart.__redis.keys():
            if key != 'index':  # filer out our id index
                data = Shopcart.__redis.get(key)
                data = pickle.loads(data)
                results.append(data)
        return results

    @staticmethod
    def find(sid):
        if Shopcart.__redis.exists(sid):
            data = Shopcart.__redis.get(sid)
            data = pickle.loads(data)
            return data
        else:
            return None

    @staticmethod
    def check_shopcart_exists(sid):
        if Shopcart.__redis.exists(sid):
            data = pickle.loads(Shopcart.__redis.get(sid))
            shopcart = Shopcart(data['sid']).deserialize(data)
            return shopcart
        else:
            return None

    @staticmethod
    def validate_shopcart(data):
        valid = False
        try:
            user_id = data['uid']
            valid = True
        except KeyError as err:
            valid = False
            #raise DataValidationError('Missing parameter error: ' + err.args[0])
        except TypeError as err:
            valid = False
            #raise DataValidationError('Invalid shopcart: body of request contained bad or no data')
        return valid

    @staticmethod
    def validate_product(data):
        valid = False
        try:
            for i in range(0,len(data['products'])):
                sku = data['products'][i]['sku']
                quantity = data['products'][i]['quantity']
                name = data['products'][i]['name']
                unitprice = data['products'][i]['unitprice']
            valid = True
        except KeyError as err:
            valid = False
            #error = err.args[0]
            #if isinstance(err.args[0],int):
            #    error = str(err.args[0])
            #raise DataValidationError('Missing parameter error: ' + error)
        except TypeError as err:
            valid = False
            #raise DataValidationError('Invalid product: body of request contained bad or no data')
        return valid

    @staticmethod
    def find_by_uid(uid):
        results = []
        for key in Shopcart.__redis.keys():
            if key != 'index':  # filer out our id index
                data = Shopcart.__redis.get(key)
                data = pickle.loads(data)
                if data["uid"] == uid:
                    results.append(data)
        return results


text:
<template name="topWrapper">

      {{> UI.contentBlock}}

</template>


text:
class GameType : public IObject
{
public:
    virtual ZString GetName() = 0;
    virtual bool IsGameType(const MissionParams& misparams) = 0;
    virtual void Apply(MissionParams& misparams) = 0;

    static TRef<GameType> FindType(const MissionParams& misparams);
    static TList<TRef<GameType> >& GetGameTypes();
};

#endif GAMETYPES_H


text:
<?php

/**
 * Export.php
 *
 * This file does the actual generation of the content for view / display by the user. It calls the
 * export.tpl found in the /modules/export_manager/templates folder.
 */

require_once(realpath((dirname(__FILE__) . "/../../global/session_start.php")));
ft_include_module("export_manager");
$request = array_merge($_POST, $_GET);

// passed in explicitly via POST or GET
$export_group_id = (isset($request["export_group_id"])) ? $request["export_group_id"] : "";
$export_type_id  = (isset($request["export_type_id"])) ? $request["export_type_id"] : "";
$results         = (isset($request["export_group_{$export_group_id}_results"])) ? $request["export_group_{$export_group_id}_results"] : "all";

// drawn from sessions
$form_id       = isset($_SESSION["ft"]["curr_form_id"]) ? $_SESSION["ft"]["curr_form_id"] : "";
$view_id       = isset($_SESSION["ft"]["form_{$form_id}_view_id"]) ? $_SESSION["ft"]["form_{$form_id}_view_id"] : "";
$order         = isset($_SESSION["ft"]["current_search"]["order"]) ? $_SESSION["ft"]["current_search"]["order"] : "";
$search_fields = isset($_SESSION["ft"]["current_search"]["search_fields"]) ? $_SESSION["ft"]["current_search"]["search_fields"] : array();

$export_group_results = ft_load_module_field("export_manager", "export_group_{$export_group_id}_results", "export_group_{$export_group_id}_results");

// if any of the required fields weren't entered, just output a simple blank message
if (empty($form_id) || empty($view_id) || empty($order) || empty($search_fields) || empty($export_group_id))
{
  echo $LANG["export_manager"]["notify_export_incomplete_fields"];
  exit;
}

set_time_limit(300);

// if the user only wants to display the currently selected rows, limit the query to those submission IDs
$submission_ids = array();
if ($results == "selected")
  $submission_ids = $_SESSION["ft"]["form_{$form_id}_selected_submissions"];

// perform the almighty search query
$results_info = ft_search_submissions($form_id, $view_id, "all", 1, $order, "all", $search_fields, $submission_ids);
$search_rows        = $results_info["search_rows"];
$search_num_results = $results_info["search_num_results"];
$view_num_results   = $results_info["view_num_results"];

$form_info   = ft_get_form($form_id);
$view_info   = ft_get_view($view_id);
$form_fields = ft_get_form_fields($form_id, array("include_field_type_info" => true, "include_field_settings" => true));
$field_types = ft_get_field_types(true);

// display_fields contains ALL the information we need for the fields in the template
$display_fields = array();
foreach ($view_info["fields"] as $view_field_info)
{
  $curr_field_id = $view_field_info["field_id"];
  foreach ($form_fields as $form_field_info)
  {
    if ($form_field_info["field_id"] != $curr_field_id)
      continue;

    $display_fields[] = array_merge($form_field_info, $view_field_info);
  }
}

// first, build the list of information we're going to send to the export type smarty template
$placeholders = exp_get_export_filename_placeholder_hash();
$placeholders["export_group_id"] = $export_group_id;
$placeholders["export_type_id"] = $export_type_id;
$placeholders["export_group_results"] = $results;
$placeholders["field_types"] = $field_types;
$placeholders["same_page"] = ft_get_clean_php_self();
$placeholders["display_fields"] = $display_fields;
$placeholders["submissions"]    = $results_info["search_rows"];
$placeholders["num_results"]    = $results_info["search_num_results"];
$placeholders["view_num_results"] = $results_info["view_num_results"];
$placeholders["form_info"] = $form_info;
$placeholders["view_info"] = $view_info;
$placeholders["timezone_offset"] = $_SESSION["ft"]["account"]["timezone_offset"];

// pull out a few things into top level placeholders for easy use
$placeholders["form_id"]   = $form_id;
$placeholders["form_name"] = $form_info["form_name"];
$placeholders["form_url"]  = $form_info["form_url"];
$placeholders["view_id"]   = $view_id;
$placeholders["view_name"] = $view_info["view_name"];
$placeholders["settings"]  = ft_get_settings();

$export_group_info = exp_get_export_group($export_group_id);
$export_types      = exp_get_export_types($export_group_id);

// if the export type ID isn't available, the export group only contains a single (visible) export type
$export_type_info = array();
if (empty($export_type_id))
{
  foreach ($export_types as $curr_export_type_info)
  {
    if ($curr_export_type_info["export_type_visibility"] == "show")
    {
      $export_type_info = $curr_export_type_info;
      break;
    }
  }
}
else
  $export_type_info = exp_get_export_type($export_type_id);

$placeholders["export_group_name"] = ft_create_slug(ft_eval_smarty_string($export_group_info["group_name"]));
$placeholders["export_group_type"] = ft_create_slug(ft_eval_smarty_string($export_type_info["export_type_name"]));
$placeholders["page_type"] = $export_group_info["action"]; // "file" / "popup" or "new_window"
$placeholders["filename"] = ft_eval_smarty_string($export_type_info["filename"], $placeholders);

$template = $export_type_info["export_type_smarty_template"];
$placeholders["export_type_name"] = $export_type_info["export_type_name"];

$plugin_dirs = array("$g_root_dir/modules/export_manager/smarty");
$export_type_smarty_template = ft_eval_smarty_string($template, $placeholders, "", $plugin_dirs);

// next, add the placeholders needed for the export group smarty template
$template = $export_group_info["smarty_template"];
$placeholders["export_group_name"] = ft_eval_smarty_string($export_group_info["group_name"]);
$placeholders["export_types"] = $export_types;
$placeholders["export_type_smarty_template"] = $export_type_smarty_template;
$page = ft_eval_smarty_string($template, $placeholders);

if ($export_group_info["action"] == "new_window" || $export_group_info["action"] == "popup")
{
  // if required, send the HTTP headers
  if (!empty($export_group_info["headers"]))
  {
    $headers = preg_replace("/\r\n|\r/", "\n", $export_group_info["headers"]);
    $header_lines = explode("\n", $headers);

    foreach ($header_lines as $header)
      header(ft_eval_smarty_string($header, $placeholders));
  }

  echo $page;
}

// create a file on the server
else
{
  $settings = ft_get_settings("", "export_manager");
  $file_upload_dir = $settings["file_upload_dir"];
  $file_upload_url = $settings["file_upload_url"];

  $file = "$file_upload_dir/{$placeholders["filename"]}";
  if ($handle = @fopen($file, "w"))
  {
    fwrite($handle, $page);
    fclose($handle);
    @chmod($file, 0777);

    $placeholders = array("url" => "$file_upload_url/{$placeholders["filename"]}");
    $message = ft_eval_smarty_string($LANG["export_manager"]["notify_file_generated"], $placeholders);
    echo "{ \"success\": 1, \"message\": \"$message\", \"target_message_id\": \"ft_message\" }";
    exit;
  }
  else
  {
    $placeholders = array(
      "url"    => "$file_upload_url/{$placeholders["filename"]}",
      "folder" => $file_upload_dir,
      "export_manager_settings_link" => "$g_root_url/modules/export_manager/settings.php"
        );
    $message = ft_eval_smarty_string($LANG["export_manager"]["notify_file_not_generated"], $placeholders);
    echo "{ \"success\": 0, \"message\": \"$message\", \"target_message_id\": \"ft_message\" }";
    exit;
  }
}


text:
package sibbo.bitmessage.network;

import java.util.List;

import sibbo.bitmessage.network.protocol.InventoryVectorMessage;
import sibbo.bitmessage.network.protocol.NetworkAddressMessage;
import sibbo.bitmessage.network.protocol.POWMessage;

/**
 * A listener that is informed if something happens during a connection to a
 * node.
 *
 * @author Sebastian Schmidt
 * @version 1.0
 *
 */
public interface ConnectionListener {
	/**
	 * The given connection was not able to connect to its target.
	 *
	 * @param c
	 *            A connection.
	 */
	void couldNotConnect(Connection c);

	/**
	 * The connection to the target was canceled.
	 *
	 * @param c
	 *            A connection.
	 */
	void connectionAborted(Connection c);

	/**
	 * The connection received a new object from its target.
	 *
	 * @param m
	 *            An object.
	 */
	void receivedObject(POWMessage m, Connection c);

	/**
	 * The connection received a list of new nodes.
	 *
	 * @param list
	 *            A list of nodes.
	 */
	void receivedNodes(List<NetworkAddressMessage> list, Connection c);

	/**
	 * The connection received a list of object hashes.
	 *
	 * @param inventoryVectors
	 *            A list of object hashes.
	 */
	void advertisedObjects(List<InventoryVectorMessage> inventoryVectors, Connection c);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/white"
            android:focusable="true"
            android:focusableInTouchMode="true"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Dark"
            app:titleTextAppearance="@style/StyleLabelMenuActivity">

        </android.support.v7.widget.Toolbar>

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>


text:
package cmd

import (
	boshdir "github.com/cloudfoundry/bosh-cli/director"
	boshui "github.com/cloudfoundry/bosh-cli/ui"
)

type CleanUpCmd struct {
	ui       boshui.UI
	director boshdir.Director
}

func NewCleanUpCmd(ui boshui.UI, director boshdir.Director) CleanUpCmd {
	return CleanUpCmd{ui: ui, director: director}
}

func (c CleanUpCmd) Run(opts CleanUpOpts) error {
	err := c.ui.AskForConfirmation()
	if err != nil {
		return err
	}

	return c.director.CleanUp(opts.All)
}


text:
racing-game
===========

2D racing game written in JavaScript.

You can see the latest version in action here.
Or you can try v1.0.


text:
#include "source/common/json/json_internal.h"

#include <cstdint>
#include <fstream>
#include <limits>
#include <map>
#include <sstream>
#include <stack>
#include <string>
#include <vector>

#include "source/common/common/assert.h"
#include "source/common/common/fmt.h"
#include "source/common/common/hash.h"
#include "source/common/common/utility.h"
#include "source/common/protobuf/utility.h"

// Do not let nlohmann/json leak outside of this file.
#include "include/nlohmann/json.hpp"

#include "absl/strings/match.h"

namespace Envoy {
namespace Json {
namespace Nlohmann {

namespace {
/**
 * Internal representation of Object.
 */
class Field;
using FieldSharedPtr = std::shared_ptr<Field>;

class Field : public Object {
public:
  void setLineNumberStart(uint64_t line_number) { line_number_start_ = line_number; }
  void setLineNumberEnd(uint64_t line_number) { line_number_end_ = line_number; }

  // Container factories for handler.
  static FieldSharedPtr createObject() { return FieldSharedPtr{new Field(Type::Object)}; }
  static FieldSharedPtr createArray() { return FieldSharedPtr{new Field(Type::Array)}; }
  static FieldSharedPtr createNull() { return FieldSharedPtr{new Field(Type::Null)}; }

  bool isArray() const override { return type_ == Type::Array; }
  bool isObject() const override { return type_ == Type::Object; }

  // Value factory.
  template <typename T> static FieldSharedPtr createValue(T value) {
    return FieldSharedPtr{new Field(value)}; // NOLINT(modernize-make-shared)
  }

  void append(FieldSharedPtr field_ptr) {
    checkType(Type::Array);
    value_.array_value_.push_back(field_ptr);
  }
  void insert(const std::string& key, FieldSharedPtr field_ptr) {
    checkType(Type::Object);
    value_.object_value_[key] = field_ptr;
  }

  uint64_t hash() const override;

  bool getBoolean(const std::string& name) const override;
  bool getBoolean(const std::string& name, bool default_value) const override;
  double getDouble(const std::string& name) const override;
  double getDouble(const std::string& name, double default_value) const override;
  int64_t getInteger(const std::string& name) const override;
  int64_t getInteger(const std::string& name, int64_t default_value) const override;
  ObjectSharedPtr getObject(const std::string& name, bool allow_empty) const override;
  std::vector<ObjectSharedPtr> getObjectArray(const std::string& name,
                                              bool allow_empty) const override;
  std::string getString(const std::string& name) const override;
  std::string getString(const std::string& name, const std::string& default_value) const override;
  std::vector<std::string> getStringArray(const std::string& name, bool allow_empty) const override;
  std::vector<ObjectSharedPtr> asObjectArray() const override;
  std::string asString() const override { return stringValue(); }
  std::string asJsonString() const override;

  bool empty() const override;
  bool hasObject(const std::string& name) const override;
  void iterate(const ObjectCallback& callback) const override;
  void validateSchema(const std::string&) const override;

private:
  enum class Type {
    Array,
    Boolean,
    Double,
    Integer,
    Null,
    Object,
    String,
  };
  static const char* typeAsString(Type t) {
    switch (t) {
    case Type::Array:
      return "Array";
    case Type::Boolean:
      return "Boolean";
    case Type::Double:
      return "Double";
    case Type::Integer:
      return "Integer";
    case Type::Null:
      return "Null";
    case Type::Object:
      return "Object";
    case Type::String:
      return "String";
    }

    return "";
  }

  struct Value {
    std::vector<FieldSharedPtr> array_value_;
    bool boolean_value_;
    double double_value_;
    int64_t integer_value_;
    std::map<std::string, FieldSharedPtr> object_value_;
    std::string string_value_;
  };

  explicit Field(Type type) : type_(type) {}
  explicit Field(const std::string& value) : type_(Type::String) { value_.string_value_ = value; }
  explicit Field(int64_t value) : type_(Type::Integer) { value_.integer_value_ = value; }
  explicit Field(double value) : type_(Type::Double) { value_.double_value_ = value; }
  explicit Field(bool value) : type_(Type::Boolean) { value_.boolean_value_ = value; }

  bool isType(Type type) const { return type == type_; }
  void checkType(Type type) const {
    if (!isType(type)) {
      throw Exception(fmt::format(
          "JSON field from line {} accessed with type '{}' does not match actual type '{}'.",
          line_number_start_, typeAsString(type), typeAsString(type_)));
    }
  }

  // Value return type functions.
  std::string stringValue() const {
    checkType(Type::String);
    return value_.string_value_;
  }
  std::vector<FieldSharedPtr> arrayValue() const {
    checkType(Type::Array);
    return value_.array_value_;
  }
  bool booleanValue() const {
    checkType(Type::Boolean);
    return value_.boolean_value_;
  }
  double doubleValue() const {
    checkType(Type::Double);
    return value_.double_value_;
  }
  int64_t integerValue() const {
    checkType(Type::Integer);
    return value_.integer_value_;
  }

  nlohmann::json asJsonDocument() const;
  static void buildJsonDocument(const Field& field, nlohmann::json& value);

  uint64_t line_number_start_ = 0;
  uint64_t line_number_end_ = 0;
  const Type type_;
  Value value_;
};

/**
 * Consume events from SAX callbacks to build JSON Field.
 */
class ObjectHandler : public nlohmann::json_sax<nlohmann::json> {
public:
  ObjectHandler() = default;

  bool start_object(std::size_t) override;
  bool end_object() override;
  bool key(std::string& val) override;
  bool start_array(std::size_t) override;
  bool end_array() override;
  bool boolean(bool value) override { return handleValueEvent(Field::createValue(value)); }
  bool number_integer(int64_t value) override {
    return handleValueEvent(Field::createValue(static_cast<int64_t>(value)));
  }
  bool number_unsigned(uint64_t value) override {
    if (value > static_cast<uint64_t>(std::numeric_limits<int64_t>::max())) {
      throw Exception(fmt::format("JSON value from line {} is larger than int64_t (not supported)",
                                  line_number_));
    }
    return handleValueEvent(Field::createValue(static_cast<int64_t>(value)));
  }
  bool number_float(double value, const std::string&) override {
    return handleValueEvent(Field::createValue(value));
  }
  bool null() override { return handleValueEvent(Field::createNull()); }
  bool string(std::string& value) override { return handleValueEvent(Field::createValue(value)); }
  bool binary(binary_t&) override { return false; }
  bool parse_error(std::size_t at, const std::string& token,
                   const nlohmann::detail::exception& ex) override {
    // Parse errors are formatted like "[json.exception.parse_error.101] parse error: explanatory
    // string." or "[json.exception.parse_error.101] parser error at (position): explanatory
    // string.". All errors start with "[json.exception.<error_type>.<error_num]" see:
    // https://json.nlohmann.me/home/exceptions/#parse-errors
    // The `parse_error` method will be called also for non-parse errors.
    absl::string_view error = ex.what();

    // Colon will always exist in the parse error. For non-parse error use the
    // ending ']' as a separator.
    auto end = error.find(": ");
    auto prefix_end = error.find(']');
    if (end != std::string::npos) {
      // Extract portion after ": " to get error string.
      error_ = std::string(error.substr(end + 2));
      // Extract position information if present.
      auto start = error.find("at ");
      if (start != std::string::npos && (start + 3) < end) {
        start += 3;
        error_position_ = absl::StrCat(error.substr(start, end - start), ", token ", token);
      }
    } else if ((prefix_end != std::string::npos) && (absl::StartsWith(error, ErrorPrefix))) {
      // Non-parse error, fetching position from the arguments as it is not
      // present in the error string.
      error_position_ = absl::StrCat("position: ", at);
      error_ = std::string(error.substr(prefix_end + 1));
    } else {
      IS_ENVOY_BUG("Error string not present. Check nlohmann/json "
                   "documentation in case error string changed.");
    }
    return false;
  }

  bool hasParseError() { return !error_.empty(); }
  std::string getParseError() { return error_; }
  std::string getErrorPosition() { return error_position_; }

  ObjectSharedPtr getRoot() { return root_; }

  int line_number_{1};

private:
  bool handleValueEvent(FieldSharedPtr ptr);

  enum class State {
    ExpectRoot,
    ExpectKeyOrEndObject,
    ExpectValueOrStartObjectArray,
    ExpectArrayValueOrEndArray,
    ExpectFinished,
  };
  State state_{State::ExpectRoot};

  std::stack<FieldSharedPtr> stack_;
  std::string key_;

  FieldSharedPtr root_;

  std::string error_;
  std::string error_position_;

  static constexpr absl::string_view ErrorPrefix = "[json.exception.";
};

struct JsonContainer {
  JsonContainer(const char* ch, ObjectHandler* handler) : data(ch), handler_(handler) {}
  const char* data;
  ObjectHandler* handler_;
};

struct JsonIterator {
  using difference_type = std::ptrdiff_t;            // NOLINT(readability-identifier-naming)
  using value_type = char;                           // NOLINT(readability-identifier-naming)
  using pointer = const char*;                       // NOLINT(readability-identifier-naming)
  using reference = const char&;                     // NOLINT(readability-identifier-naming)
  using iterator_category = std::input_iterator_tag; // NOLINT(readability-identifier-naming)

  JsonIterator& operator++() {
    ++ptr.data;
    return *this;
  }

  bool operator!=(const JsonIterator& rhs) const { return rhs.ptr.data != ptr.data; }

  reference operator*() {
    const char& ch = *(ptr.data);
    if (ch == '\n') {
      ptr.handler_->line_number_++;
    }
    return ch;
  }

  JsonContainer ptr;
};

JsonIterator begin(const JsonContainer& c) {
  return JsonIterator{JsonContainer(c.data, c.handler_)};
}

JsonIterator end(const JsonContainer& c) {
  return JsonIterator{JsonContainer(c.data + strlen(c.data), c.handler_)};
}

void Field::buildJsonDocument(const Field& field, nlohmann::json& value) {
  switch (field.type_) {
  case Type::Array: {
    for (const auto& element : field.value_.array_value_) {
      switch (element->type_) {
      case Type::Array:
      case Type::Object: {
        nlohmann::json nested_value;
        buildJsonDocument(*element, nested_value);
        value.push_back(nested_value);
        break;
      }
      case Type::Boolean:
        value.push_back(element->value_.boolean_value_);
        break;
      case Type::Double:
        value.push_back(element->value_.double_value_);
        break;
      case Type::Integer:
        value.push_back(element->value_.integer_value_);
        break;
      case Type::Null:
        value.push_back(nlohmann::json::value_t::null);
        break;
      case Type::String:
        value.push_back(element->value_.string_value_);
      }
    }
    break;
  }
  case Type::Object: {
    for (const auto& item : field.value_.object_value_) {
      auto name = std::string(item.first);

      switch (item.second->type_) {
      case Type::Array:
      case Type::Object: {
        nlohmann::json nested_value;
        buildJsonDocument(*item.second, nested_value);
        value.emplace(name, nested_value);
        break;
      }
      case Type::Boolean:
        value.emplace(name, item.second->value_.boolean_value_);
        break;
      case Type::Double:
        value.emplace(name, item.second->value_.double_value_);
        break;
      case Type::Integer:
        value.emplace(name, item.second->value_.integer_value_);
        break;
      case Type::Null:
        value.emplace(name, nlohmann::json::value_t::null);
        break;
      case Type::String:
        value.emplace(name, item.second->value_.string_value_);
        break;
      }
    }
    break;
  }
  case Type::Null: {
    break;
  }
  case Type::Boolean:
    FALLTHRU;
  case Type::Double:
    FALLTHRU;
  case Type::Integer:
    FALLTHRU;
  case Type::String:
    PANIC("not implemented");
  }
}

nlohmann::json Field::asJsonDocument() const {
  nlohmann::json j;
  buildJsonDocument(*this, j);
  return j;
}

uint64_t Field::hash() const { return HashUtil::xxHash64(asJsonString()); }

bool Field::getBoolean(const std::string& name) const {
  checkType(Type::Object);
  auto value_itr = value_.object_value_.find(name);
  if (value_itr == value_.object_value_.end() || !value_itr->second->isType(Type::Boolean)) {
    throw Exception(fmt::format("key '{}' missing or not a boolean from lines {}-{}", name,
                                line_number_start_, line_number_end_));
  }
  return value_itr->second->booleanValue();
}

bool Field::getBoolean(const std::string& name, bool default_value) const {
  checkType(Type::Object);
  auto value_itr = value_.object_value_.find(name);
  if (value_itr != value_.object_value_.end()) {
    return getBoolean(name);
  }
  return default_value;
}

double Field::getDouble(const std::string& name) const {
  checkType(Type::Object);
  auto value_itr = value_.object_value_.find(name);
  if (value_itr == value_.object_value_.end() || !value_itr->second->isType(Type::Double)) {
    throw Exception(fmt::format("key '{}' missing or not a double from lines {}-{}", name,
                                line_number_start_, line_number_end_));
  }
  return value_itr->second->doubleValue();
}

double Field::getDouble(const std::string& name, double default_value) const {
  checkType(Type::Object);
  auto value_itr = value_.object_value_.find(name);
  if (value_itr != value_.object_value_.end()) {
    return getDouble(name);
  }
  return default_value;
}

int64_t Field::getInteger(const std::string& name) const {
  checkType(Type::Object);
  auto value_itr = value_.object_value_.find(name);
  if (value_itr == value_.object_value_.end() || !value_itr->second->isType(Type::Integer)) {
    throw Exception(fmt::format("key '{}' missing or not an integer from lines {}-{}", name,
                                line_number_start_, line_number_end_));
  }
  return value_itr->second->integerValue();
}

int64_t Field::getInteger(const std::string& name, int64_t default_value) const {
  checkType(Type::Object);
  auto value_itr = value_.object_value_.find(name);
  if (value_itr != value_.object_value_.end()) {
    return getInteger(name);
  }
  return default_value;
}

ObjectSharedPtr Field::getObject(const std::string& name, bool allow_empty) const {
  checkType(Type::Object);
  auto value_itr = value_.object_value_.find(name);
  if (value_itr == value_.object_value_.end()) {
    if (allow_empty) {
      return createObject();
    } else {
      throw Exception(fmt::format("key '{}' missing from lines {}-{}", name, line_number_start_,
                                  line_number_end_));
    }
  } else if (!value_itr->second->isType(Type::Object)) {
    throw Exception(fmt::format("key '{}' not an object from line {}", name,
                                value_itr->second->line_number_start_));
  } else {
    return value_itr->second;
  }
}

std::vector<ObjectSharedPtr> Field::getObjectArray(const std::string& name,
                                                   bool allow_empty) const {
  checkType(Type::Object);
  auto value_itr = value_.object_value_.find(name);
  if (value_itr == value_.object_value_.end() || !value_itr->second->isType(Type::Array)) {
    if (allow_empty && value_itr == value_.object_value_.end()) {
      return std::vector<ObjectSharedPtr>();
    }
    throw Exception(fmt::format("key '{}' missing or not an array from lines {}-{}", name,
                                line_number_start_, line_number_end_));
  }

  std::vector<FieldSharedPtr> array_value = value_itr->second->arrayValue();
  return {array_value.begin(), array_value.end()};
}

std::string Field::getString(const std::string& name) const {
  checkType(Type::Object);
  auto value_itr = value_.object_value_.find(name);
  if (value_itr == value_.object_value_.end() || !value_itr->second->isType(Type::String)) {
    throw Exception(fmt::format("key '{}' missing or not a string from lines {}-{}", name,
                                line_number_start_, line_number_end_));
  }
  return value_itr->second->stringValue();
}

std::string Field::getString(const std::string& name, const std::string& default_value) const {
  checkType(Type::Object);
  auto value_itr = value_.object_value_.find(name);
  if (value_itr != value_.object_value_.end()) {
    return getString(name);
  }
  return default_value;
}

std::vector<std::string> Field::getStringArray(const std::string& name, bool allow_empty) const {
  checkType(Type::Object);
  std::vector<std::string> string_array;
  auto value_itr = value_.object_value_.find(name);
  if (value_itr == value_.object_value_.end() || !value_itr->second->isType(Type::Array)) {
    if (allow_empty && value_itr == value_.object_value_.end()) {
      return string_array;
    }
    throw Exception(fmt::format("key '{}' missing or not an array from lines {}-{}", name,
                                line_number_start_, line_number_end_));
  }

  std::vector<FieldSharedPtr> array = value_itr->second->arrayValue();
  string_array.reserve(array.size());
  for (const auto& element : array) {
    if (!element->isType(Type::String)) {
      throw Exception(fmt::format("JSON array '{}' from line {} does not contain all strings", name,
                                  line_number_start_));
    }
    string_array.push_back(element->stringValue());
  }

  return string_array;
}

std::vector<ObjectSharedPtr> Field::asObjectArray() const {
  checkType(Type::Array);
  return {value_.array_value_.begin(), value_.array_value_.end()};
}

std::string Field::asJsonString() const {
  nlohmann::json j = asJsonDocument();
  return j.dump();
}

bool Field::empty() const {
  if (isType(Type::Object)) {
    return value_.object_value_.empty();
  } else if (isType(Type::Array)) {
    return value_.array_value_.empty();
  } else {
    throw Exception(
        fmt::format("Json does not support empty() on types other than array and object"));
  }
}

bool Field::hasObject(const std::string& name) const {
  checkType(Type::Object);
  auto value_itr = value_.object_value_.find(name);
  return value_itr != value_.object_value_.end();
}

void Field::iterate(const ObjectCallback& callback) const {
  checkType(Type::Object);
  for (const auto& item : value_.object_value_) {
    bool stop_iteration = !callback(item.first, *item.second);
    if (stop_iteration) {
      break;
    }
  }
}

void Field::validateSchema(const std::string&) const { throw Exception("not implemented"); }

bool ObjectHandler::start_object(std::size_t) {
  FieldSharedPtr object = Field::createObject();
  object->setLineNumberStart(line_number_);

  switch (state_) {
  case State::ExpectValueOrStartObjectArray:
    stack_.top()->insert(key_, object);
    stack_.push(object);
    state_ = State::ExpectKeyOrEndObject;
    return true;
  case State::ExpectArrayValueOrEndArray:
    stack_.top()->append(object);
    stack_.push(object);
    state_ = State::ExpectKeyOrEndObject;
    return true;
  case State::ExpectRoot:
    root_ = object;
    stack_.push(object);
    state_ = State::ExpectKeyOrEndObject;
    return true;
  case State::ExpectKeyOrEndObject:
    FALLTHRU;
  case State::ExpectFinished:
    PANIC("not implemented");
  }
  return false;
}

bool ObjectHandler::end_object() {
  if (state_ == State::ExpectKeyOrEndObject) {
    stack_.top()->setLineNumberEnd(line_number_);
    stack_.pop();

    if (stack_.empty()) {
      state_ = State::ExpectFinished;
    } else if (stack_.top()->isObject()) {
      state_ = State::ExpectKeyOrEndObject;
    } else if (stack_.top()->isArray()) {
      state_ = State::ExpectArrayValueOrEndArray;
    }
    return true;
  }
  PANIC("parsing error not handled");
}

bool ObjectHandler::key(std::string& val) {
  if (state_ == State::ExpectKeyOrEndObject) {
    key_ = val;
    state_ = State::ExpectValueOrStartObjectArray;
    return true;
  }
  PANIC("parsing error not handled");
}

bool ObjectHandler::start_array(std::size_t) {
  FieldSharedPtr array = Field::createArray();
  array->setLineNumberStart(line_number_);

  switch (state_) {
  case State::ExpectValueOrStartObjectArray:
    stack_.top()->insert(key_, array);
    stack_.push(array);
    state_ = State::ExpectArrayValueOrEndArray;
    return true;
  case State::ExpectArrayValueOrEndArray:
    stack_.top()->append(array);
    stack_.push(array);
    return true;
  case State::ExpectRoot:
    root_ = array;
    stack_.push(array);
    state_ = State::ExpectArrayValueOrEndArray;
    return true;
  default:
    PANIC("parsing error not handled");
  }
}

bool ObjectHandler::end_array() {
  switch (state_) {
  case State::ExpectArrayValueOrEndArray:
    stack_.top()->setLineNumberEnd(line_number_);
    stack_.pop();

    if (stack_.empty()) {
      state_ = State::ExpectFinished;
    } else if (stack_.top()->isObject()) {
      state_ = State::ExpectKeyOrEndObject;
    } else if (stack_.top()->isArray()) {
      state_ = State::ExpectArrayValueOrEndArray;
    }

    return true;
  default:
    PANIC("parsing error not handled");
  }
}

bool ObjectHandler::handleValueEvent(FieldSharedPtr ptr) {
  ptr->setLineNumberStart(line_number_);

  switch (state_) {
  case State::ExpectValueOrStartObjectArray:
    state_ = State::ExpectKeyOrEndObject;
    stack_.top()->insert(key_, ptr);
    return true;
  case State::ExpectArrayValueOrEndArray:
    stack_.top()->append(ptr);
    return true;
  default:
    return true;
  }
}

} // namespace

ObjectSharedPtr Factory::loadFromString(const std::string& json) {
  ObjectHandler handler;
  auto json_container = JsonContainer(json.c_str(), &handler);

  nlohmann::json::sax_parse(json_container, &handler);

  if (handler.hasParseError()) {
    throw Exception(fmt::format("JSON supplied is not valid. Error({}): {}\n",
                                handler.getErrorPosition(), handler.getParseError()));
  }
  return handler.getRoot();
}

std::string Factory::serialize(absl::string_view str) {
  nlohmann::json j(str);
  return j.dump();
}

} // namespace Nlohmann
} // namespace Json
} // namespace Envoy


text:
package main

import (
	"log"
	"runtime"
	"syscall"
	"time"

	"github.com/u-root/u-root/pkg/libinit"
)

func cpuSetup() error {
	// The process reaper runs from here, and needs to run
	// as PID 1.
	runtime.LockOSThread()
	log.Printf(`

  ####   #####   #    #   ##
 #    #  #    #  #    #   ##
 #       #    #  #    #   ##
 #       #####   #    #   ##
 #    #  #       #    #
  ####   #        ####    ##
`)
	libinit.SetEnv()
	libinit.CreateRootfs()
	libinit.NetInit()
	// Wait for orphans, forever.
	// Since there is no way of knowning when we are
	// done for good, our work here is never done.
	// A complication is that for long periods of time, there
	// may be no orphans.In that case, sleep for one second,
	// and try again. This background load is hardly enough
	// to matter. And, in general, it will happen by definition
	// when there is nothing to wait for, i.e. there is nothing
	// on the node to be upset about.
	// Were this ever to be a concern, an option is to kick off
	// a process that will never exit, such that wait4 will always
	// block and always return when any child process exits.
	go func() {
		var numReaped int
		for {
			var (
				s syscall.WaitStatus
				r syscall.Rusage
			)
			p, err := syscall.Wait4(-1, &s, 0, &r)
			// Once per second, Wait 4 returns if there's nothing
			// else to do.
			if err != nil && err.Error() == "no child processes" {
				continue
			}
			verbose("orphan reaper: returns with %v", p)
			if p == -1 {
				verbose("Nothing to wait for, %d wait for so far", numReaped)
				time.Sleep(time.Second)
			}
			if err != nil {
				log.Printf("CPUD: a process exited with %v, status %v, rusage %v, err %v", p, s, r, err)
			}
			numReaped++
		}
	}()

	runtime.UnlockOSThread()
	return nil
}


text:
package com.gs.fw.common.mithra.test.domain.evo;

import com.gs.fw.common.mithra.finder.Operation;

import java.util.Collection;

public class EvoType3TxnTypesList extends EvoType3TxnTypesListAbstract
{

    public EvoType3TxnTypesList()
	{
		super();
	}

	public EvoType3TxnTypesList(int initialSize)
	{
		super(initialSize);
	}

	public EvoType3TxnTypesList(Collection c)
	{
		super(c);
	}

	public EvoType3TxnTypesList(Operation operation)
	{
		super(operation);
	}
}