text:
from __future__ import absolute_import, division, print_function

import logging

from decimal import Decimal
import warnings

from sqlalchemy import MetaData, create_engine
from sqlalchemy.exc import SAWarning

from manhattan.worker import Worker

from manhattan.log.memory import MemoryLog
from manhattan.log.timerotating import TimeRotatingLog

from manhattan.backend import Backend

from . import data
from .base import BaseTest, work_path

# Filter out pysqlite Decimal loss of precision warning.
warnings.filterwarnings('ignore',
                        '.*pysqlite does \*not\* support Decimal',
                        SAWarning,
                        'sqlalchemy.types')
# Turn unicode bind param warnings into errors.
warnings.filterwarnings('error',
                        r'Unicode type received non-unicode bind',
                        SAWarning,
                        'sqlalchemy.engine.default')

logging.basicConfig()
logging.getLogger('sqlalchemy.engine').setLevel(logging.DEBUG)

def drop_existing_tables(engine):
    "Drop all tables, including tables that aren't defined in metadata."
    temp_metadata = MetaData()
    temp_metadata.reflect(bind=engine)
    for table in reversed(temp_metadata.sorted_tables):
        table.drop(bind=engine)

class TestCombinations(BaseTest):

    def _check_backend_queries(self, backend):
        self.assertEqual(backend.count(u'add to cart', site_id=1), 5)
        self.assertEqual(backend.count(u'began checkout', site_id=1), 4)
        self.assertEqual(backend.count(u'viewed page', site_id=1), 6)

        self.assertEqual(backend.count(u'add to cart', site_id=2), 1)
        self.assertEqual(backend.count(u'began checkout', site_id=2), 1)
        self.assertEqual(backend.count(u'completed checkout', site_id=2), 0)
        self.assertEqual(backend.count(u'viewed page', site_id=2), 1)

        num = backend.count(u'completed checkout',
                            variant=(u'red checkout form', u'False'),
                            site_id=1)
        self.assertEqual(num, 2)

        revenue = backend.goal_value(u'completed checkout', site_id=1)
        self.assertEqual(revenue, Decimal('108.19'))

        revenue_nored = backend.goal_value(
            u'completed checkout',
            variant=(u'red checkout form', u'False'), site_id=1)
        self.assertEqual(revenue_nored, Decimal('43.2'))

        noreds = backend.count(variant=(u'red checkout form', u'False'),
                               site_id=1)
        self.assertEqual(noreds, 2)

        margin = backend.goal_value(u'order margin', site_id=1)
        margin = margin.quantize(Decimal('.01'))
        self.assertEqual(margin, Decimal('23.47'))

        margin_per = backend.goal_value(u'margin per session', site_id=1)
        margin_per = margin_per.quantize(Decimal('.01'))
        self.assertEqual(margin_per, Decimal('3.90'))

        margin_per_noreds = backend.goal_value(
            u'margin per session',
            variant=(u'red checkout form', u'False'), site_id=1)
        margin_per_noreds = margin_per_noreds.quantize(Decimal('.01'))
        self.assertEqual(margin_per_noreds, Decimal('5.16'))

        abandoned_carts = backend.count(u'abandoned cart', site_id=1)
        self.assertEqual(abandoned_carts, 1)

        abandoned_checkouts = backend.count(u'abandoned checkout', site_id=1)
        self.assertEqual(abandoned_checkouts, 1)

        abandoned_payment = backend.count(u'abandoned after payment failure',
                                          site_id=1)
        self.assertEqual(abandoned_payment, 1)

        abandoned_validation = backend.count(
            u'abandoned after validation failure', site_id=1)
        self.assertEqual(abandoned_validation, 0)

        self.assertEqual(backend.all_tests(),
                         [('red checkout form', 1602, 7246)])

        self.assertEqual(
            backend.results('red checkout form',
                            ['viewed page',
                             'add to cart',
                             'began checkout',
                             'completed checkout'],
                            site_id=1),
            {'True': [2, 0, 2, Decimal('64.99')],
             'False': [2, 0, 2, Decimal('43.2')]})

    def _get_backend(self, reset=False):
        url = 'sqlite:////tmp/manhattan-test.db'
        if reset:
            drop_existing_tables(create_engine(url))
        return Backend(url, flush_every=2, cache_size=5,
                       complex_goals=data.test_complex_goals)

    def test_resume(self):
        path = work_path('resume')

        backend = self._get_backend(reset=True)

        log_w = TimeRotatingLog(path)
        data.run_clickstream(log_w, first=0, last=25)

        log_r1 = TimeRotatingLog(path)
        worker1 = Worker(log_r1, backend)
        worker1.run()

        first_pointer = backend.get_pointer()
        self.assertIsNotNone(first_pointer)

        backend = self._get_backend(reset=False)

        data.run_clickstream(log_w, first=25)
        log_r2 = TimeRotatingLog(path)
        worker2 = Worker(log_r2, backend)
        worker2.run(resume=True)

        second_pointer = backend.get_pointer()
        self.assertIsNotNone(second_pointer)

        self._check_backend_queries(backend)

    def test_basic(self):
        path = work_path('basic')

        backend = self._get_backend(reset=True)

        log_w = TimeRotatingLog(path)
        data.run_clickstream(log_w)

        log_r = TimeRotatingLog(path)
        worker1 = Worker(log_r, backend)
        worker1.run()

        self._check_backend_queries(backend)

    def test_memory_log(self):
        log = MemoryLog()
        data.run_clickstream(log)

        backend = self._get_backend(reset=True)

        worker1 = Worker(log, backend)
        worker1.run(resume=False)

        self._check_backend_queries(backend)


text:
CREATE TABLE IF NOT EXISTS tmp_unittest_table (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(100),
registrationdate TIMESTAMP
)

redpajama_set_name: RedPajamaGithub


text:
package com.ezentis.ezentistrackingapp.views;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;

import com.liferay.mobile.screens.ddl.form.view.DDLFieldViewModel;
import com.liferay.mobile.screens.ddl.form.view.DDLFormViewModel;

/**
 * @author Silvio Santos
 */
public class DDLFormView
        extends com.liferay.mobile.screens.viewsets.material.ddl.form.DDLFormView implements DDLFormViewModel, View.OnClickListener {

    public DDLFormView(Context context) {
        super(context);
    }

    public DDLFormView(Context context, AttributeSet attributes) {
        super(context, attributes);
    }

    public DDLFormView(Context context, AttributeSet attributes, int defaultStyle) {
        super(context, attributes, defaultStyle);
    }

    @Override
    public void showRecordValues() {
        for (int i = 0; i < fieldsContainerView.getChildCount(); i++) {
            DDLFieldViewModel viewModel = (DDLFieldViewModel) fieldsContainerView.getChildAt(i);
            viewModel.refresh();

            if (viewModel.getField().isReadOnly()) {
                ((View) viewModel).setVisibility(View.GONE);
            }
        }
    }

}


text:
<?php
// vim: set ts=4 sts=4 sw=4 si noet:

function array_key_value($key, $array, $emptyValue = 0) {
	return array_key_exists($key, $array) ? $array[$key] : $emptyValue;
}

function _json_encode($array) {
	$buffer = json_encode($array);
	$buffer = str_replace('\r\n', '', $buffer);
	$buffer = str_replace('\n', '', $buffer);
	$buffer = str_replace('\r', '', $buffer);
	$buffer = str_replace('\t', '', $buffer);
	$buffer = str_replace('\"', '"', $buffer);
	$buffer = str_replace('"<script>', '', $buffer);
	$buffer = str_replace('<\/script>"', '', $buffer);
	return $buffer;
}


text:
Form Edit Data

                            Edit Data User

                                <?php foreach ($edit_data as $u){ ?>
                                    <form action="<?php echo base_url(). 'index.php/cuser/update'; ?>" method="post">

                                            Username
                                            <input type="hidden" class="form-control" name="id_user" value="<?php echo $u->id_user?>">
                                            <input type="text" class="form-control" name="username" value="<?php echo $u->username?>">
                                            Password
                                            <input class="form-control" name="password" value="<?php echo $u->password?>">
                                            Jabatan
                                            <input class="form-control" name="jabatan" value="<?php echo $u->jabatan?>">
                                            Hak Akses
                                            <input class="form-control" name="hakakses" value="<?php echo $u->hakakses?>">

                                        <button type="submit" class="btn btn-default">Update</button>

                                    </form>
                                <?php } ?>


text:
---
sitemap: false
---
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

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

    <title>HOMER | WebApp admin theme</title>

    <link rel="stylesheet" href="./css/font-awesome.css">
    <link rel="stylesheet" href="http://webapplayers.com/homer_admin-v1.6/vendor/metisMenu/dist/metisMenu.css">
    <link rel="stylesheet" href="http://webapplayers.com/homer_admin-v1.6/vendor/animate.css/animate.css">
    <link rel="stylesheet" href="http://webapplayers.com/homer_admin-v1.6/vendor/bootstrap/dist/css/bootstrap.css">

    <link rel="stylesheet" href="./fonts/pe-icon-7-stroke/css/pe-icon-7-stroke.css">
    <link rel="stylesheet" href="http://webapplayers.com/homer_admin-v1.6/fonts/pe-icon-7-stroke/css/helper.css">
    <link rel="stylesheet" href="http://webapplayers.com/homer_admin-v1.6/styles/style.css">

Homer - Responsive Admin Theme

Special AngularJS Admin Theme for small and medium webapp with very clean and aesthetic style and feel.

					Griggi

            HOMER APP

                    Logout

                John Dean

                        25 GB

                    Your Karma GB quota

                 Dashboard

                 Buy Karma GB

                 Profile

				You are now using AwesomeGuy-Griggi Disconnect

Your Current Bandwidth

7.1 Mbps

																Currently 3 Griggi users are connected on this network. The network is on for past 20 days

Available Data at this router

5 GB

															Billing cycle will renew on Aug 15. Total data per cycle that owner has allocated is 30 GB

 Data Used

20 MB

                            Your Karma GB used in this session

  Your speed history in current session (Mbps)

  Active duration

1 minute

                            and 20 seconds


text:
package ucar.nc2.iosp;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ucar.ma2.InvalidRangeException;
import ucar.ma2.Section;
import java.lang.invoke.MethodHandles;

/**
 * @author caron
 * @since Jan 2, 2008
 */
public class TestIndexChunker {
  private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

  @Test
  public void testFull() throws InvalidRangeException {
    int[] shape = new int[] {123, 22, 92, 12};
    Section section = new Section(shape);
    IndexChunker index = new IndexChunker(shape, section);
    assert index.getTotalNelems() == section.computeSize();
    IndexChunker.Chunk chunk = index.next();
    assert chunk.getNelems() == section.computeSize();
    assert !index.hasNext();
  }

  @Test
  public void testPart() throws InvalidRangeException {
    int[] full = new int[] {2, 10, 20};
    int[] part = new int[] {2, 5, 20};
    Section section = new Section(part);
    IndexChunker index = new IndexChunker(full, section);
    assert index.getTotalNelems() == section.computeSize();
    IndexChunker.Chunk chunk = index.next();
    assert chunk.getNelems() == section.computeSize() / 2;
  }

  @Test
  public void testChunkerTiled() throws InvalidRangeException {
    Section dataSection = new Section("0:0, 20:39,  0:1353 ");
    Section wantSection = new Section("0:2, 22:3152,0:1350");
    IndexChunkerTiled index = new IndexChunkerTiled(dataSection, wantSection);
    while (index.hasNext()) {
      Layout.Chunk chunk = index.next();
      System.out.println(" " + chunk);
    }
  }

  @Test
  public void testChunkerTiled2() throws InvalidRangeException {
    Section dataSection = new Section("0:0, 40:59,  0:1353  ");
    Section wantSection = new Section("0:2, 22:3152,0:1350");
    IndexChunkerTiled index = new IndexChunkerTiled(dataSection, wantSection);
    while (index.hasNext()) {
      Layout.Chunk chunk = index.next();
      System.out.println(" " + chunk);
    }
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="navigation">NO NAV</string>
</resources>


text:
function ScanMediaPlugin() {}

ScanMediaPlugin.prototype.scanFile = function(string, win, fail) {
    console.log("ScanMediaPlugin: scanFile called");
    cordova.exec(win, fail, "ScanMedia", "mediaScanner", [string]);
};

ScanMediaPlugin.prototype.test = function() {
    console.log("ScanMediaPlugin: Javascript Interface Loaded");
};

ScanMediaPlugin.install = function () {
    console.log("ScanMediaPlugin: Initializing");
    if(!window.plugins){
        window.plugins = {};
        console.log("ScanMediaPlugin: window.plugins initialized");
    }

    window.plugins.scanmedia = new ScanMediaPlugin();
    window.plugins.scanmedia.test();

    return window.plugins.scanmedia;
};

cordova.addConstructor(ScanMediaPlugin.install);


text:
use lib 'lib';
use strict;
use warnings;
use utf8;
use File::Slurp; # From CPAN
use JSON;

use AsposeStorageCloud::StorageApi;
use AsposeStorageCloud::ApiClient;
use AsposeStorageCloud::Configuration;

use AsposeBarCodeCloud::BarcodeApi;
use AsposeBarCodeCloud::ApiClient;
use AsposeBarCodeCloud::Configuration;
use AsposeBarCodeCloud::Object::BarcodeReader;

my $configFile = '../../config/config.json';
my $configPropsText = read_file($configFile);
my $configProps = decode_json($configPropsText);

my $data_path = '../../../../Data/';
my $out_path = $configProps->{'out_folder'};

#ExStart:1
$AsposeBarCodeCloud::Configuration::app_sid = $configProps->{'app_sid'};
$AsposeBarCodeCloud::Configuration::api_key = $configProps->{'api_key'};
$AsposeBarCodeCloud::Configuration::debug = 1;
$AsposeStorageCloud::Configuration::app_sid = $AsposeBarCodeCloud::Configuration::app_sid;
$AsposeStorageCloud::Configuration::api_key = $AsposeBarCodeCloud::Configuration::api_key;

# Instantiate Aspose.Storage API SDK
my $storageApi = AsposeStorageCloud::StorageApi->new();

# Instantiate Aspose.BarCode API SDK
my $barcodeApi = AsposeBarCodeCloud::BarcodeApi->new();

# Set input file name
my $name = 'sample-barcode.jpeg';

# Set BarcodeReader object with mode for checksum validation during recognition
my @barcodeReaderBody = AsposeBarCodeCloud::Object::BarcodeReader->new('StripFNC' => 'TRUE', 'BinarizationHints' => 'ComplexBackground', 'checksumValidation' => 'On');

# Upload file to aspose cloud storage
my $response = $storageApi->PutCreate(Path => $name, file => $data_path.$name);

# Invoke Aspose.BarCode Cloud SDK API to recognition of a barcode from file on server with parameters in body
$response = $barcodeApi->PutBarcodeRecognizeFromBody(name => $name, body =>@barcodeReaderBody);

if($response->{'Status'} eq 'OK'){

	foreach my $barcode (@{$response->{'Barcodes'}}){
    print "\n Type :: $barcode->{'BarcodeType'}";
    print "\n Codetext :: $barcode->{'BarcodeValue'}";
	}
}
#ExEnd:1


text:
//Add click event to search button on Index Page

$('#search_form_main').submit(function () {
    //console.log("running");
    //sendContactForm();
    return false;
});

$("#topSearchBtn_inner").click(function () {
    var searchTag = $('#keyword_top').val();
    //console.log(searchTag);
    var url = "result?" + searchTag;
    window.open(url, '_self', false);
});
// hover function on User Login

$("#userLoginBox").hover(function () {
    $(this).css("cursor", "pointer");
    $("#userLogin").css("color", "#404040");
    $("#loginLogo").css("background", "url('images/key_hover.svg') no-repeat");

}, function () {
    $("#userLogin").css("color", "#666666");
    $("#loginLogo").css("background", "url('images/key.svg') no-repeat");
});

// hover function for show/hide Tag Clouds (Top Page)

$("#tagSwitch").hover(function () {
    $(this).css("cursor", "pointer");
    $("#showTag").css("color", "#404040");
    $("#tagIcon").css("background", "url('images/tags_hover.svg') no-repeat");
    $("#tag_underline").css("border-top", "1px solid #404040");

}, function () {
    $("#showTag").css("color", "#666666");
    $("#tagIcon").css("background", "url('images/tags.svg') no-repeat");
    $("#tag_underline").css("border-top", "1px solid #666666");
});

// click function on show/hide Tag Clouds (Top Page)

$("#tagSwitch").click(function () {
    if (!$(this).hasClass("active")) {
        $(this).addClass("active");
        $("#tagIcon").css("background", "url('images/tags_hover.svg') no-repeat");
        $("#showTag").html(" hide");
        $("#tagCloudbox").css("display", "block");
        $("#tag_underline").css("border-top", "1px solid #404040").animate({
            width: "280px"
        }, 300);
    } else {
        $(this).removeClass("active");
        $("#tagIcon").css("background", "url('images/tags.svg') no-repeat");
        $("#showTag").html(" Show popular tags");
        $("#tagCloudbox").css("display", "none");
        $("#tag_underline").css("border-top", "1px solid #66666").animate({
            width: "150px"
        }, 300);
    }
});

////////////////////////////// Result Page //////////////////////////////

// hover function on User Login (Result page)

$("#userLoginBox_result").hover(function () {
    $(this).css("cursor", "pointer");
    $("#userLogin_result").css("color", "rgb(89, 184, 230)");
    $("#loginLogo_result").css("background", "url('images/key_result_hover.svg') no-repeat");

}, function () {
    $("#userLogin_result").css("color", "#ffffff");
    $("#loginLogo_result").css("background", "url('images/key_result.svg') no-repeat");
});

// hover function on open/close button (Result page)

$("#openCloseBtn_filter").hover(function () {
    if ($(this).hasClass("closeSwitch")) {
        $(this).css("cursor", "pointer");
        $(this).css("background", "url('images/close_hover.svg') no-repeat");
        $(this).css("background-size", "12px 12px");
    } else if ($(this).hasClass("openSwitch")) {
        $(this).css("cursor", "pointer");
        $(this).css("background", "url('images/open_hover.svg') no-repeat");
        $(this).css("background-size", "15px 15px");
    }
}, function () {
    if ($(this).hasClass("closeSwitch")) {
        $(this).css("background", "url('images/close.svg') no-repeat");
        $(this).css("background-size", "12px 12px");
    } else if ($(this).hasClass("openSwitch")) {
        $(this).css("background", "url('images/open.svg') no-repeat");
        $(this).css("background-size", "15px 15px");
    }
});

// click function on open/close button (Result page)

$("#openCloseBtn_filter").click(function () {
    if ($("#filteringPanel").hasClass("active")) {
        $("#filteringPanel").removeClass("active");
        $(this).addClass("openSwitch");
        $(this).removeClass("closeSwitch");
        $("#filteringPanel").animate({
            left: "-325px"
        }, 450);
        $("#mainPanel").animate({
            marginLeft: "25px"
        }, 350);
        $("#mainPanel").animate({
            width: "calc(100%-0px)"
        }, 450);
        $(function () {
            setTimeout(function () {
                $("#openCloseBtn_filter").css("background", "url('images/open.svg') no-repeat");
                $("#openCloseBtn_filter").css("background-size", "15px 15px");
            }, 250);
        });

    } else {
        $("#filteringPanel").addClass("active");
        $(this).removeClass("openSwitch");
        $(this).addClass("closeSwitch");
        $("#filteringPanel").animate({
            left: "0px"
        }, 450);
        $("#mainPanel").animate({
            marginLeft: "350px"
        }, 350);
        $("#mainPanel").animate({
            width: "calc(100%-450px)"
        }, 450);
        $(function () {
            setTimeout(function () {
                $(this).css("background", "url('images/close.svg') no-repeat");
                $(this).css("background-size", "12px 12px");
            }, 250);
        });
        console.log("active");
    }
});

// hover function for show/hide Tag Clouds (Result Page: filtering panel)

$("#tagSwitch_filter").hover(function () {
    $(this).css("cursor", "pointer");
    $("#showTag_filter").css("color", "#404040");
    $("#tagIcon_filter").css("background", "url('images/tags_hover.svg') no-repeat");
    $("#tag_underline_filter").css("border-top", "1px solid #404040");
}, function () {
    $("#showTag_filter").css("color", "#666666");
    $("#tagIcon_filter").css("background", "url('images/tags.svg') no-repeat");
    $("#tag_underline_filter").css("border-top", "1px solid #666666");
});

// click function on show/hide Tag Clouds (Result Page: filtering panel)

$("#tagSwitch_filter").click(function () {
    if (!$(this).hasClass("active")) {
        $(this).addClass("active");
        $("#tagIcon_filter").css("background", "url('images/tags_hover.svg') no-repeat");
        $("#showTag_filter").html(" hide");
        $("#tagCloudbox_filter").css("display", "block");
        $("#tag_underline_filter").css("border-top", "1px solid #404040").animate({
            width: "230px"
        }, 200);
    } else {
        $(this).removeClass("active");
        $("#tagIcon_filter").css("background", "url('images/tags.svg') no-repeat");
        $("#showTag_filter").html(" Show popular tags");
        $("#tagCloudbox_filter").css("display", "none");
        $("#tag_underline_filter").css("border-top", "1px solid #66666").animate({
            width: "150px"
        }, 200);
    }
});

////////////////////////////// Check Box in the Sidebar //////////////////////////////

$(document).ready(function () {
    // Set variables of selectors
    var $tgt_parent = $("input.check-parent");
    var $tgt_child = $("input.check-child");

    // Parent checkbox
    $tgt_parent.click(function () {
        $(this).parents("div.parent").find('ul li input.check-child').prop('checked', this.checked);
    });

    // Children check box
    $tgt_child.click(function () {
        var checkNum1 = $(this).parents('ul').find('li input.check-child:checked').length;
        var listNum1 = $(this).parents('ul').find('li').length;
        if (checkNum1 == listNum1) {
            $(this).parents("div.parent").find("input.check-parent").prop('checked', true);
        } else {
            $(this).parents("div.parent").find("input.check-parent").prop('checked', false);
        }

    });
});

//Check parent checkboxes when their children checkboxes are all checked
$(document).ready(function () {
    var checkNum2 = $("input.check-child:checked").parents('ul').find('li input.check-child:checked').length;
    var listNum2 = $("input.check-child:checked").parents('ul').find('li').length;
    if (checkNum2 == listNum2) {
        $("input.check-child:checked").parents("div.parent").find("input.check-parent:checkbox").prop('checked', true);
    }

});

////////////////////////////// Check Box in the Sidebar //////////////////////////////

// Close side panel for filtring when users change window size
$(window).resize(function () {
    var w = $(window).width();
    var sm = 768;

    if (w >= sm) {
        // console.log("oepn filtering panel");
        $('#filteringPanel').addClass("active");
        $("#openCloseBtn_filter").removeClass("openSwitch");
        $("#openCloseBtn_filter").addClass("closeSwitch");
        $("#filteringPanel").animate({
            left: "0px"
        }, 10);
        $("#mainPanel").animate({
            marginLeft: "350px"
        }, 10);
        $("#mainPanel").animate({
            width: "calc(100%-450px)"
        }, 10);
        $("#openCloseBtn_filter").css("background", "url('images/close.svg') no-repeat");
        $("#openCloseBtn_filter").css("background-size", "12px 12px");
        // console.log("active");
    } else {
        $("#filteringPanel").removeClass("active");
        $("#openCloseBtn_filter").addClass("openSwitch");
        $("#openCloseBtn_filter").removeClass("closeSwitch");
        $("#filteringPanel").animate({
            left: "-325px"
        }, 10);
        $("#mainPanel").animate({
            marginLeft: "0px"
        }, 10);
        $("#mainPanel").animate({
            width: "calc(100%-45px)"
        }, 10);
        $("#openCloseBtn_filter").css("background", "url('images/open.svg') no-repeat");
        $("#openCloseBtn_filter").css("background-size", "15px 15px");
        // console.log("not active");
    }
});

// Close side panel for filtring if screen size is small when users load page

$(function () {
    var w = $(window).width();
    var sm = 768;

    if (w >= sm) {
        // console.log("oepn filtering panel");
        $('#filteringPanel').addClass("active");
        $('#openCloseBtn_filter').removeClass("openSwitch");
        $('#openCloseBtn_filter').addClass("closeSwitch");
        $("#filteringPanel").animate({
            left: "0px"
        }, 100);
        $("#mainPanel").animate({
            marginLeft: "350px"
        }, 100);
        $("#mainPanel").animate({
            width: "calc(100%-450px)"
        }, 100);
        // $(function(){ setTimeout (function(){
        $("#openCloseBtn_filter").css("background", "url('images/close.svg') no-repeat");
        $("#openCloseBtn_filter").css("background-size", "12px 12px");
        // }, 100);
        // console.log("active");
    } else if (w < sm) {
        $("#filteringPanel").removeClass("active");
        $('#openCloseBtn_filter').addClass("openSwitch");
        $('#openCloseBtn_filter').removeClass("closeSwitch");
        $("#filteringPanel").animate({
            left: "-325px"
        }, 10);
        $("#mainPanel").animate({
            marginLeft: "0px"
        }, 10);
        $("#mainPanel").animate({
            width: "calc(100%-0px)"
        }, 10);
        // $(function(){ setTimeout (function(){
        $("#openCloseBtn_filter").css("background", "url('images/open.svg') no-repeat");
        $("#openCloseBtn_filter").css("background-size", "15px 15px");
        // }, 100);
    }
});

$(window).resize(function () {

    var w = $(window).width();
    var sm = 500,
        md = 992,
        lg = 1200;

    if (w < sm) {
        console.log("extra small device");
        $('.table_smDivice,.table_mdDivice, .datatype_text').addClass("columnHide");
    } else if (w >= sm && w < md) {
        $('.table_mdDivice, .datatype_text').addClass("columnHide");
        $('.table_smDivice').removeClass("columnHide");
        console.log("small device");
    } else if (w >= md && w < lg) {
        $('.table_smDivice, .table_mdDivice, .datatype_text').removeClass("columnHide");
        console.log("medium device");
    }

    // else if (w >= lg){
    //      console.log("large device");
    //      $('.table_xsDivice, .table_smDivice, .table_mdDivice').css("visibility", "visible");
    // }

});

/// Modal Window Functions ///

$("dl.accordion").prepend("    ");

$(".icon").css("background", function () {
    if ($("dt#metaTitle").hasClass("active")) {
        return "url('images/downarrow.svg') no-repeat 50% 50%"
    } else if ($("dt#metaTitle").not(".active")) {
        return "url('images/rightarrow.svg') no-repeat 50% 50%"
    }
});

$("#modalCloseBtn").hover(function () {
    $(this).css("cursor", "pointer");
    $(this).css("background", "url('images/close_hover.svg') no-repeat");
    $(this).css("background-size", "12px 12px");
}, function () {
    $(this).css("background", "url('images/close.svg') no-repeat");
    $(this).css("background-size", "12px 12px");
});

$("dt#metaTitle").hover(function () {
        //$(this).addClass("hover");
        $(this).css("cursor", "pointer");
        $(this).css("color", "rgb(89, 184, 230)");
        $(".icon").css("background", function () {
            if ($("dt#metaTitle").hasClass("active")) {
                return "url('images/downarrow_hover.svg') no-repeat 50% 50%"
            } else {
                return "url('images/rightarrow_hover.svg') no-repeat 50% 50%"
            }
        });

    }, function () {
        //$(this).removeClass("hover");
        $(this).css("color", function () {
            if ($(this).hasClass("active")) {
                return "rgb(51, 103, 153)"
            } else {
                return "#797979"
            }
        });
        $(".icon").css("background", function () {
            if ($("dt#metaTitle").hasClass("active")) {
                return "url('images/downarrow.svg') no-repeat 50% 50%"
            } else {
                return "url('images/rightarrow.svg') no-repeat 50% 50%"
            }
        });
    })
    .click(
        function () {
            if (!$(this).hasClass("active")) {
                $(this).addClass("active");
                $(".icon").css("background", "url('images/downarrow.svg') no-repeat 50% 50%");
                // $("dt").css("color", "#797979");
                $("dd#metadd").slideDown("fast");

                $(this).css("color", "rgb(51, 103, 153)");
                // $("> .icon", this).css("background", "url('images/helpTab/downarrow.svg') no-repeat 50% 50%");
                // $("+ dd", this).slideDown("fast");
            } else if ($(this).hasClass("active")) {
                $(this).removeClass("active");
                $("dd#metadd").slideUp("fast");
                $(".icon").css("background", "url('images/rightarrow.svg') no-repeat 50% 50%");
                $(this).css("color", "#797979");
            }

        });

$('body').on('click', function (e) {
    $('[data-toggle="popover"]').each(function () {
        //the 'is' for buttons that trigger popups
        //the 'has' for icons within a button that triggers a popup
        if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
            $(this).popover('hide');
        }
    });
});

$("#loginEditBox").hover(function () {
    $("#loginEditText").css("color", "rgb(89, 184, 230)");
    $("#loginEditIcon").css("background", "url(images/edit_hover.svg) no-repeat left top").css("background-size", "15px 15px").css("background-position", "0px 2px").css("padding-left", "20px");

}, function () {
    $("#loginEditText").css("color", "#797979");
    $("#loginEditIcon").css("background", "url(images/edit.svg) no-repeat left top").css("background-size", "15px 15px").css("background-position", "0px 2px").css("padding-left", "20px");
});

// Fader for modal window
// // click btn
// $("#feedbackBtn").click(function(){
//     // Current content
//     $("#modalContent").fadeOut(1000, function(){
//         // Fade in form for feeback
//         $("#feedbackForm").fadeIn(1000);
//     })
// });


text:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace vLogs.Loggers
{
    using Objects;
    using Utilities;

    /// <summary>
    /// Prepares log objects as text before logging.
    /// </summary>
    public abstract class BinaryLogger
        : IObjectLogger
    {
        /// <summary>
        /// Gets the encoding used to store character strings.
        /// </summary>
        public Encoding Encoding { get; private set; }

        /// <summary>
        /// Initializes the <see cref="vLogs.Loggers.BinaryLogger"/>.
        /// </summary>
        /// <param name="encoding">optional; The encoding used to store character strings. The default value (null) menas UTF-8.</param>
        public BinaryLogger(Encoding encoding = null)
        {
            if (encoding == null)
                encoding = Encoding.UTF8;

            this.Encoding = encoding;
        }

        #region IObjectLogger Members

        /// <summary>
        /// Logs the specified object as string.
        /// </summary>
        /// <param name="o"></param>
        /// <returns>True if the object was logged; otherwise false.</returns>
        public bool Log(LogObject o)
        {
            using (var ms = new MemoryStream())
            using (var b = new BinaryWriter(ms))
            {
                b.WriteStrings(o.Sources);

                b.Write(o.Timestamp.Ticks);
                b.Write(o.Priority);
                b.Write((byte)o.Flags);
                b.Write(o.Indent);

                b.Write((byte)o.PayloadTypes);

                if ((o.PayloadTypes & PayloadTypes.Message) != 0)
                {
                    var msg = (MessagePayload)o.Payloads.Where(p => p is MessagePayload).First();

                    b.Write((byte)msg.MessageType);
                    b.WriteSpaceEfficientString(msg.Message, Encoding);
                }

                if ((o.PayloadTypes & PayloadTypes.Exception) != 0)
                {
                    var exc = (ExceptionPayload)o.Payloads.Where(p => p is ExceptionPayload).First();

                    b.WriteStrings(exc.Exceptions);
                }

                if ((o.PayloadTypes & PayloadTypes.KeyValue) != 0)
                {
                    var kvp = (KeyValuePayload)o.Payloads.Where(p => p is KeyValuePayload).First();

                    b.WriteKeyValues(kvp.Collection);
                }

                b.Flush();
                return Log(o, ms.ToArray());
            }
        }

        #endregion

        /// <summary>
        /// Logs the specified byte array representing a <see cref="vLogs.Objects.LogObject"/>.
        /// </summary>
        /// <param name="o"></param>
        /// <param name="b"></param>
        /// <returns>True if the object was logged; otherwise false.</returns>
        protected abstract bool Log(LogObject o, byte[] b);
    }
}


text:
const Koa = require('koa');
const app = new Koa();
const Router = require('koa-router');

let home = new Router();
home.get('/jspang', async (ctx) => {
  ctx.body = 'Home JSPang';
}).get('/todo', async (ctx) => {
  ctx.body = 'Home ToDo';
});

let page = new Router();
page.get('/jspang', async (ctx) => {
  ctx.body = 'Page JSPang';
}).get('/todo', async (ctx) => {
  ctx.body = 'Page ToDo';
});

//封装所有子路由
let router = new Router();
router.use('/home', home.routes(), home.allowedMethods());
router.use('/page', page.routes(), page.allowedMethods());

//加载路由中间件
app.use(router.routes()).use(router.allowedMethods());

app.listen(3000, () => {
  console.log('[demo] server is starting at port 3000');
});


text:
import fs = require('fs');
import path = require('path');
import chai = require('chai');
import build = require('./build');

const generatedFolder = path.join(__dirname, 'generated');
const baselineFolder = path.join(__dirname, 'baselines');
const casesFolder = path.join(__dirname, 'cases');

function ensureCleanGeneratedFolder() {
    if (fs.existsSync(generatedFolder)) {
        for (const fileName of fs.readdirSync(generatedFolder)) {
            fs.unlinkSync(path.join(generatedFolder, fileName));
        }
        fs.rmdirSync(generatedFolder);
    }
    fs.mkdirSync(generatedFolder);
}

// Ensure generated folder
ensureCleanGeneratedFolder();

// Generate the new baselines
for (const fileName of fs.readdirSync(casesFolder)) {
    describe("Generating baseline for " + fileName, () => {
        let wholeBaseline: string;
        let parsedFileName: path.ParsedPath;

        before(done => {
            const text = fs.readFileSync(path.join(casesFolder, fileName), 'utf8');
            parsedFileName  = path.parse(fileName);
            build.generateScopes(text, parsedFileName).then(result => {
                wholeBaseline = result;
                done();
            })
        });
        after(() => {
            wholeBaseline = undefined!;
            parsedFileName = undefined!;
        });

        it('Comparing baseline', () => {
            assertBaselinesMatch(parsedFileName.name + '.baseline.txt', wholeBaseline);
        });
    });
}

function assertBaselinesMatch(file: string, generatedText: string) {
    const generatedFileName = path.join(generatedFolder, file);
    fs.writeFileSync(generatedFileName, generatedText);

    const baselineFile = path.join(baselineFolder, file);
    if (fs.existsSync(baselineFile)) {
        chai.assert.equal(generatedText, fs.readFileSync(baselineFile, 'utf8'), "Expected baselines to match: " + file);
    } else {
        chai.assert(false, "New generated baseline");
    }
}


text:
package model

import (
	"github.com/fuxiaohei/purine/src/log"
	"github.com/fuxiaohei/purine/src/vars"
)

const (
	COMMENT_FROM_ARTICLE = "article"
	COMMENT_FROM_PAGE    = "page"

	COMMENT_STATUS_APPROVED = "approved"
	COMMENT_STATUS_WAIT     = "wait"
	COMMENT_STATUS_SPAM     = "spam"
	COMMENT_STATUS_DELETED  = "deleted"
)

type Comment struct {
	Id         int64  `json:"id"`
	Name       string `json:"name"`
	UserId     int64  `json:"user_id"`
	Email      string `json:"-"`
	Url        string `json:"url"`
	AvatarUrl  string `json:"avatar"`
	Body       string `json:"body"`
	CreateTime int64  `xorm:"created" json:"created"`
	Status     string `xorm:"index(status)" json:"status"`

	UserIp    string `json:"ip"`
	UserAgent string `json:"user_agent"`

	From     string `xorm:"index(from)" json:"-"`
	FromId   int64  `xorm:"index(from)" json:"-"`
	ParentId int64  `xorm:"index(parent)" json:"parent"`
}

// save a comment,
// always insert new
func SaveComment(c *Comment) error {
	if _, err := vars.Db.Insert(c); err != nil {
		log.Error("Db|SaveComment|%s", err.Error())
		return err
	}
	return nil
}

// get a comment by column and value
func GetCommentBy(col string, v interface{}) (*Comment, error) {
	c := new(Comment)
	if isIdColumn(col) {
		if _, err := vars.Db.Id(v).Get(c); err != nil {
			log.Error("Db|GetCommentBy|%s,%v|%s", col, v, err.Error())
			return nil, err
		}
	} else {
		if _, err := vars.Db.Where(col+" = ?", v).Get(c); err != nil {
			log.Error("Db|GetCommentBy|%s,%v|%s", col, v, err.Error())
			return nil, err
		}
	}
	if c.Id > 0 {
		return c, nil
	}
	return nil, nil
}

// change comment status
func ChangeCommentStatus(cid int64, status string) (*Comment, error) {
	c := &Comment{Status: status}
	if _, err := vars.Db.Id(cid).Cols("status").Update(c); err != nil {
		log.Error("Db|ChangeCommentStatus|%d,%s|%s", cid, status, err.Error())
		return nil, err
	}
	return GetCommentBy("id", cid)
}

// list all comments
func ListAllComments(page, size int64, order string) ([]*Comment, error) {
	comments := make([]*Comment, 0)
	if err := vars.Db.OrderBy(order).
		Where("status != ?", COMMENT_STATUS_DELETED).
		Limit(int(size), int((page-1)*size)).Find(&comments); err != nil {
		log.Error("Db|ListAllComments|%s|%d,%d|%s|%s", "all", page, size, order, err.Error())
		return nil, err
	}
	return comments, nil
}

// list comments in specific status
func ListStatusComments(status string, page, size int64, order string) ([]*Comment, error) {
	comments := make([]*Comment, 0)
	if err := vars.Db.Where("status = ?", status).OrderBy(order).
		Limit(int(size), int((page-1)*size)).Find(&comments); err != nil {
		log.Error("Db|ListStatusComments|%s|%d,%d|%s|%s", status, page, size, order, err.Error())
		return nil, err
	}
	return comments, nil
}

// list all comments in article
func ListAllCommentsInArticle(aid, page, size int64, order string) ([]*Comment, error) {
	comments := make([]*Comment, 0)
	if err := vars.Db.
		OrderBy(order).
		Where("status != ? AND `from` = ? AND `from_id` = ?", COMMENT_STATUS_DELETED, COMMENT_FROM_ARTICLE, aid).
		Limit(int(size), int((page-1)*size)).Find(&comments); err != nil {
		log.Error("Db|ListAllCommentsInArticle|%s|%d,%d|%s|%s", "all", page, size, order, err.Error())
		return nil, err
	}
	return comments, nil
}

// list comments by status in article
func ListStatusCommentsInArticle(status string, aid, page, size int64, order string) ([]*Comment, error) {
	comments := make([]*Comment, 0)
	if err := vars.Db.
		Where("status = ? AND `from` = ? AND `from_id` = ?", status, COMMENT_FROM_ARTICLE, aid).
		OrderBy(order).
		Limit(int(size), int((page-1)*size)).Find(&comments); err != nil {
		log.Error("Db|ListStatusCommentsInArticle|%s|%d,%d|%s|%s", status, page, size, order, err.Error())
		return nil, err
	}
	return comments, nil
}

// check email's approved comment count
func CountApprovedCommentsByEmail(email string) int64 {
	c, err := vars.Db.Where("status = ? AND email = ?", COMMENT_STATUS_APPROVED, email).Count(new(Comment))
	if err != nil {
		log.Error("Db|CountApprovedCommentsByEmail|%s|%s", email, err.Error())
		return 0
	}
	return c
}


text:
#include "gm/gm.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkColor.h"
#include "include/core/SkFont.h"
#include "include/core/SkFontMetrics.h"
#include "include/core/SkFontStyle.h"
#include "include/core/SkFontTypes.h"
#include "include/core/SkPaint.h"
#include "include/core/SkRefCnt.h"
#include "include/core/SkScalar.h"
#include "include/core/SkSize.h"
#include "include/core/SkString.h"
#include "include/core/SkTypeface.h"
#include "src/core/SkEnumerate.h"
#include "tools/Resources.h"
#include "tools/ToolUtils.h"

#include <string.h>
#include <initializer_list>

namespace skiagm {
class ScaledEmojiRenderingGM : public GM {
public:
    ScaledEmojiRenderingGM() {}

protected:
    struct Test {
        enum class Source { Resource, Portable };
        Source const fontSource;
        char const * const fontName;
        char const * const text;
    };
    static constexpr char const * const sampleText = ToolUtils::emoji_sample_text();
    static constexpr const Test tests[] = {
        { Test::Source::Resource, "fonts/colr.ttf"     , sampleText  },
        { Test::Source::Resource, "fonts/sbix.ttf"     , sampleText  },
        { Test::Source::Resource, "fonts/cbdt.ttf"     , sampleText  },
        { Test::Source::Portable, "Emoji"              , sampleText  },
        { Test::Source::Resource, "fonts/SampleSVG.ttf", "abcdefghij" },
    };
    sk_sp<SkTypeface> typefaces[std::size(tests)];
    void onOnceBeforeDraw() override {
        for (auto&& [i, test] : SkMakeEnumerate(tests)) {
            if (test.fontSource == Test::Source::Resource) {
                typefaces[i] = MakeResourceAsTypeface(test.fontName);
            } else if (test.fontSource == Test::Source::Portable) {
                typefaces[i] = ToolUtils::create_portable_typeface(test.fontName, SkFontStyle());
            } else {
                SK_ABORT("Unknown test type");
            }
        }
    }

    SkString onShortName() override {
        return SkString("scaledemoji_rendering");
    }

    SkISize onISize() override { return SkISize::Make(1200, 1200); }

    void onDraw(SkCanvas* canvas) override {

        canvas->drawColor(SK_ColorGRAY);
        SkPaint textPaint;
        textPaint.setColor(SK_ColorCYAN);

        SkPaint boundsPaint;
        boundsPaint.setStrokeWidth(2);
        boundsPaint.setStyle(SkPaint::kStroke_Style);
        boundsPaint.setColor(SK_ColorGREEN);

        SkPaint advancePaint;
        advancePaint.setColor(SK_ColorRED);

        SkScalar y = 0;
        for (auto&& [i, test] : SkMakeEnumerate(tests)) {
            SkFont font(typefaces[i]);
            font.setEdging(SkFont::Edging::kAlias);

            const char* text = test.text;
            SkFontMetrics metrics;

            for (SkScalar textSize : { 70, 150 }) {
                font.setSize(textSize);
                font.getMetrics(&metrics);
                // All typefaces should support subpixel mode
                font.setSubpixel(true);

                y += -metrics.fAscent;

                SkScalar x = 0;
                for (bool fakeBold : { false, true }) {
                    font.setEmbolden(fakeBold);
                    SkRect bounds;
                    SkScalar advance = font.measureText(text, strlen(text), SkTextEncoding::kUTF8,
                                                        &bounds, &textPaint);
                    canvas->drawSimpleText(text, strlen(text), SkTextEncoding::kUTF8,
                                           x, y, font, textPaint);
                    if ((false)) {
                        bounds.offset(x, y);
                        canvas->drawRect(bounds, boundsPaint);
                        SkRect advanceRect = SkRect::MakeLTRB(x, y + 2, x + advance, y + 4);
                        canvas->drawRect(advanceRect, advancePaint);
                    }
                    x += bounds.width() * 1.2;
                }
                y += metrics.fDescent + metrics.fLeading;
                x = 0;
            }
        }
    }

private:
    using INHERITED = GM;
};

//////////////////////////////////////////////////////////////////////////////

DEF_GM(return new ScaledEmojiRenderingGM;)
}  // namespace skiagm


text:
'''Python six compatibility'''
__all__ = ['PY3', 'cStringIO', 'shlex_quote']

import sys
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
if PY3:  # pragma: no cover
    from io import StringIO as cStringIO
    from pipes import quote as shlex_quote
    text_type = str
else:  # pragma: no cover
    from cStringIO import StringIO as cStringIO
    from pipes import quote as shlex_quote
    text_type = unicode  # noqa


text:
[Science Journal][play-store] allows you to gather data from the world around you. It uses sensors to measure your environment, like light and sound, so you can graph your data, record your experiments, and organize your questions and ideas. It's the lab notebook you always have with you.

This sketch is used to make an Arduino that has Bluetooth Low Energy
(BLE) capabilities (such as the RedBear BLEND board and the Arduino 101)
send data from its pins to Science Journal.  The arduinoUno firmware
is provided for reference, but does not work because of limited RAM on
the Uno.

## Building the firmware

This project uses [Platform IO](http://platformio.org/get-started).
Please refer to [Build Guide][guide]

## Contributing

Please read our [guidelines for contributors][contributing].

## License

Open Science Journal is licensed under the [Apache 2 license][license].

## More

Science Journal is brought to you by [Making & Science][making-science], an initiative by Google. Open Science Journal is not an official Google product.

[play-store]: https://play.google.com/store/apps/details?id=com.google.android.apps.forscience.whistlepunk
[contributing]: https://github.com/google/science-journal-arduino/blob/master/CONTRIBUTING
[license]: https://github.com/google/science-journal-arduino/blob/master/LICENSE
[making-science]: https://makingscience.withgoogle.com
[guide]: https://github.com/google/science-journal-arduino/tree/master/guide


text:
import { config } from './../../src/config/index';

export const configTest = () => {
  describe('Config', () => {
    it('Should return the current environment', () => {
      config.env = 'test';
    });
  });
};


text:
package brooklyn.entity.brooklynnode;

import java.net.URI;
import java.util.List;
import java.util.Map;

import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import brooklyn.config.ConfigKey;
import brooklyn.config.render.RendererHints;
import brooklyn.entity.Effector;
import brooklyn.entity.Entity;
import brooklyn.entity.basic.BrooklynTaskTags;
import brooklyn.entity.basic.SoftwareProcessImpl;
import brooklyn.entity.effector.EffectorBody;
import brooklyn.entity.effector.Effectors;
import brooklyn.event.feed.ConfigToAttributes;
import brooklyn.event.feed.http.HttpFeed;
import brooklyn.event.feed.http.HttpPollConfig;
import brooklyn.event.feed.http.HttpValueFunctions;
import brooklyn.util.collections.Jsonya;
import brooklyn.util.collections.MutableMap;
import brooklyn.util.config.ConfigBag;
import brooklyn.util.exceptions.Exceptions;
import brooklyn.util.http.HttpTool;
import brooklyn.util.http.HttpTool.HttpClientBuilder;
import brooklyn.util.http.HttpToolResponse;
import brooklyn.util.javalang.JavaClassNames;
import brooklyn.util.net.Urls;
import brooklyn.util.stream.Streams;
import brooklyn.util.task.Tasks;
import brooklyn.util.text.Strings;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.gson.Gson;

public class BrooklynNodeImpl extends SoftwareProcessImpl implements BrooklynNode {

    private static final Logger log = LoggerFactory.getLogger(BrooklynNodeImpl.class);

    static {
        RendererHints.register(WEB_CONSOLE_URI, new RendererHints.NamedActionWithUrl("Open"));
    }

    private HttpFeed httpFeed;

    public BrooklynNodeImpl() {
        super();
    }

    public BrooklynNodeImpl(Entity parent) {
        super(parent);
    }

    @Override
    public Class getDriverInterface() {
        return BrooklynNodeDriver.class;
    }

    @Override
    public void init() {
        super.init();
        getMutableEntityType().addEffector(DeployBlueprintEffectorBody.DEPLOY_BLUEPRINT);
    }

    public static class DeployBlueprintEffectorBody extends EffectorBody<String> implements DeployBlueprintEffector {
        public static final Effector<String> DEPLOY_BLUEPRINT = Effectors.effector(BrooklynNode.DEPLOY_BLUEPRINT).impl(new DeployBlueprintEffectorBody()).build();

        // TODO support YAML parsing
        // TODO define a new type YamlMap for the config key which supports coercing from string and from map
        public static Map<String,Object> asMap(ConfigBag parameters, ConfigKey<?> key) {
            Object v = parameters.getStringKey(key.getName());
            if (v==null || (v instanceof String && Strings.isBlank((String)v)))
                return null;
            if (v instanceof Map)
                return (Map<String, Object>) v;

            if (v instanceof String) {
                // TODO ideally, parse YAML
                return new Gson().fromJson((String)v, Map.class);
            }
            throw new IllegalArgumentException("Invalid "+JavaClassNames.simpleClassName(v)+" value for "+key+": "+v);
        }

        @Override
        public String call(ConfigBag parameters) {
            String plan = extractPlanYamlString(parameters);
            return submitPlan(plan);
        }

        protected String extractPlanYamlString(ConfigBag parameters) {
            Object planRaw = parameters.getStringKey(BLUEPRINT_CAMP_PLAN.getName());
            if (planRaw instanceof String && Strings.isBlank((String)planRaw)) planRaw = null;

            String url = parameters.get(BLUEPRINT_TYPE);
            if (url!=null && planRaw!=null)
                throw new IllegalArgumentException("Cannot supply both plan and url");
            if (url==null && planRaw==null)
                throw new IllegalArgumentException("Must supply plan or url");

            Map<String, Object> config = asMap(parameters, BLUEPRINT_CONFIG);
            if (planRaw==null) {
                planRaw = Jsonya.at("services").list().put("serviceType", url).put(config).getRootMap();
            } else {
                if (config!=null)
                    throw new IllegalArgumentException("Cannot supply plan with config");
            }

            // planRaw might be a yaml string, or a map; if a map, convert to string
            if (planRaw instanceof Map)
                planRaw = Jsonya.of((Map)planRaw).toString();
            if (!(planRaw instanceof String))
                throw new IllegalArgumentException("Invalid "+JavaClassNames.simpleClassName(planRaw)+" value for CAMP plan: "+planRaw);

            // now *all* the data is in planRaw; that is what will be submitted
            return (String)planRaw;
        }

        protected String submitPlan(String plan) {
            URI baseUri = Preconditions.checkNotNull(entity().getAttribute(WEB_CONSOLE_URI), "Cannot be invoked until the web console URL is available");
            HttpClientBuilder builder = HttpTool.httpClientBuilder()
                .trustAll()
                .laxRedirect(true)
                .uri(baseUri);
            if (entity().getConfig(MANAGEMENT_USER)!=null)
                builder.credentials(new UsernamePasswordCredentials(entity().getConfig(MANAGEMENT_USER), entity().getConfig(MANAGEMENT_PASSWORD)));
            HttpClient client = builder.build();

            return submitPlan(client, baseUri, plan);
        }

        @VisibleForTesting
        // Integration test for this in BrooklynNodeIntegrationTest in this project doesn't use this method,
        // but a Unit test for this does, in DeployBlueprintTest -- but in the REST server project (since it runs against local)
        public static String submitPlan(HttpClient client, URI baseUri, String plan) {
            URI uri = URI.create(Urls.mergePaths(baseUri.toString(), "/v1/applications"));

            HttpToolResponse result = null;
            byte[] content;
            try {
                result = HttpTool.httpPost(client, uri, MutableMap.of(com.google.common.net.HttpHeaders.CONTENT_TYPE, "application/yaml"), plan.getBytes());
                content = result.getContent();
            } catch (Exception e) {
                Exceptions.propagateIfFatal(e);
                throw new IllegalStateException("Invalid response invoking "+uri+": "+e, e);
            }
            Tasks.addTagDynamically(BrooklynTaskTags.tagForStream("http_response", Streams.byteArray(content)));
            if (!HttpTool.isStatusCodeHealthy(result.getResponseCode())) {
                log.warn("Invalid response invoking "+uri+": response code "+result.getResponseCode()+"\n"+result+": "+new String(content));
                throw new IllegalStateException("Invalid response invoking "+uri+": response code "+result.getResponseCode());
            }
            return (String)new Gson().fromJson(new String(content), Map.class).get("entityId");
        }
    }

    public List<String> getClasspath() {
        List<String> classpath = getConfig(CLASSPATH);
        if (classpath == null || classpath.isEmpty()) {
            classpath = getManagementContext().getConfig().getConfig(CLASSPATH);
        }
        return classpath;
    }

    protected List<String> getEnabledHttpProtocols() {
        return getAttribute(ENABLED_HTTP_PROTOCOLS);
    }

    protected boolean isHttpProtocolEnabled(String protocol) {
        List<String> protocols = getAttribute(ENABLED_HTTP_PROTOCOLS);
        for (String contender : protocols) {
            if (protocol.equalsIgnoreCase(contender)) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void connectSensors() {
        super.connectSensors();

        // TODO what sensors should we poll?
        ConfigToAttributes.apply(this);

        String host = getAttribute(WEB_CONSOLE_BIND_ADDRESS);
        if (Strings.isEmpty(host)) {
            if (getAttribute(NO_WEB_CONSOLE_AUTHENTICATION)) {
                host = "localhost"; // Because of --noConsoleSecurity option
            } else {
                host = getAttribute(HOSTNAME);
            }
        }

        URI webConsoleUri;
        if (isHttpProtocolEnabled("http")) {
            int port = getConfig(PORT_MAPPER).apply(getAttribute(HTTP_PORT));
            webConsoleUri = URI.create(String.format("http://%s:%s", host, port));
            setAttribute(WEB_CONSOLE_URI, webConsoleUri);
        } else if (isHttpProtocolEnabled("https")) {
            int port = getConfig(PORT_MAPPER).apply(getAttribute(HTTPS_PORT));
            webConsoleUri = URI.create(String.format("https://%s:%s", host, port));
            setAttribute(WEB_CONSOLE_URI, webConsoleUri);
        } else {
            // web-console is not enabled
            setAttribute(WEB_CONSOLE_URI, null);
            webConsoleUri = null;
        }

        if (webConsoleUri != null) {
            httpFeed = HttpFeed.builder()
                    .entity(this)
                    .period(200)
                    .baseUri(webConsoleUri)
                    .credentialsIfNotNull(getConfig(MANAGEMENT_USER), getConfig(MANAGEMENT_PASSWORD))
                    .poll(new HttpPollConfig<Boolean>(SERVICE_UP)
                            .onSuccess(HttpValueFunctions.responseCodeEquals(200))
                            .setOnFailureOrException(false))
                    .build();

        } else {
            setAttribute(SERVICE_UP, true);
        }
    }

    @Override
    protected void disconnectSensors() {
        super.disconnectSensors();

        if (httpFeed != null) httpFeed.stop();
    }
}


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.dawidperdek.zad4prepare.Fragment1">

    <!-- TODO: Update blank fragment layout -->

    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center_horizontal|top"
        android:id="@+id/radioGroupOpcje">

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Opcja 1"
            android:id="@+id/radioButtonFragment1"
            android:layout_gravity="center_horizontal" />

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Opcja 2"
            android:id="@+id/radioButtonFragment2"
            android:layout_gravity="center_horizontal" />

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Opcja 3"
            android:id="@+id/radioButtonFragment3"
            android:layout_gravity="center_horizontal" />

    </RadioGroup>
</FrameLayout>


text:
var loopRate = 100.0; //100 ms

exports.Game = function(clients, io){
    //clients is an array of client sockets
    this.io = io;
    this.ships = []; //handles the controllable ships
    this.shipIDs = [];
    this.size = {width:1000,height:1000};
    var clientCount = clients.length;
    this.clients = clients;
    for(x = 0; x < this.clients.length; x++){
        this.clients[x].on('inputReceived', inputReceivedFunction().bind(this));
        this.ships[x] = new Ship(this.clients[x].id);
        console.log("client id: "+this.clients[x].id);
        //this.ships[x].position.x = x*(this.size.width/clientCount);
        //this.ships[x].position.y = (this.size.height/2.0);
        this.ships[x].position.x = 100+(x+1)*100; //random positions to just move them more toward the center of the screen
        this.ships[x].position.y = 150;
        this.shipIDs[this.clients[x].id] = x;
    }
    this.lastFrame = 0;
};

exports.Game.prototype.startGame = function(){
    console.log("start game");
    this.startGameLoop();
};

exports.Game.prototype.startGameLoop = function(){
    setInterval(this.update.bind(this), loopRate);
};

exports.Game.prototype.update = function(){
    var t = 0.1;
    for(var x = 0; x < this.ships.length; x++){
        if(this.ships[x].moving){
            var ship = this.ships[x];
            var dx = ship.target.x-ship.position.x;
            var dy = ship.target.y-ship.position.y;
            var dist = Math.sqrt(dx*dx+dy*dy);
            if(dist <= ship.moveSpeed*t){
                ship.position.x = ship.target.x;
                ship.position.y = ship.target.y;
                ship.moving = false;
            }
            else{
                //calculate the change in position
                var deltaX = (dx/dist)*ship.moveSpeed*t;
                var deltaY = (dy/dist)*ship.moveSpeed*t;
                this.ships[x].position.x += deltaX;
                this.ships[x].position.y += deltaY;
            }
        }
    }
    this.io.sockets.emit('update', this.ships);
};

function Ship(clientID){
    this.size = {width:50,height:50};
    this.target = {x:0,y:0};
    this.moving = false;
    this.nextMoveSpace = {x:0,y:0};
    this.position = {x:0,y:0};
    this.id = clientID;
    this.moveSpeed = 150;
}

function inputReceivedFunction(){
    return function(data){
        console.log("input recieved+"+data.id);
        var ship = this.ships[this.shipIDs[data.id]];
        if(data.mouse){
            ship.target.x = data.mouseX;
            ship.target.y = data.mouseY;
            ship.moving = true;
        }
        if(data.stop)
            ship.moving = false;
    };
}


text:
from lxml import etree
from route53 import xml_parsers, xml_generators
from route53.exceptions import Route53Error
from route53.transport import RequestsTransport
from route53.xml_parsers.common_change_info import parse_change_info

class Route53Connection(object):
    """
    Instances of this class are instantiated by the top-level
    :py:func:`route53.connect` function, and serve as a high level gateway
    to the Route 53 API. The majority of your interaction with these
    instances will probably be creating, deleting, and retrieving
    :py:class:`HostedZone <route53.hosted_zone.HostedZone>` instances.

    .. warning:: Do not instantiate instances of this class yourself.
    """

    endpoint_version = '2012-02-29'
    """The date-based API version. Mostly visible for your reference."""

    def __init__(self, aws_access_key_id, aws_secret_access_key, endpoint_version = '2012-02-29', **kwargs):
        """
        :param str aws_access_key_id: An account's access key ID.
        :param str aws_secret_access_key: An account's secret access key.
        """

        self.endpoint_version = endpoint_version
        self._endpoint = 'https://route53.amazonaws.com/%s/' % self.endpoint_version
        self._xml_namespace = 'https://route53.amazonaws.com/doc/%s/' % self.endpoint_version
        self._aws_access_key_id = aws_access_key_id
        self._aws_secret_access_key = aws_secret_access_key
        if 'transport_class' not in kwargs or kwargs['transport_class'] is None:
            self._transport = RequestsTransport(self)
        else:
            self._transport = kwargs['transport_class'](self)

    def _send_request(self, path, data, method):
        """
        Uses the HTTP transport to query the Route53 API. Runs the response
        through lxml's parser, before we hand it off for further picking
        apart by our call-specific parsers.

        :param str path: The RESTful path to tack on to the :py:attr:`endpoint`.
        :param data: The params to send along with the request.
        :type data: Either a dict or bytes, depending on the request type.
        :param str method: One of 'GET', 'POST', or 'DELETE'.
        :rtype: lxml.etree._Element
        :returns: An lxml Element root.
        """

        response_body = self._transport.send_request(path, data, method)
        root = etree.fromstring(response_body)
        return root

    def _do_autopaginating_api_call(self, path, params, method, parser_func,
        next_marker_xpath, next_marker_param_name,
        next_type_xpath=None, parser_kwargs=None):
        """
        Given an API method, the arguments passed to it, and a function to
        hand parsing off to, loop through the record sets in the API call
        until all records have been yielded.

        :param str method: The API method on the endpoint.
        :param dict params: The kwargs from the top-level API method.
        :param callable parser_func: A callable that is used for parsing the
            output from the API call.
        :param str next_marker_param_name: The XPath to the marker tag that
            will determine whether we continue paginating.
        :param str next_marker_param_name: The parameter name to manipulate
            in the request data to bring up the next page on the next
            request loop.
        :keyword str next_type_xpath: For the
            py:meth:`list_resource_record_sets_by_zone_id` method, there's
            an additional paginator token. Specifying this XPath looks for it.
        :keyword dict parser_kwargs: Optional dict of additional kwargs to pass
            on to the parser function.
        :rtype: generator
        :returns: Returns a generator that may be returned by the top-level
            API method.
        """

        if not parser_kwargs:
            parser_kwargs = {}

        # We loop indefinitely since we have no idea how many "pages" of
        # results we're going to have to go through.
        while True:
            # An lxml Element node.
            root = self._send_request(path, params, method)

            # Individually yield HostedZone instances after parsing/instantiating.
            for record in parser_func(root, connection=self, **parser_kwargs):
                yield record

            # This will determine at what offset we start the next query.
            next_marker = root.find(next_marker_xpath)
            if next_marker is None:
                # If the NextMarker tag is absent, we know we've hit the
                # last page.
                break

            # if NextMarker is present, we'll adjust our API request params
            # and query again for the next page.
            params[next_marker_param_name] = next_marker.text

            if next_type_xpath:
                # This is a _list_resource_record_sets_by_zone_id call. Look
                # for the given tag via XPath and adjust our type arg for
                # the next request. Without specifying this, we loop
                # infinitely.
                next_type = root.find(next_type_xpath)
                params['type'] = next_type.text

    def list_hosted_zones(self, page_chunks=100):
        """
        List all hosted zones associated with this connection's account. Since
        this method returns a generator, you can pull as many or as few
        entries as you'd like, without having to query and receive every
        hosted zone you may have.

        :keyword int page_chunks: This API call is "paginated" behind-the-scenes
            in order to break up large result sets. This number determines
            the maximum number of
            :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
            instances to retrieve per request. The default is fine for almost
            everyone.

        :rtype: generator
        :returns: A generator of :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
            instances.
        """

        return  self._do_autopaginating_api_call(
            path='hostedzone',
            params={'maxitems': page_chunks},
            method='GET',
            parser_func=xml_parsers.list_hosted_zones_parser,
            next_marker_xpath="./{*}NextMarker",
            next_marker_param_name="marker",
        )

    def create_hosted_zone(self, name, caller_reference=None, comment=None):
        """
        Creates and returns a new hosted zone. Once a hosted zone is created,
        its details can't be changed.

        :param str name: The name of the hosted zone to create.
        :keyword str caller_reference: A unique string that identifies the
            request and that allows failed create_hosted_zone requests to be
            retried without the risk of executing the operation twice. If no
            value is given, we'll generate a Type 4 UUID for you.
        :keyword str comment: An optional comment to attach to the zone.
        :rtype: tuple
        :returns: A tuple in the form of ``(hosted_zone, change_info)``.
            The ``hosted_zone`` variable contains a
            :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
            instance matching the newly created zone, and ``change_info``
            is a dict with some details about the API request.
        """

        body = xml_generators.create_hosted_zone_writer(
            connection=self,
            name=name,
            caller_reference=caller_reference,
            comment=comment
        )

        root = self._send_request(
            path='hostedzone',
            data=body,
            method='POST',
        )

        return xml_parsers.created_hosted_zone_parser(
            root=root,
            connection=self
        )

    def get_hosted_zone_by_id(self, id):
        """
        Retrieves a hosted zone, by hosted zone ID (not name).

        :param str id: The hosted zone's ID (a short hash string).
        :rtype: :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
        :returns: An :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
            instance representing the requested hosted zone.
        """

        root = self._send_request(
            path='hostedzone/%s' % id,
            data={},
            method='GET',
        )

        return xml_parsers.get_hosted_zone_by_id_parser(
            root=root,
            connection=self,
        )

    def delete_hosted_zone_by_id(self, id):
        """
        Deletes a hosted zone, by hosted zone ID (not name).

        .. tip:: For most cases, we recommend deleting hosted zones via a
            :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
            instance's
            :py:meth:`HostedZone.delete <route53.hosted_zone.HostedZone.delete>`
            method, but this saves an HTTP request if you already know the zone's ID.

        .. note:: Unlike
            :py:meth:`HostedZone.delete <route53.hosted_zone.HostedZone.delete>`,
            this method has no optional ``force`` kwarg.

        :param str id: The hosted zone's ID (a short hash string).
        :rtype: dict
        :returns: A dict of change info, which contains some details about
            the request.
        """

        root = self._send_request(
            path='hostedzone/%s' % id,
            data={},
            method='DELETE',
        )

        return xml_parsers.delete_hosted_zone_by_id_parser(
            root=root,
            connection=self,
        )

    def _list_resource_record_sets_by_zone_id(self, id, rrset_type=None,
                                             identifier=None, name=None,
                                             page_chunks=100):
        """
        Lists a hosted zone's resource record sets by Zone ID, if you
        already know it.

        .. tip:: For most cases, we recommend going through a
            :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
            instance's
            :py:meth:`HostedZone.record_sets <route53.hosted_zone.HostedZone.record_sets>`
            property, but this saves an HTTP request if you already know the
            zone's ID.

        :param str id: The ID of the zone whose record sets we're listing.
        :keyword str rrset_type: The type of resource record set to begin the
            record listing from.
        :keyword str identifier: Weighted and latency resource record sets
            only: If results were truncated for a given DNS name and type,
            the value of SetIdentifier for the next resource record set
            that has the current DNS name and type.
        :keyword str name: Not really sure what this does.
        :keyword int page_chunks: This API call is paginated behind-the-scenes
            by this many ResourceRecordSet instances. The default should be
            fine for just about everybody, aside from those with tons of RRS.

        :rtype: generator
        :returns: A generator of ResourceRecordSet instances.
        """

        params = {
            'name': name,
            'type': rrset_type,
            'identifier': identifier,
            'maxitems': page_chunks,
        }

        return  self._do_autopaginating_api_call(
            path='hostedzone/%s/rrset' % id,
            params=params,
            method='GET',
            parser_func=xml_parsers.list_resource_record_sets_by_zone_id_parser,
            parser_kwargs={'zone_id': id},
            next_marker_xpath="./{*}NextRecordName",
            next_marker_param_name="name",
            next_type_xpath="./{*}NextRecordType"
        )

    def _change_resource_record_sets(self, change_set, comment=None):
        """
        Given a ChangeSet, POST it to the Route53 API.

        .. note:: You probably shouldn't be using this method directly,
            as there are convenience methods on the ResourceRecordSet
            sub-classes.

        :param change_set.ChangeSet change_set: The ChangeSet object to create
            the XML doc from.
        :keyword str comment: An optional comment to go along with the request.
        :rtype: dict
        :returns: A dict of change info, which contains some details about
            the request.
        """

        body = xml_generators.change_resource_record_set_writer(
            connection=self,
            change_set=change_set,
            comment=comment
        )

        root = self._send_request(
            path='hostedzone/%s/rrset' % change_set.hosted_zone_id,
            data=body,
            method='POST',
        )

        e_change_info = root.find('./{*}ChangeInfo')
        if e_change_info is None:
            error = root.find('./{*}Error').find('./{*}Message').text
            raise Route53Error(error)
        return parse_change_info(e_change_info)

    def list_health_checks(self, page_chunks=100):
        """
        List all health checks associated with this connection's account. Since
        this method returns a generator, you can pull as many or as few
        entries as you'd like, without having to query and receive every
        hosted zone you may have.

        :keyword int page_chunks: This API call is "paginated" behind-the-scenes
            in order to break up large result sets. This number determines
            the maximum number of
            :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
            instances to retrieve per request. The default is fine for almost
            everyone.

        :rtype: generator
        :returns: A generator of :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
            instances.
        """

        return  self._do_autopaginating_api_call(
            path='healthcheck',
            params={'maxitems': page_chunks},
            method='GET',
            parser_func=xml_parsers.list_health_checks_parser,
            next_marker_xpath="./{*}NextMarker",
            next_marker_param_name="marker",
        )

    def create_health_check(self, ipaddress, port, type, resource_path, fqdn, search_string, caller_reference=None):
        """
        Creates and returns a new hosted zone. Once a hosted zone is created,
        its details can't be changed.

        :param str name: The name of the hosted zone to create.
        :keyword str caller_reference: A unique string that identifies the
            request and that allows failed create_health_check requests to be
            retried without the risk of executing the operation twice. If no
            value is given, we'll generate a Type 4 UUID for you.
        :keyword str comment: An optional comment to attach to the zone.
        :rtype: tuple
        :returns: A tuple in the form of ``(hosted_zone, change_info)``.
            The ``hosted_zone`` variable contains a
            :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
            instance matching the newly created zone, and ``change_info``
            is a dict with some details about the API request.
        """

        body = xml_generators.create_health_check_writer(
            connection=self,
            caller_reference=caller_reference,
            ipaddress=ipaddress,
            port=port,
            type=type,
            resource_path=resource_path,
            fqdn=fqdn,
            search_string=search_string
        )

        root = self._send_request(
            path='healthcheck',
            data=body,
            method='POST',
        )

        return xml_parsers.created_health_check_parser(
            root=root,
            connection=self
        )

    def get_health_check_by_id(self, id):
        """
        Retrieves a hosted zone, by hosted zone ID (not name).

        :param str id: The hosted zone's ID (a short hash string).
        :rtype: :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
        :returns: An :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
            instance representing the requested hosted zone.
        """

        root = self._send_request(
            path='healthcheck/%s' % id,
            data={},
            method='GET',
        )

        return xml_parsers.get_health_check_by_id_parser(
            root=root,
            connection=self,
        )

    def delete_health_check_by_id(self, id):
        """
        Deletes a hosted zone, by hosted zone ID (not name).

        .. tip:: For most cases, we recommend deleting hosted zones via a
            :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
            instance's
            :py:meth:`HostedZone.delete <route53.hosted_zone.HostedZone.delete>`
            method, but this saves an HTTP request if you already know the zone's ID.

        .. note:: Unlike
            :py:meth:`HostedZone.delete <route53.hosted_zone.HostedZone.delete>`,
            this method has no optional ``force`` kwarg.

        :param str id: The hosted zone's ID (a short hash string).
        :rtype: dict
        :returns: A dict of change info, which contains some details about
            the request.
        """

        root = self._send_request(
            path='healthcheck/%s' % id,
            data={},
            method='DELETE',
        )

        return xml_parsers.delete_health_check_by_id_parser(
            root=root,
            connection=self,
        )


text:
package org.sejda.sambox.pdmodel.interactive.form;

import org.sejda.sambox.cos.COSArray;
import org.sejda.sambox.cos.COSArrayList;
import org.sejda.sambox.cos.COSBase;
import org.sejda.sambox.cos.COSDictionary;
import org.sejda.sambox.cos.COSName;
import org.sejda.sambox.cos.COSString;
import org.sejda.sambox.pdmodel.interactive.annotation.PDAnnotationWidget;
import org.sejda.sambox.pdmodel.interactive.annotation.PDAppearanceDictionary;
import org.sejda.sambox.pdmodel.interactive.annotation.PDAppearanceEntry;
import org.sejda.sambox.pdmodel.interactive.annotation.PDAppearanceStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * A button field represents an interactive control on the screen that the user can manipulate with
 * the mouse.
 *
 * @author sug
 */
public abstract class PDButton extends PDTerminalField
{

    private static final Logger LOG = LoggerFactory.getLogger(PDButton.class);

    /**
     * A Ff flag. If set, the field is a set of radio buttons
     */
    static final int FLAG_RADIO = 1 << 15;

    /**
     * A Ff flag. If set, the field is a pushbutton.
     */
    static final int FLAG_PUSHBUTTON = 1 << 16;

    /**
     * A Ff flag. If set, radio buttons individual fields, using the same value for the on state
     * will turn on and off in unison.
     */
    static final int FLAG_RADIOS_IN_UNISON = 1 << 25;

    // SAMBOX SPECIFIC
    // PDFBox accepts field.setValue("Export option 1") and does some mapping between option/value
    // this mapping makes a lot of assumptions and breaks in several cases:
    // 1) when widgets.size != exportOptions.size
    // 2) when options are numeric and match the appearance states, eg: export options /Opt = ["0", "1"]

    // We add an option to perform setValue()/getValue() by always passing the final dict /V value,
    // (the appearance state value), and ignoring any /Opt mapping
    private boolean ignoreExportOptions = false;

    /**
     * @param acroForm The acroform.
     * @see PDField#PDField(PDAcroForm)
     */
    public PDButton(PDAcroForm acroForm)
    {
        super(acroForm);
        getCOSObject().setItem(COSName.FT, COSName.BTN);
    }

    /**
     * Constructor.
     *
     * @param acroForm The form that this field is part of.
     * @param field the PDF object to represent as a field.
     * @param parent the parent node of the node
     */
    PDButton(PDAcroForm acroForm, COSDictionary field, PDNonTerminalField parent)
    {
        super(acroForm, field, parent);
    }

    /**
     * Determines if push button bit is set.
     *
     * @return true if type of button field is a push button.
     */
    public boolean isPushButton()
    {
        return getCOSObject().getFlag(COSName.FF, FLAG_PUSHBUTTON);
    }

    /**
     * Set the push button bit.
     *
     * @deprecated use {@link org.sejda.sambox.pdmodel.interactive.form.PDPushButton} instead
     * @param pushbutton if true the button field is treated as a push button field.
     */
    @Deprecated
    public void setPushButton(boolean pushbutton)
    {
        getCOSObject().setFlag(COSName.FF, FLAG_PUSHBUTTON, pushbutton);
        if (pushbutton)
        {
            setRadioButton(false);
        }
    }

    /**
     * Determines if radio button bit is set.
     *
     * @return true if type of button field is a radio button.
     */
    public boolean isRadioButton()
    {
        return getCOSObject().getFlag(COSName.FF, FLAG_RADIO);
    }

    /**
     * Set the radio button bit.
     *
     * @deprecated use {@link org.sejda.sambox.pdmodel.interactive.form.PDRadioButton} instead
     * @param radiobutton if true the button field is treated as a radio button field.
     */
    @Deprecated
    public void setRadioButton(boolean radiobutton)
    {
        getCOSObject().setFlag(COSName.FF, FLAG_RADIO, radiobutton);
        if (radiobutton)
        {
            setPushButton(false);
        }
    }

    /**
     * Returns the selected value.
     *
     *
Off is the default value which will also be returned if the
     * value hasn't been set at all.
     *
     * @return A non-null string.
     */
    public String getValue()
    {
        COSBase value = getInheritableAttribute(COSName.V);
        if (value instanceof COSName)
        {
            String stringValue = ((COSName)value).getName();

            if(ignoreExportOptions)
            {
                return stringValue;
            }

            List<String> exportValues = getExportValues();
            if (!exportValues.isEmpty())
            {
                try
                {
                    int idx = Integer.parseInt(stringValue, 10);
                    if (idx >= 0 && idx < exportValues.size())
                    {
                        return exportValues.get(idx);
                    }
                }
                catch (NumberFormatException nfe)
                {
                    return stringValue;
                }
            }
            return stringValue;
        }

        // Off is the default value if there is nothing else set.
        // See PDF Spec.
        return "Off";
    }

    /**
     * Sets the selected option given its name. It also tries to update the visual appearance,
     * unless {@link PDAcroForm#isNeedAppearances()} is true.
     *
     * @param value Name of option to select
     * @throws IOException if the value could not be set
     * @throws IllegalArgumentException if the value is not a valid option.
     */
    @Override
    public void setValue(String value) throws IOException
    {
        checkValue(value);

        // if there are export values/an Opt entry there is a different
        // approach to setting the value
        boolean hasExportValues = getExportValues().size() > 0;

        if (hasExportValues && !ignoreExportOptions) {
            updateByOption(value);
        }
        else
        {
            updateByValue(value);
        }

        applyChange();
    }

    /**
     * Set the selected option given its index, and try to update the visual appearance.
     *

     * NOTE: this method is only usable if there are export values and used for radio buttons with
     * FLAG_RADIOS_IN_UNISON not set.
     *
     * @param index index of option to be selected
     * @throws IOException if the value could not be set
     * @throws IllegalArgumentException if the index provided is not a valid index.
     */
    public void setValue(int index) throws IOException
    {
        if (getExportValues().isEmpty() || index < 0 || index >= getExportValues().size())
        {
            throw new IllegalArgumentException(
                    "index '" + index + "' is not a valid index for the field "
                            + getFullyQualifiedName() + ", valid indices are from 0 to " + (
                            getExportValues().size() - 1));
        }

        updateByValue(String.valueOf(index));

        applyChange();
    }

    /**
     * Returns the default value, if any.
     *
     * @return A non-null string.
     */
    public String getDefaultValue()
    {
        COSBase value = getInheritableAttribute(COSName.DV);
        if (value instanceof COSName)
        {
            return ((COSName)value).getName();
        }
            return "";
    }

    /**
     * Sets the default value.
     *
     * @param value Name of option to select
     * @throws IllegalArgumentException if the value is not a valid option.
     */
    public void setDefaultValue(String value)
    {
        checkValue(value);
        getCOSObject().setName(COSName.DV, value);
    }

    @Override
    public String getValueAsString()
    {
        return getValue();
    }

    /**
     * This will get the export values.
     *
     *

     * The export values are defined in the field dictionaries /Opt key.
     *

     *
     *

     * The option values are used to define the export values for the field to
     *

     *
hold values in non-Latin writing systems as name objects, which represent the field value, are limited to
     * PDFDocEncoding

     *
allow radio buttons having the same export value to be handled independently

     *

     *

     *
     * @return List containing all possible export values. If there is no Opt entry an empty list
     * will be returned.
     */
    public List<String> getExportValues()
    {
        COSBase value = getInheritableAttribute(COSName.OPT);

        if (value instanceof COSString)
        {
            List<String> array = new ArrayList<>();
            array.add(((COSString) value).getString());
            return array;
        }
        if (value instanceof COSArray)
        {
            return COSArrayList.convertCOSStringCOSArrayToList((COSArray) value);
        }
        return Collections.emptyList();
    }

    /**
     * This will set the export values.
     *
     * @param values List containing all possible export values. Supplying null or an empty list
     *               will remove the Opt entry.
     * @see #getExportValues()
     */
    public void setExportValues(List<String> values)
    {
        COSArray cosValues;
        if (values != null && !values.isEmpty())
        {
            cosValues = COSArrayList.convertStringListToCOSStringCOSArray(values);
            getCOSObject().setItem(COSName.OPT, cosValues);
        }
        else
        {
            getCOSObject().removeItem(COSName.OPT);
        }
    }

    @Override
    void constructAppearances() throws IOException
    {
        List<String> exportValues = getExportValues();
        if (exportValues.size() > 0 && !ignoreExportOptions)
        {
            // the value is the index value of the option. So we need to get that
            // and use it to set the value
            try
            {
                int optionsIndex = Integer.parseInt(getValue());
                if (optionsIndex < exportValues.size())
                {
                    updateByOption(exportValues.get(optionsIndex));
                }
            } catch (NumberFormatException e)
            {
                // silently ignore that
                // and don't update the appearance
            }
        }
        else
        {
            updateByValue(getValue());
        }
    }

    /**
     * Get the values to set individual buttons within a group to the on state.
     *
     *

     * The On value could be an arbitrary string as long as it is within the limitations of a PDF
     * name object. The Off value shall always be 'Off'. If not set or not part of the normal
     * appearance keys 'Off' is the default
     *

     *
     * @return the potential values setting the check box to the On state. If an empty Set is
     * returned there is no appearance definition.
     */
    public Set<String> getOnValues()
    {
        Set<String> onValues = new HashSet<>();
        if(!ignoreExportOptions)
        {
            onValues.addAll(getExportValues());
        }
        onValues.addAll(getNormalAppearanceValues());
        return onValues;
    }

    public List<String> getNormalAppearanceValues()
    {
        List<String> values = new ArrayList<>();
        List<PDAnnotationWidget> widgets = this.getWidgets();
        for (PDAnnotationWidget widget : widgets)
        {
            String value = getOnValueForWidget(widget);
            if (value != null)
            {
                values.add(value);
            }
        }
        return values;
    }

    /*
     * Get the on value for an individual widget by it's index.
     */
    private String getOnValue(int index)
    {
        List<PDAnnotationWidget> widgets = this.getWidgets();
        if (index < widgets.size())
        {
            return getOnValueForWidget(widgets.get(index));
        }
        // PDFBox returns an empty string here.
        // Chose to return null so it's clear it's an undefined value
        // Caller should choose to not act on these values
        return null;
    }

    /*
     * Get the on value for an individual widget.
     */
    public String getOnValueForWidget(PDAnnotationWidget widget)
    {
        PDAppearanceDictionary apDictionary = widget.getAppearance();
        if (apDictionary != null)
        {
            PDAppearanceEntry normalAppearance = apDictionary.getNormalAppearance();
            if (normalAppearance != null && normalAppearance.isSubDictionary())
            {
                // SAMBOX specific: there can be more than one entry, besides "Off"
                // pick the first one alphabetically, so it's consistently returning the same value each time
                Map<COSName, PDAppearanceStream> subDictionary = normalAppearance.getSubDictionary();
                SortedSet<COSName> entries = new TreeSet<>(subDictionary.keySet());
                for (COSName entry : entries)
                {
                    if (COSName.Off.compareTo(entry) != 0)
                    {
                        return entry.getName();
                    }
                }
            }
        }

        // PDFBox returns an empty string here.
        // Chose to return null so it's clear it's an undefined value
        // Caller should choose to not act on these values
        return null;
    }

    /**
     * Checks value.
     *
     * @param value Name of radio button to select
     * @throws IllegalArgumentException if the value is not a valid option.
     */
    void checkValue(String value)
    {
        Set<String> onValues = getOnValues();

        if (onValues.isEmpty())
        {
            return;
        }

        if (COSName.Off.getName().compareTo(value) != 0 && !onValues.contains(value))
        {
            throw new IllegalArgumentException(
                    "value '" + value + "' is not a valid option for the field "
                            + getFullyQualifiedName() + ", valid values are: " + onValues + " and "
                            + COSName.Off.getName());
        }
    }

    private void updateByValue(String value)
    {
        getCOSObject().setName(COSName.V, value);
        // update the appearance state (AS)
        for (PDAnnotationWidget widget : getWidgets())
        {
            PDAppearanceDictionary appearance = widget.getAppearance();
            PDAppearanceEntry normalAppearance = null;
            Set<String> entries = new HashSet<>();
            if (appearance != null)
            {
                normalAppearance = widget.getAppearance().getNormalAppearance();

                if (normalAppearance != null && normalAppearance.isSubDictionary())
                {
                    entries = normalAppearance.getSubDictionary().keySet().stream()
                            .map(COSName::getName).collect(Collectors.toSet());

                    if (entries.contains(value))
                    {
                        widget.setAppearanceState(value);
                    }
                    else
                    {
                        widget.setAppearanceState(COSName.Off.getName());
                    }
                }
            }

            // FIX scenario: checkboxes with a malformed normal appearance (eg: stream instead of sub-dictionary with entries)
            // see forms-malformed-checkbox-normal-appearances.pdf
            // otherwise these checkboxes are not rendered at all in Adobe Reader
            // FIX scenario: checkbox that only has an "Off" entry in normal appearances
            if (entries.isEmpty() || (entries.size() == 1 && entries.contains("Off")))
            {
                if(this instanceof PDCheckBox checkBox)
                {
                    if (checkBox.getOnValue().equals(value)) {
                        // checkbox is being checked
                        widget.setAppearanceState(value);
                    } else {
                        // checkbox being unchecked
                        widget.setAppearanceState(COSName.Off.getName());
                    }
                }

                if(normalAppearance != null && !normalAppearance.isSubDictionary())
                {
                    if(this instanceof PDRadioButton || this instanceof PDCheckBox)
                    {
                        // checkbox/radio has a single stream normal appearance
                        // this can cause problems, because the checkbox looks the same no matter if checked or not
                        throw new RuntimeException(
                                "Check/radio has a single normal appearance, might look the same when checked or not");
                    }
                }
            }
        }
    }

    private void updateByOption(String value) throws IOException
    {
        List<PDAnnotationWidget> widgets = getWidgets();
        List<String> options = getExportValues();

        if (widgets.size() != options.size())
        {
            throw new IllegalArgumentException("The number of options doesn't match the number of widgets");
        }

        if (value.equals(COSName.Off.getName()))
        {
            updateByValue(value);
        }
        else
        {
            // the value is the index of the matching option
            int optionsIndex = options.indexOf(value);

            // get the values the options are pointing to as
            // this might not be numerical
            // see PDFBOX-3682
            if (optionsIndex != -1)
            {
                updateByValue(getOnValue(optionsIndex));
            }
        }
    }

    public boolean isIgnoreExportOptions() {
        return ignoreExportOptions;
    }

    public void setIgnoreExportOptions(boolean ignoreExportOptions) {
        this.ignoreExportOptions = ignoreExportOptions;
    }
}


text:
package com.tankformers.model;

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

public class Ground {
  public List<Tank> tanks = new ArrayList<Tank>();
  public List<Wall> walls = new ArrayList<Wall>();
  public List<Bullet> bullets = new ArrayList<Bullet>();
}