text:
(function (request, util, assert, Joi, Promise, create, EventEmitter) {
    var methods = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'];

    var statusCodes = [100, 101, 102, 200, 201, 202, 203, 204, 205, 206, 207, 300,
        301, 302, 303, 304, 305, 307, 308, 400, 401, 402, 403, 404, 405, 406, 407,
        408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 422, 423, 424, 425,
        426, 428, 429, 431, 500, 501, 502, 503, 504, 505, 506, 507, 509, 510, 511];

    var regexValueSchema = Joi.object().keys({
        expression: Joi.string().required(),
        flags: Joi.object().keys({
            ignoreCase: Joi.boolean().optional(),
            global: Joi.boolean().optional(),
            multiline: Joi.boolean().optional()
        }).unknown().optional()
    }).unknown().required();
    var testValueSchema = Joi.alternatives().try(Joi.string().required(), regexValueSchema);

    var testSchema = Joi.array().items(Joi.object().keys({
        title: Joi.string().optional(),
        target: Joi.object().keys({
            url: Joi.string().uri({
                scheme: ['http', 'https']
            }).required(),
            method: Joi.string().valid(methods).required(),
            headers: Joi.object().pattern(/.+/, Joi.string().required()).optional(),
            body: Joi.alternatives().when('method', {is: ['POST', 'PUT', 'PATCH'], then: Joi.alternatives().try(Joi.string().optional(), Joi.object().optional()), otherwise: Joi.forbidden()})
        }).unknown().required(),
        expect: Joi.object().keys({
            statusCode: Joi.alternatives().try(Joi.number().valid(statusCodes), regexValueSchema).optional(),
            headers: Joi.object().pattern(/.+/, testValueSchema.required()).optional(),
            body: Joi.alternatives().try(testValueSchema.optional(), Joi.object().optional(), Joi.func().optional())
        }).unknown()
    }).unknown().required()).single(true);

    var suitesSchema = Joi.object().keys({
        options: Joi.object().keys({
            followRedirects: Joi.boolean().default(false).optional(),
            persistCookies: Joi.boolean().default(false).optional(),
            runInParallel: Joi.boolean().default(false).optional()
        }).unknown().optional(),
        suite: Joi.object().keys({
            title: Joi.string().optional(),
            before: testSchema.optional(),
            beforeEach: testSchema.optional(),
            after: testSchema.optional(),
            afterEach: testSchema.optional(),
            tests: testSchema.required()
        }).unknown().required()
    }).unknown().required();

    function SuiteRunner() {
    }

    SuiteRunner.prototype = create(EventEmitter.prototype, {
        constructor: SuiteRunner
    });

    SuiteRunner.prototype.run = function runSuites(suites) {
        if (!suites) {
            return Promise.reject(new Error('Suites must either be an Array of suites or a single suite'));
        }

        if (!Array.isArray(suites)) {
            suites = [suites];
        }

        var self = this;
        self.emit('start', suites);
        return Promise.each(suites, function (suite) {
            return new Promise(function (resolve, reject) {
                var result = Joi.validate(suite, suitesSchema, {stripUnknown: true});

                if (result.error) {
                    return reject(result.error);
                }

                var validatedSuite = result.value.suite;
                self.suiteOptions = result.value.options || {};

                // For now, don't want to add the ability to nest suites, as I feel that would encourage test suites to be larger than I prefer. I think they should be small and simple, but it would allow for over-nesting and large test suites instead of focusing on small bits of functionality.
                return resolve(self.executeSuite(validatedSuite));
            });
        }).finally(function () {
            self.emit('end', suites);
        });
    };

    SuiteRunner.prototype.executeSuite = function executeSuite(suite) {
        var self = this;
        suite.title = suite.title || 'Suite';
        self.emit('suite', suite);
        var suiteCompletePromise;
        if (suite.before) {
            self.emit('before', suite.before);
            suiteCompletePromise = self.executeTestsSerial(suite.before).then(function () {
                self.emit('before end', suite.before);
            });
        } else {
            suiteCompletePromise = Promise.resolve();
        }

        suiteCompletePromise = suiteCompletePromise.then(function () {
            if (self.suiteOptions.runInParallel) {
                return self.executeTestsParallel(suite.tests, suite.beforeEach, suite.afterEach);
            }
            return self.executeTestsSerial(suite.tests, suite.beforeEach, suite.afterEach);
        });

        if (suite.after) {
            suiteCompletePromise = suiteCompletePromise.then(function () {
                self.emit('after', suite.after);
                return self.executeTestsSerial(suite.after).then(function () {
                    self.emit('after end', suite.after);
                });
            });
        }

        return suiteCompletePromise.then(function () {
            self.emit('suite end', suite);
        });
    };

    SuiteRunner.prototype.executeTestsSerial = function executeTestsSerial(tests, beforeEach, afterEach) {
        var self = this;
        var testsCompletePromise = Promise.resolve();
        tests.forEach(function (test) {
            testsCompletePromise = testsCompletePromise.then(function () {
                return self.executeTest(test, beforeEach, afterEach);
            });
        });
        return testsCompletePromise;
    };

    SuiteRunner.prototype.executeTestsParallel = function executeTestsParallel(tests, beforeEach, afterEach) {
        var self = this;
        return Promise.all(tests.map(function (test) {
            return self.executeTest(test, beforeEach, afterEach);
        }));
    };

    SuiteRunner.prototype.executeTest = function executeTest(test, beforeEach, afterEach) {
        var self = this;
        var testCompletePromise;

        if (beforeEach) {
            self.emit('beforeEach', beforeEach);
            testCompletePromise = self.executeTestsSerial(beforeEach).then(function () {
                self.emit('beforeEach end', beforeEach);
            });
        } else {
            testCompletePromise = Promise.resolve();
        }

        test.title = test.title || (test.target.method + ' ' + test.target.url);

        testCompletePromise = testCompletePromise.then(function () {
            //self.emit('pending', test);
            return self.executeRequest(test).then(function () {
                self.emit('pass', test);
            }, function (err) {
                self.emit('fail', test, err);
                return Promise.reject(err);
            }).finally(function () {
                self.emit('test end', test);
            });
        });

        if (afterEach) {
            self.emit('afterEach', afterEach);
            testCompletePromise = testCompletePromise.then(function () {
                return self.executeTestsSerial(afterEach).then(function () {
                    self.emit('afterEach end', afterEach);
                });
            });
        }

        return testCompletePromise;
    };

    SuiteRunner.prototype.executeRequest = function executeRequest(test) {
        var self = this;
        var options = {
            url: test.target.url,
            method: test.target.method,
            headers: test.target.headers,
            gzip: true,
            resolveWithFullResponse: true,
            body: test.target.body,
            json: typeof test.target.body === 'object',
            simple: false,
            jar: self.suiteOptions.persistCookies
        };
        return request(options)
            .then(function (response) {
                var resultPromise = Promise.resolve();
                if (test.expect) {
                    if (test.expect.statusCode) {
                        resultPromise = resultPromise.then(function () {
                            return validateTestValue(response.statusCode, test.expect.statusCode, 'statusCode');
                        });
                    }

                    if (test.expect.headers) {
                        Object.keys(test.expect.headers).forEach(function (header) {
                            resultPromise = resultPromise.then(function () {
                                var lcaseHeader = header.toLowerCase();
                                assert.ok(response.headers[lcaseHeader], util.format('Expected header "%s" to have value "%s" but it wasn\'t present', header, test.expect.headers[header]));
                                return validateTestValue(response.headers[lcaseHeader], test.expect.headers[header], util.format('header "%s"', header));
                            });
                        });
                    }

                    if (test.expect.body) {
                        resultPromise = resultPromise.then(function () {
                            return validateTestValue(response.body, test.expect.body, 'body');
                        });
                    }
                }

                return resultPromise;
            });
    };

    function validateTestValue(actual, expected, type) {
        return new Promise(function (resolve) {
            if (typeof expected === 'function') {
                return resolve(validateValueWithFunction(actual, expected, type));
            } else if (typeof expected === 'string' || typeof expected === 'number') {
                return resolve(validateValueAsEquivalent(actual, expected, type));
            } else if (typeof expected === 'object') {
                // If we have a Regex provided, use that.
                if (expected.expression) {
                    return resolve(validateValueWithRegExp(actual, expected, type));
                } else {
                    // Otherwise we have a JSON object, let's compare those.
                    return resolve(validateValueAsObject(actual, expected, type));
                }
            }
            resolve();
        });
    }

    function validateValueWithFunction(actual, expected, type) {
        return new Promise(function (resolve) {
            return resolve(expected(actual));
        }).then(function (result) {
                if (typeof result === 'boolean') {
                    if (!result) {
                        return Promise.reject(new Error(util.format('Expected %s "%s" to satisfy function "%s" but it did not', type, JSON.stringify(actual), expected.name || 'anonymous')));
                    }
                }

                return Promise.resolve();
            });
    }

    function validateValueAsObject(actual, expected, type) {
        return new Promise(function (resolve) {
            if (typeof actual === 'string') {
                // If we got a String back, let's make it JSON.
                actual = JSON.parse(actual);
            }

            assert.deepEqual(actual, expected, util.format('Expected %s "%s" to deep equal "%s" but it did not', type, JSON.stringify(actual), JSON.stringify(expected)));
            resolve();
        });
    }

    function validateValueAsEquivalent(actual, expected, type) {
        return new Promise(function (resolve) {
            assert.strictEqual(actual, expected, util.format('Expected %s to have value "%s" but it had value "%s"', type, expected, actual));
            resolve();
        });
    }

    function validateValueWithRegExp(actual, expected, type) {
        return new Promise(function (resolve) {
            var flags = '';
            expected.flags = expected.flags || {};
            if (expected.flags.ignoreCase) {
                flags += 'i';
            }
            if (expected.flags.global) {
                flags += 'g';
            }
            if (expected.flags.multiline) {
                flags += 'm';
            }
            var regex = new RegExp(expected.expression, flags);
            assert.ok(regex.test(actual), util.format('Expected %s to match "%s" with flags "%s" but "%s" did not match', type, regex.source, flags, actual));
            resolve();
        });
    }

    module.exports = SuiteRunner;
}(require('request-promise'), require('util'), require('assert'), require('joi'), require('bluebird'), require('lodash.create'), require('events').EventEmitter));


text:
package io.skysail.server.app.resources

import com.fasterxml.jackson.annotation.{JsonAutoDetect, JsonProperty}
import io.skysail.api.ui.{Link, Linkable}
import io.skysail.domain.resources.ListResource
import io.skysail.domain.{ListResponseEvent, RequestEvent}
import io.skysail.server.app.RootApplication

@JsonAutoDetect(fieldVisibility=JsonAutoDetect.Visibility.ANY)
case class Client(name: String) extends Linkable {
  @JsonProperty("_links")
  override def _links = List(Link("self", s"clients/$name"))
}

class ClientsResource() extends ListResource[RootApplication, Client] {

  override def get(requestEvent: RequestEvent) = {
    val clients = getApplication().appService.clients
    ListResponseEvent(requestEvent, clients.map(c => Client(c.name)))
  }

}

redpajama_set_name: RedPajamaGithub


text:
namespace estimation {

template class Ekf<jet_filter::State>;
template class ObservationModel<jet_filter::State, jet_filter::AccelMeasurement>;
template class ObservationModel<jet_filter::State, jet_filter::FiducialMeasurement>;
template class ObservationModel<jet_filter::State, jet_filter::GyroMeasurement>;

}  // namespace estimation


text:
    $ US Dollar

$ US Dollar

€ Euro

£ Pound


text:
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{config.PAGE_TITLE}}</title>
    {% if config.OFFLINE_MODE %}

      <link href='{{ url_for('static', filename='jquery-datatables-1.10.13/dataTables.semanticui.min.css') }}' rel='stylesheet' type='text/css'>
      <link href="{{ url_for('offline_static', filename='Semantic-UI-2.1.8/semantic.min.css') }}" rel="stylesheet" />
      <link href="{{ url_for('static', filename='css/c3.min.css') }}" rel="stylesheet" />
    {% else %}
      <link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' />
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.13/css/dataTables.semanticui.min.css" integrity="sha512-CHELgpUsYRrAwM9daSo22qlmK8N6sFRl1TYkZx0CqOdwhpa5vv6C9ogRxZ9qyHoF3bPMNLMHXqFiXjNhmu093A==" crossorigin="anonymous" />
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.1.8/semantic.min.css" integrity="sha512-GbyTrK4wNa8DuGiZ0xUtlSBFr1S/2aqAs2tyk0hWdCxK7maobr5O/L0nW8gLuKQkhbWLpy6GUYUf8FSmZAEj6Q==" crossorigin="anonymous" />
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.22/c3.min.css" integrity="sha512-i6an+SVy8Q0HXieEwQFTzbnrE3xgfVly99YatczufZCQB0RI6wD+wb5fX3k3Co2KshtsMra/5OTdjCbpdJb/VQ==" crossorigin="anonymous" />
    {% endif %}
    <link href="{{ url_for('static', filename='css/puppetboard.css') }}" rel="stylesheet" />

    {% if config.OFFLINE_MODE %}

      {% if config.LOCALISE_TIMESTAMP %}

      {% endif %}
    {% else %}

      {% if config.LOCALISE_TIMESTAMP %}

      {% endif %}
    {% endif %}
    {% if config.LOCALISE_TIMESTAMP %}

    {% endif %}

    {% if config.OFFLINE_MODE %}

    {% else %}

    {% endif %}

    {% block script %} {% endblock script %}

    {% block head %} {% endblock head %}

        Puppetboard

      {%- for endpoint, caption in [
      ('index', 'Overview'),
      ('nodes', 'Nodes'),
      ('facts', 'Facts'),
      ('reports', 'Reports'),
      ('metrics', 'Metrics'),
      ('inventory', 'Inventory'),
      ('catalogs', 'Catalogs'),
      ('radiator', 'Radiator'),
      ('query', 'Query'),
      ] %}
      {{ caption }}
      {%- endfor %}

        {{current_env}}

            All environments
          {% for env in envs %}
            {{env}}
          {% endfor %}

{{version()}}

        {% block content %} {% endblock content %}

        Copyright © 2013-{{ now('%Y') }} Puppet Community. Live from PuppetDB.


text:
from setuptools import setup, find_packages

try:
    readme_text = file('README.rst', 'rb').read()
except IOError,e:
    readme_text = ''

setup(name = "gwcconfig",
    version = "0.0.1",
    description = "Geoserver GeoWebCache REST Configuration",
    long_description = readme_text,
    keywords = "GeoServer GeoWebCache REST Configuration",
    license = "MIT",
    url = "http://github.com/ndufrane/gwcconfig",
    author = "Nicolas Dufrane",
    author_email = "nicolas.dufrane@gmail.com",
    install_requires = ['httplib2>=0.7.4',
    ],
    package_dir = {'':'src'},
    packages = find_packages('src'),
    test_suite = "test.catalogtests",
    classifiers = [
                 'Development Status :: 4 - Beta',
                 'Intended Audience :: Developers',
                 'Intended Audience :: Science/Research',
                 'License :: OSI Approved :: MIT License',
                 'Operating System :: OS Independent',
                 'Programming Language :: Python',
                 'Topic :: Scientific/Engineering :: GIS',
                ]
)


text:
Component::Component(const ComponentType & type)
    : m_type(type)
{ }

Component::~Component()
{ }

ComponentType Component::getType()
{
    return m_type;
}


text:
from .fixtures import client, cluster, compiler, index  # noqa: F401

def assert_expression(expr, expected, compiler):  # noqa: F811
    assert expr.to_dict(compiler=compiler) == expected

def assert_same_elements(seq1, seq2):
    it1 = iter(seq1)
    it2 = iter(seq2)
    i = 0
    while True:
        try:
            e1 = next(it1)
        except StopIteration:
            try:
                e2 = next(it2)
            except StopIteration:
                break
            else:
                raise AssertionError(
                    'seq2 has more elements than seq1: {!r}'.format(e2)
                )
        try:
            e2 = next(it2)
        except StopIteration:
            raise AssertionError(
                'seq1 has more elements than seq2: {!r}'.format(e1)
            )
        assert e1 is e2, '{} element is not the same'.format(i)
        i += 1


text:
using UnityEngine;
using System.Collections;

public class UIListSelector : UIBase {

	Animator anim;
	int animatorItemCount = Animator.StringToHash("itemCount");
	private int SelectedItemIndex = 0;
	int itemMax = 3;
	int itemMin = 0;
	//int runStateHash = Animator.StringToHash("Base Layer.Run");

	void Start ()
	{
		anim = GetComponent<Animator>();
		//set first item to be selected
		MenuItemAnimatorSelector(transform.GetChild(0), true);
//		Debug.Log (transform.childCount);
	}

	//not type safe!!
	void MenuItemAnimatorSelector(Transform Child, bool value)
	{
		if (value)
		{
			//Child.GetComponentInChildren<UImenuItem> ().Select ();
		}
		else
		{
			//Child.GetComponentInChildren<UImenuItem>().Unselect();
		}

	}

	//not type safe!!
	void MenuItemAnimatorPressed(Transform Child, bool value)
	{
		if (value) {
			//Child.GetComponentInChildren<UImenuItem> ().Pressed ();

		} else {
			//Child.GetComponentInChildren<UImenuItem>().UnPressed();

		}

	}

	//this is hard coded to the animator!!!
	void moveCursorDown ()
	{
		if (SelectedItemIndex >= itemMax){return;}
		//make previous item false
		MenuItemAnimatorSelector (transform.GetChild (SelectedItemIndex), false);
		SelectedItemIndex++;
		//select next item down
		anim.SetInteger (animatorItemCount, SelectedItemIndex);
		MenuItemAnimatorSelector (transform.GetChild (SelectedItemIndex), true);
	}

	void moveCursorUp ()
	{
		if(SelectedItemIndex <= itemMin){return;}
		//make previous item false
		MenuItemAnimatorSelector(transform.GetChild(SelectedItemIndex), false);
		SelectedItemIndex --;
		//select next item up
		anim.SetInteger (animatorItemCount, SelectedItemIndex);
		MenuItemAnimatorSelector(transform.GetChild(SelectedItemIndex), true);
	}

	void Update ()
	{
		//AnimatorStateInfo stateInfo = anim.GetCurrentAnimatorStateInfo(0);
		//if(Input.GetKeyDown(KeyCode.Space) && stateInfo.nameHash == runStateHash)
		if(Input.GetKeyDown(KeyCode.DownArrow))
		{
			moveCursorDown ();
		}
//
		if(Input.GetKeyDown(KeyCode.UpArrow))
		{
			moveCursorUp();
		}

		if(Input.GetKeyDown(KeyCode.Space))
		{
			//Debug.Log("entered" + SelectedItemIndex);
			MenuItemAnimatorPressed(transform.GetChild(SelectedItemIndex), true);
		}
	}
}


text:
/**
 * @fileoverview Earth Engine Developer's Guide examples
 *   from 'Arrays - Sorting and Reducing' section
 */

// [START earthengine__arrays06__sort_reduce]
// Define a function that scales and masks Landsat 8 surface reflectance images
// and adds an NDVI band.
function prepSrL8(image) {
  // Develop masks for unwanted pixels (fill, cloud, cloud shadow).
  var qaMask = image.select('QA_PIXEL').bitwiseAnd(parseInt('11111', 2)).eq(0);
  var saturationMask = image.select('QA_RADSAT').eq(0);

  // Apply the scaling factors to the appropriate bands.
  var opticalBands = image.select('SR_B.').multiply(0.0000275).add(-0.2);
  var thermalBands = image.select('ST_B.*').multiply(0.00341802).add(149.0);

  // Calculate NDVI.
  var ndvi = opticalBands.normalizedDifference(['SR_B5', 'SR_B4'])
      .rename('NDVI');

  // Replace original bands with scaled bands, add NDVI band, and apply masks.
  return image.addBands(opticalBands, null, true)
      .addBands(thermalBands, null, true)
      .addBands(ndvi)
      .updateMask(qaMask)
      .updateMask(saturationMask);
}

// Define an arbitrary region of interest as a point.
var roi = ee.Geometry.Point(-122.26032, 37.87187);

// Load a Landsat 8 surface reflectance collection.
var collection = ee.ImageCollection('LANDSAT/LC08/C02/T1_L2')
  // Filter to get only imagery at a point of interest.
  .filterBounds(roi)
  // Filter to get only six months of data.
  .filterDate('2021-01-01', '2021-07-01')
  // Prepare images by mapping the prepSrL8 function over the collection.
  .map(prepSrL8)
  // Select the bands of interest to avoid taking up unneeded memory.
  .select('SR_B.|NDVI');

// Convert the collection to an array.
var array = collection.toArray();

// Label of the axes.
var imageAxis = 0;
var bandAxis = 1;

// Get the NDVI slice and the bands of interest.
var bandNames = collection.first().bandNames();
var bands = array.arraySlice(bandAxis, 0, bandNames.length());
var ndvi = array.arraySlice(bandAxis, -1);

// Sort by descending NDVI.
var sorted = bands.arraySort(ndvi.multiply(-1));

// Get the highest 20% NDVI observations per pixel.
var numImages = sorted.arrayLength(imageAxis).multiply(0.2).int();
var highestNdvi = sorted.arraySlice(imageAxis, 0, numImages);

// Get the mean of the highest 20% NDVI observations by reducing
// along the image axis.
var mean = highestNdvi.arrayReduce({
  reducer: ee.Reducer.mean(),
  axes: [imageAxis]
});

// Turn the reduced array image into a multi-band image for display.
var meanImage = mean.arrayProject([bandAxis]).arrayFlatten([bandNames]);
Map.centerObject(roi, 12);
Map.addLayer(meanImage, {bands: ['SR_B6', 'SR_B5', 'SR_B4'], min: 0, max: 0.4});
// [END earthengine__arrays06__sort_reduce]


text:
package org.pdxfinder.services;

/*
 * Created by csaba on 06/03/2018.
 */

import org.pdxfinder.graph.dao.DataProjection;
import org.pdxfinder.graph.repositories.DataProjectionRepository;
import org.pdxfinder.graph.repositories.MarkerAssociationRepository;
import org.pdxfinder.graph.repositories.MarkerRepository;
import org.pdxfinder.graph.repositories.MolecularCharacterizationRepository;
import org.springframework.stereotype.Service;

/**
 *
 * This service is responsible for providing data for the Molecular Characterization Facet
 */
@Service
public class MolCharService {

    private MolecularCharacterizationRepository molecularCharacterizationRepository;
    private MarkerAssociationRepository markerAssociationRepository;
    private MarkerRepository markerRepository;
    private DataProjectionRepository dataProjectionRepository;

    public MolCharService(MolecularCharacterizationRepository molecularCharacterizationRepository, MarkerAssociationRepository markerAssociationRepository,
                          MarkerRepository markerRepository, DataProjectionRepository dataProjectionRepository) {

        this.molecularCharacterizationRepository = molecularCharacterizationRepository;
        this.markerAssociationRepository = markerAssociationRepository;
        this.markerRepository = markerRepository;
        this.dataProjectionRepository = dataProjectionRepository;
    }

    public String getMutatedMarkersAndVariants(){

        DataProjection dp = dataProjectionRepository.findByLabel("MarkerVariant");

        if(dp != null){

            if(dp.getValue() != null){
                return dp.getValue();
            }
        }

        return "";
    }

}


text:
{#-  Copyright 2017 Cargill Incorporated

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-#}
-- Create a Kudu table in Impala
USE {{ conf.staging_database.name }};
CREATE TABLE IF NOT EXISTS {{ table.destination.name }}_kudu
{%- set ordered_columns = order_columns(table.primary_keys,table.columns) -%}
({%- for column in ordered_columns %}
        {{ column.name }} {{ map_datatypes_v2(column, 'kudu') }}
{%- if not loop.last -%},{% endif %}
{%- endfor %},
primary key ({{ table.primary_keys|join(', ') }}))
{%- if table.kudu.hash_by or table.kudu.range %}
  PARTITION BY
{%- endif %}
{%- if table.kudu.hash_by %}
  HASH({{ table.kudu.hash_by|join(', ') }}) PARTITIONS {{ table.kudu.num_partitions }} {%- if table.kudu.range %} ,{%- endif %}
{%- endif %}
{%- if table.kudu.range %}
 RANGE ({{ table.kudu.range|join(', ') }})
 (
   {{ table.kudu.ranges|join(', ') }}
 )
{%- endif %}
COMMENT '{{ table.comment }}'
STORED AS KUDU
TBLPROPERTIES(
{%- if table.metadata %}
  {%- for key, value in table.metadata.items() %}
  '{{ key }}' = '{{ value }}',
  {%- endfor %}
{%- endif %}
{%- for column in table.columns -%}
  '{{ column.name|lower }}' = "{{ column.comment }}"{%- if not loop.last -%},{% endif %}
{%- endfor -%})


text:
package org.conqat.engine.commons.pattern;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.conqat.engine.core.core.ConQATException;
import org.conqat.engine.core.logging.testutils.ProcessorInfoMock;
import org.conqat.lib.commons.filesystem.FileSystemUtils;
import org.conqat.lib.commons.string.StringUtils;
import org.conqat.lib.commons.test.CCSMTestCaseBase;

/**
 * Tests the {@link PatternListDef}.
 *
 * @author $Author: hummelb $
 * @version $Rev: 40864 $
 * @ConQAT.Rating GREEN Hash: 10BECB1DDBCF005F925F9E09558441D0
 */
public class PatternListDefTest extends CCSMTestCaseBase {

	/** Tests a complex setting with macros for parsing VB. */
	public void testVBPattern() throws ConQATException, IOException {
		PatternListDef def = new PatternListDef();
		def.init(new ProcessorInfoMock());

		def.defineMacro("DOT", "[.]");
		def.defineMacro("SIMPLE_OR_FQ_NAME",
				"(%{IDENTIFIER}%{DOT})*%{IDENTIFIER}");
		def.defineMacro("SPACE_OR_TAB", "[ %{TAB}]");
		def.defineMacro("SPACE_OR_TAB_0U", "%{SPACE_OR_TAB}*");
		def.defineMacro("LF_OR_CR", "[%{LINE_FEED}%{CARRIAGE_RETURN}]");
		def.defineMacro("NOT_LF_AND_NOT_CR",
				"[^%{LINE_FEED}%{CARRIAGE_RETURN}]");
		def.defineMacro("BEGIN_GENERATED_REGION",
				"^#Region%{SPACE_OR_TAB_0U}%{NOT_LF_AND_NOT_CR}*(generiert|generated)");
		def.defineMacro("END_REGION", "^#End Region");

		def.addPattern("(?m)^Imports%{SPACE_OR_TAB_0U}%{SIMPLE_OR_FQ_NAME}$");
		def.addPattern("(?m)%{BEGIN_GENERATED_REGION}(.|%{LF_OR_CR})*?%{END_REGION}");

		PatternList patternList = def.process();

		String fileContent = FileSystemUtils.readFile(useTestFile("test.vb"));
		List<String> matches = new ArrayList<String>();
		for (Pattern p : patternList) {
			Matcher matcher = p.matcher(fileContent);
			while (matcher.find()) {
				matches.add(StringUtils.normalizeLineBreaks(matcher.group()));
			}
		}

		List<String> expected = Arrays
				.asList("Imports AAA.BBB.CCC",
						StringUtils
								.normalizeLineBreaks("#Region \" Vom Windows Form Designer generierter Code \"\n\nRegion inhalt\n\n#End Region"));
		assertEquals(expected, matches);
	}

	/** Tests a complex setting with macros for parsing C#/C++ fragments. */
	public void testCSharpCPPPattern() throws ConQATException {
		PatternListDef def = new PatternListDef();
		def.init(new ProcessorInfoMock());

		def.defineMacro("ACCESS_MODIFIER", "(public|protected|private)");
		def.defineMacro("DOT", "[.]");
		def.defineMacro("FQ_SEPARATOR", "(%{DOT}|::)");
		def.defineMacro("SIMPLE_OR_FQ_NAME",
				"(%{IDENTIFIER}%{FQ_SEPARATOR})*%{IDENTIFIER}");
		def.defineMacro("SIMPLE_OR_FQ_NAME_SETTER",
				"(%{IDENTIFIER}%{FQ_SEPARATOR})*[sS]et%{IDENTIFIER}");
		def.defineMacro("WS", "(%{NEWLINE}|%{TAB}| )");
		def.defineMacro("WS0U", "%{WS}*");
		def.defineMacro("WS1U", "%{WS}+");
		def.defineMacro("LPAREN", "[(]");
		def.defineMacro("RPAREN", "[)]");
		def.defineMacro("LCURLY", "[{]");
		def.defineMacro("RCURLY", "[}]");
		def.defineMacro("GREATER", ">");
		def.defineMacro("AMPERSAND", "&");
		def.defineMacro("THIS_WITH_DELIMITER",
				"(this%{WS0U}(%{DOT}|-%{GREATER})%{WS0U})");
		def.defineMacro("JAVA_RETURN_OR_PARAMETER_TYPE",
				"((final%{WS1U})?%{SIMPLE_OR_FQ_NAME})");
		def.defineMacro("CPP_RETURN_OR_PARAMETER_TYPE",
				"((const%{WS1U})?%{SIMPLE_OR_FQ_NAME}(%{WS0U}[*%{AMPERSAND}])?)");
		def.defineMacro("RETURN_OR_PARAMETER_TYPE",
				"(%{JAVA_RETURN_OR_PARAMETER_TYPE}|%{CPP_RETURN_OR_PARAMETER_TYPE})");

		def.addPattern("(%{ACCESS_MODIFIER}%{WS1U})?%{RETURN_OR_PARAMETER_TYPE}%{WS1U}%{SIMPLE_OR_FQ_NAME}%{WS0U}%{LPAREN}%{WS0U}%{RPAREN}%{WS0U}(const%{WS0U})?%{LCURLY}"
				+ "%{WS0U}return%{WS1U}%{THIS_WITH_DELIMITER}?%{IDENTIFIER}%{WS0U};%{WS0U}"
				+ "%{RCURLY}");
		def.addPattern("(%{ACCESS_MODIFIER}%{WS1U})?void%{WS1U}%{SIMPLE_OR_FQ_NAME}%{WS0U}%{LPAREN}%{WS0U}%{RETURN_OR_PARAMETER_TYPE}%{WS1U}%{IDENTIFIER}%{RPAREN}%{WS0U}%{LCURLY}"
				+ "%{WS0U}%{THIS_WITH_DELIMITER}?%{IDENTIFIER}%{WS0U}=%{WS0U}%{IDENTIFIER}%{WS0U};%{WS0U}"
				+ "%{RCURLY}");

		PatternList patternList = def.process();
		for (int patternNumber = 0; patternNumber <= 6; ++patternNumber) {
			testWithNewline(patternList, patternNumber, "\n");
			testWithNewline(patternList, patternNumber, "\r\n");
		}
	}

	/** Performs the test with the given (numbered) input and newline string. */
	private void testWithNewline(PatternList patternList, int patternNumber,
			String newline) {
		String getterSetterClass = generateGetterSetterTestInput(patternNumber,
				newline);
		assertTrue(patternList.findsAnyIn(getterSetterClass));
	}

	/** Generates test input. */
	private final static String generateGetterSetterTestInput(
			final int patternNumber, final String newline) {
		switch (patternNumber) {
		case 0:
			return "public final String  getField(){" + newline
					+ "  return this.field ; " + newline + "}";
		case 1:
			return "protected   java.lang.String  getField( ) {" + newline
					+ "  return field; }";
		case 2:
			return " /* comment */" + "final String  getField() {" + newline
					+ "  return   this." + newline + "field; " + newline + "}";
		case 3:
			return " /* comment */" + newline
					+ "const A::B::String&  ClassName::field() const {"
					+ newline + "  return   this->field;" + newline + "}";
		case 4:
			return " /* comment */" + "A::B::String*" + newline
					+ "ClassName::getField ()const{" + newline
					+ "  return this->field;" + newline + "}";
		case 5:
			return " // comment " + newline
					+ " public void setDate(final java.util.Date  date) {"
					+ newline + "      this.date = date;" + newline + "}";
		case 6:
			return " // comment " + newline
					+ " void ClassName::setDate(const A::B::Date& date) {"
					+ newline + "      this->date= date ;" + newline + "}";
		}

		fail("Unknown pattern number!");
		return null;
	}

	/**
	 * Create pattern list from patterns. Useful for tests that require
	 * PatternLists
	 */
	public static PatternList createPatternList(String... patterns) {
		PatternList patternList = new PatternList();
		for (String pattern : patterns) {
			patternList.add(Pattern.compile(pattern));
		}
		return patternList;
	}
}


text: APP_CONFIG = YAML.load_file("#{Rails.root}/config/application.yml")[Rails.env]


text:
module MapPaint {

	export var drawPatternPencil = (ctx: CanvasRenderingContext2D, point: PaintPoint, previousPoint: PaintPoint, sketch: Sketchy, pattern: CanvasPattern, widthRatio: number = 1.0) => {
			var sdx = previousPoint.x - point.x,
				sdy = previousPoint.y - point.y,
				speed = Math.sqrt(sdx * sdx + sdy * sdy);

			var xa = 0,
				ya = 26,
				xb = 80,
				yb = 60;

			var w = widthRatio * Math.floor(ya + (Math.min(speed, xb) - xa) * ((yb - ya) / (xb - xa)));

			ctx.beginPath();
			ctx.moveTo(previousPoint.x, previousPoint.y);
			ctx.quadraticCurveTo((previousPoint.x + point.x) * 0.5, (previousPoint.y + point.y) * 0.5, point.x, point.y);
			//ctx.closePath();

			ctx.lineCap = 'round';
			ctx.lineJoin = 'round';

			// Remove the eventual previous pattern
			// It improves the smoothing of the shapes
			var tmpGlobalCompositeOperation = ctx.globalCompositeOperation;
			ctx.globalCompositeOperation = 'destination-out';
			ctx.strokeStyle = 'black';
			ctx.lineWidth = w - 1;

			ctx.stroke();

			// Stroke using a pattern
			ctx.strokeStyle = pattern;
			ctx.lineWidth = w;

			ctx.globalCompositeOperation = tmpGlobalCompositeOperation;

			ctx.stroke();
	}

	var stripesPencilPattern: CanvasPattern,
		stripesPencilColor: string,
		stripesPencilGetPattern = (color: string) => {
			if (stripesPencilPattern && stripesPencilColor === color) {
				return stripesPencilPattern;
			}

			stripesPencilColor = color;

			var patternCanvas = document.createElement('canvas'),
				ctx: CanvasRenderingContext2D = patternCanvas.getContext('2d');

			patternCanvas.width = patternCanvas.height = 12;
			ctx.strokeStyle = color;
			ctx.lineWidth = 4;
			ctx.beginPath();

			ctx.moveTo(-6, 6);
			ctx.lineTo(6, -6);

			ctx.moveTo(-6, 18);
			ctx.lineTo(18, -6);

			ctx.moveTo(6, 18);
			ctx.lineTo(18, 6);

			ctx.closePath();
			ctx.stroke();
			return stripesPencilPattern = ctx.createPattern(patternCanvas, 'repeat');
	};

	export var StripesPencil: Pencil = {
		draw: (ctx: CanvasRenderingContext2D, point: PaintPoint, previousPoint: PaintPoint, sketch: Sketchy) => {
			var pattern = stripesPencilGetPattern(sketch.colorFull);
			drawPatternPencil(ctx, point, previousPoint, sketch, pattern);
		}
	}
}


text:
<?php

namespace artworx\omegacp\Commands;

use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Intervention\Image\ImageServiceProviderLaravel5;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Process\Process;
use artworx\omegacp\Traits\Seedable;
use artworx\omegacp\OmegaServiceProvider;

class InstallCommand extends Command
{
    use Seedable;

    protected $seedersPath = __DIR__.'/../../publishable/database/seeds/';

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'omega:install';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Install the Omega Ragnarok Admin Panel package';

    protected function getOptions()
    {
        return [
            ['with-dummy', null, InputOption::VALUE_NONE, 'Install with dummy data', null],
        ];
    }

    /**
     * Get the composer command for the environment.
     *
     * @return string
     */
    protected function findComposer()
    {
        if (file_exists(getcwd().'/composer.phar')) {
            return '"'.PHP_BINARY.'" '.getcwd().'/composer.phar';
        }

        return 'composer';
    }

    /**
     * Execute the console command.
     *
     * @param \Illuminate\Filesystem\Filesystem $filesystem
     *
     * @return void
     */
    public function fire(Filesystem $filesystem)
    {
        $this->info('Publishing the Omega assets, database, and config files');
        $this->call('vendor:publish', ['--provider' => OmegaServiceProvider::class]);
        $this->call('vendor:publish', ['--provider' => ImageServiceProviderLaravel5::class]);

        $this->info('Migrating the database tables into your application');
        $this->call('migrate');

        $this->info('Dumping the autoloaded files and reloading all new files');

        $composer = $this->findComposer();

        $process = new Process($composer.' dump-autoload');
        $process->setWorkingDirectory(base_path())->run();

        $this->info('Adding Omega routes to routes/web.php');
        $filesystem->append(
            base_path('routes/web.php'),
            "\n\nRoute::group(['prefix' => 'admin'], function () {\n    Omega::routes();\n});\n"
        );

        $this->info('Seeding data into the database');
        $this->seed('OmegaDatabaseSeeder');

        if ($this->option('with-dummy')) {
            $this->seed('OmegaDummyDatabaseSeeder');
        }

        $this->info('Adding the storage symlink to your public folder');
        $this->call('storage:link');

        $this->info('Omega Ragnarok Admin Panel has been successfully installed!');
    }
}


text:
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

let userAuth = false;
let userName = '';
let counter = 1;
/**
 * Authenticate user
 */
async function authenticate() {
  try {
    logInOut = document.getElementById('logInOut');
    const response = await fetch('/auth');
    const userDetails = await response.json();

    if (userDetails.email) {
      userAuth = true;
      logInOut.innerHTML = `Logout`;
      setPreference();
    } else {
      if (userDetails.invalidLogin) {
        logInOut.innerHTML = `Logout`;
        alert(`We can only allow @google.com users currently. Please logout
        and make sure you are logged in with your @google.com account before
        trying again.`);
      } else {
        userAuth = false;
        logInOut.innerHTML = `<a href="${userDetails.loginUrl}">Login</a>`;
      }
    }
  } catch (e) {
    console.log('Error: ', e.message);
  }
};

/**
 * Set user UI preferneces
 */
async function setPreference() {
  try {
    const response = await fetch('/auth');
    const userDetails = await response.json();
    const userFont = userDetails.font;
    const userFontSize = userDetails.font_size;
    const userFontColor = userDetails.text_color;
    const userBackgroundColor = userDetails.bg_color;
    userName = userDetails.name;

    document.body.style.fontFamily = userFont;
    document.body.style.fontSize = userFontSize + 'px';
    document.body.style.color = userFontColor;
    document.body.style.backgroundColor = userBackgroundColor;
  } catch (e) {
    console.log('Error: ', e.message);
  }
}

// On load
window.onload = function() {
  authenticate();
};

/* eslint-disable no-unused-vars */
/**
 * Check if user has access to page
 */
function pageAccess() {
  if (userAuth) {
    const page = newUser(userName);
    window.location.href = page;
  } else {
    document.getElementById(
        'accessDenied',
    ).innerHTML = `<p> Cannot access until you login</p>`;
  }
};

/**
 * Check if user is new
 * @param {string} name name of the user
 * @return {string} return href depending on user status
 */
function newUser(name) {
  if (name === null) {
    return 'userSetUp.html';
  } else if (name === undefined) {
    return 'userSetUp.html';
  } else {
    return '/dashboardServlet';
  }
};

/**
 * Gets the list of checkbox items
 */
function getCheckBox() {
  const checkBoxList = document.querySelectorAll('#checkbox');
  const submitButton = document.getElementById('checkBoxSubmit');
  isChecked(checkBoxList, submitButton);
};

/**
 * Checks if any items in the list are checked
 * @param {NodeListOf<Element>} checkBoxList List of checkbox items
 * @param {HTMLElement} submitButton Html for submit button
 * @return {Boolean} returns if any boxes are checked
 */
function isChecked(checkBoxList, submitButton) {
  const checkBoxArray = [...checkBoxList];
  const areTheyChecked = checkBoxArray.some((box) => box.checked);
  if (areTheyChecked) {
    submitButton.style.display = 'block';
  } else {
    submitButton.style.display = 'none';
  }
  return areTheyChecked;
};
/** Checks if the MCQ checkbox is checked */
function getMcqChecked() {
  const mcqCheck = document.getElementById('mcqCheckBox');
  const addFieldsButton = document.getElementById('addFields');
  const removeFieldsButton= document.getElementById('removeFields');
  const fieldsList = document.getElementById('fieldsList');
  const mcqAnswer = document.getElementById('mcqAnswer');
  const mcqLine = document.getElementById('mcq');
  if (mcqCheck.checked) {
    addFieldsButton.style.display = 'inline-block';
    removeFieldsButton.style.display = 'inline-block';
    fieldsList.style.display = 'block';
    mcqLine.style.display = 'block';
    mcqAnswer.style.display = 'block';
  } else {
    addFieldsButton.style.display = 'none';
    removeFieldsButton.style.display = 'none';
    mcqAnswer.style.display = 'none';
    mcqLine.style.display = 'none';
    fieldsList.style.display = 'none';
  }
};
/** Add more input fields for the MCQ answers */
function moreFields() {
  if (counter >= 5) {
    document.getElementById('popup').style.display = 'block';
  } else {
    const dropdown = document.createElement('OPTION');
    dropdown.innerHTML ='<option>' + counter + '</option';
    document.getElementById('mcqAnswer').append(dropdown);
    document.getElementById('mcqAnswer').style.display = 'block';
    document.getElementById('mcq').style.display = 'block';
    const number = document.createElement('SPAN');
    number.innerHTML = counter + '. ';
    const field = document.createElement('input');
    field.type ='text';
    field.name = 'mcqField';
    field.id = 'mcqField'+counter;
    field.onClick = startDictation(field.id);
    field.cols = '50';
    field.rows = '3';
    field.style.display = 'block';
    field.required = true;
    number.append(field);
    document.getElementById('fieldsList').append(number);
    document.getElementById('removeFields').style.display = 'inline-block';
    counter++;
  }
};
/** Remove the last field from the MCQ answers */
function lessFields() {
  if (counter > 1) {
    const listOfFields = document.getElementById('fieldsList').lastChild;
    listOfFields.parentNode.removeChild(listOfFields);
    document.getElementById('popup').style.display = 'none';
    counter--;
  }
};
/**
*  Starts the speech to text ability
*  @param {string} Id id of the element that called startDictation
*
 */
function startDictation(Id) {
  if (window.hasOwnProperty('webkitSpeechRecognition')) {
    const WebkitSpeechRecognition = webkitSpeechRecognition;
    const recognition = new WebkitSpeechRecognition();
    recognition.continuous = false;
    recognition.interimResults = false;
    recognition.lang = 'en-GB';
    recognition.start();
    recognition.onresult = function(e) {
      if (document.getElementById(Id).value == null) {
        document.getElementById(Id).value = e.results[0][0].transcript;
      } else {
        document.getElementById(Id).value +=' ' + e.results[0][0].transcript;
      }
      recognition.stop();
    };
    recognition.onerror = function(e) {
      recognition.stop();
    };
  }
};
/* eslint-enable no-unused-vars */

// Export modules for testing
if (typeof exports !== 'undefined') {
  module.exports = {
    authenticate,
    setPreference,
    pageAccess,
    userAuth,
    userName,
    newUser,
    isChecked,
  };
};
/* eslint-disable no-unused-vars */

/* eslint-disable no-unused-vars */


text:
package com.cloudray.scalapress.plugin.gallery.base

import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.{ModelAttribute, RequestMapping}
import org.springframework.beans.factory.annotation.Autowired
import scala.collection.JavaConverters._

/** @author Stephen Samuel */
@Controller
@Autowired
@RequestMapping(Array("backoffice/plugin/gallery"))
class GalleryListController(galleryDao: GalleryDao) {

  @RequestMapping
  def list = "admin/plugin/gallery/list.vm"

  @RequestMapping(value = Array("create"))
  def create = {
    val g = new Gallery
    g.name = "new gallery"
    galleryDao.save(g)
    "redirect:/backoffice/gallery"
  }

  @ModelAttribute("galleries")
  def galleries = galleryDao.findAll.asJava
}


text:
package org.jmotor.util.persistence.dto;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Component:
 * Description:
 * Date: 12-11-6
 *
 * @author Andy.Ai
 */
public class PropertyMapper {
    private Map<String, String> entries = new HashMap<String, String>(10);
    private List<String> insertOrders = new ArrayList<String>(10);

    public void put(String key, String value) {
        if (!entries.containsKey(key)) {
            insertOrders.add(key);
        }
        entries.put(key, value);
    }

    public void add(String key, String value) {
        insertOrders.add(key);
        if (!entries.containsKey(key)) {
            entries.put(key, value);
        }
    }

    public List<String> keyList() {
        return insertOrders;
    }

    public String[] keyArray() {
        return insertOrders.toArray(new String[insertOrders.size()]);
    }

    public List<String> valueList() {
        List<String> values = new ArrayList<String>(insertOrders.size());
        for (String key : insertOrders) {
            values.add(entries.get(key));
        }
        return values;
    }

    public String[] valueArray() {
        String[] values = new String[insertOrders.size()];
        for (int i = 0; i < values.length; i++) {
            values[i] = entries.get(insertOrders.get(i));
        }
        return values;
    }

    public String get(String key) {
        return entries.get(key);
    }

    public int size() {
        return insertOrders.size();
    }
}


text:
// Copyright 2021-2022, University of Colorado Boulder

/**
 * Base class that defines a settable Property that determines whether the Object is enabled or not. This includes
 * support for phet-io instrumentation and a variety of options to customize the enabled Property as well as how it is
 * created.
 *
 * @author Michael Kauzmann (PhET Interactive Simulations)
 * @author Sam Reid (PhET Interactive Simulations)
 */

import EnabledProperty, { EnabledPropertyOptions } from './EnabledProperty.js';
import merge from '../../phet-core/js/merge.js';
import { optionize3 } from '../../phet-core/js/optionize.js';
import Tandem from '../../tandem/js/Tandem.js';
import axon from './axon.js';
import TProperty from './TProperty.js';
import TReadOnlyProperty from './TReadOnlyProperty.js';

// constants
const DEFAULT_OPTIONS = {
  enabledProperty: null,
  enabled: true,
  enabledPropertyOptions: null,
  phetioEnabledPropertyInstrumented: true,
  tandem: Tandem.OPTIONAL
} as const;

export type EnabledComponentOptions = {

  // if not provided, a Property will be created
  enabledProperty?: TReadOnlyProperty<boolean> | null;

  // initial value of enabledProperty if we create it, ignored if enabledProperty is provided
  enabled?: boolean;

  // options to enabledProperty if we create it, ignored if enabledProperty is provided
  enabledPropertyOptions?: EnabledPropertyOptions | null;

  // Whether or not the default-created enabledProperty should be instrumented for PhET-iO. Ignored if
  // options.enabledProperty is provided.
  phetioEnabledPropertyInstrumented?: boolean;

  // phet-io
  tandem?: Tandem;
};

export default class EnabledComponent {

  public enabledProperty: TProperty<boolean>;

  private disposeEnabledComponent: () => void;

  public constructor( providedOptions?: EnabledComponentOptions ) {

    const options = optionize3<EnabledComponentOptions, EnabledComponentOptions>()( {}, DEFAULT_OPTIONS, providedOptions );

    const ownsEnabledProperty = !options.enabledProperty;

    assert && options.enabledPropertyOptions && assert( !( !options.phetioEnabledPropertyInstrumented && options.enabledPropertyOptions.tandem ),
      'incompatible options. Cannot specify phetioEnabledPropertyInstrumented opt out and a Tandem via enabledPropertyOptions.' );

    // @ts-ignore There is no way without a plethora of parameterized types to convey if this enabledProperty is
    // settable, so accept unsettable, and typecast to settable.
    this.enabledProperty = options.enabledProperty || new EnabledProperty( options.enabled, merge( {
      tandem: options.phetioEnabledPropertyInstrumented ? options.tandem.createTandem( EnabledProperty.TANDEM_NAME ) : Tandem.OPT_OUT
    }, options.enabledPropertyOptions ) );

    this.disposeEnabledComponent = () => {
      ownsEnabledProperty && this.enabledProperty.dispose();
    };
  }

  private setEnabled( enabled: boolean ): void {
    assert && assert( this.enabledProperty.isSettable(), 'cannot set enabledProperty' );
    this.enabledProperty.value = enabled;
  }

  public set enabled( value: boolean ) { this.setEnabled( value ); }

  public get enabled(): boolean { return this.isEnabled(); }

  public isEnabled(): boolean { return this.enabledProperty.value; }

  public dispose(): void {
    this.disposeEnabledComponent();
  }
}

axon.register( 'EnabledComponent', EnabledComponent );


text:
package com.catherine.webservices.components;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.ClientCertRequest;
import android.webkit.ConsoleMessage;
import android.webkit.DownloadListener;
import android.webkit.GeolocationPermissions;
import android.webkit.HttpAuthHandler;
import android.webkit.JsResult;
import android.webkit.PermissionRequest;
import android.webkit.RenderProcessGoneDetail;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

import com.catherine.webservices.Constants;
import com.catherine.webservices.MyApplication;
import com.catherine.webservices.R;
import com.catherine.webservices.interfaces.ActivityResultListener;
import com.catherine.webservices.interfaces.WebViewProgressListener;
import com.catherine.webservices.network.DownloadManager;
import com.catherine.webservices.network.NetworkHelper;
import com.catherine.webservices.toolkits.ApplicationConfig;
import com.catherine.webservices.toolkits.CLog;

import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.Locale;

import static com.catherine.webservices.Constants.FILECHOOSER_RESULTCODE;

/**
 * Created by Catherine on 2017/11/3.
 * Soft-World Inc.
 * catherine919@soft-world.com.tw
 *

 *

 * This WebView is suppose to deal with url starts with "http://", "https://", "file:///", "content://" and "intent://"
 */

public class MyWebView extends WebView {
    private final static String TAG = MyWebView.class.getSimpleName();
    private WebViewProgressListener progressListener;
    private ActivityResultListener activityResultListener;
    //save console logs in disk
    private final boolean keepLog = false;
    private boolean jsTimeout;
    private ApplicationConfig config;
    private Context ctx;
    private NetworkHelper networkHelper;
    private DownloadManager downloadManager;

    public MyWebView(Context context) {
        super(context);
        initSettings(context);
    }

    public MyWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initSettings(context);
    }

    public MyWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initSettings(context);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public MyWebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initSettings(context);
    }

    @SuppressLint("SetJavaScriptEnabled")
    public void initSettings(Context context) {
        ctx = context;
        config = new ApplicationConfig();
        networkHelper = new NetworkHelper();
        activityResultListener = (ActivityResultListener) ctx;
        downloadManager = new DownloadManager();

        WebSettings settings = getSettings();
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        settings.setLoadsImagesAutomatically(true);
        settings.setDefaultTextEncodingName("utf-8");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            settings.setUserAgentString(WebSettings.getDefaultUserAgent(ctx));
        } else {
            settings.setUserAgentString(System.getProperty("http.agent"));
        }
        String ua = settings.getUserAgentString();
        CLog.i(TAG, "my user agent:" + ua);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            settings.setAllowUniversalAccessFromFileURLs(true);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            settings.setMediaPlaybackRequiresUserGesture(true);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // In this mode, the WebView will allow a secure origin to load content from any other origin, even if that origin is insecure.
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        safeBrowsing(false);
        enableCache(false);
        setWebChromeClient(new WebChromeClient() {

            @Override
            public void onReceivedIcon(WebView view, Bitmap icon) {
                CLog.i(TAG, "onReceivedIcon");
                super.onReceivedIcon(view, icon);
            }

            @Override
            public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) {
                CLog.i(TAG, "onReceivedTouchIconUrl:" + url);
                super.onReceivedTouchIconUrl(view, url, precomposed);
            }

            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {
                CLog.i(TAG, "onShowCustomView1");
                super.onShowCustomView(view, callback);
            }

            @Override
            public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) {
                CLog.i(TAG, "onShowCustomView2");
                super.onShowCustomView(view, requestedOrientation, callback);
            }

            @Override
            public void onHideCustomView() {
                CLog.i(TAG, "onHideCustomView");
                super.onHideCustomView();
            }

            @Override
            public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
                CLog.i(TAG, "onCreateWindow");
                return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
            }

            @Override
            public void onRequestFocus(WebView view) {
                CLog.i(TAG, "onRequestFocus");
                super.onRequestFocus(view);
            }

            @Override
            public void onCloseWindow(WebView window) {
                CLog.i(TAG, "onCloseWindow");
                super.onCloseWindow(window);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (progressListener != null)
                    progressListener.onProgressChanged(view, newProgress);
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public boolean onJsAlert(WebView view, final String url, final String message, final JsResult result) {
                CLog.i(TAG, "onJsAlert:" + message);
                DialogManager.showAlertDialog(ctx, message, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.confirm();
                    }
                });

//                return super.onJsAlert(view, url, message, result);
                return true;
            }

            @Override
            public boolean onJsConfirm(WebView view, final String url, final String message, final JsResult result) {
                CLog.i(TAG, "onJsConfirm:" + message);
                DialogManager.showAlertDialog(ctx, message, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.confirm();
                    }
                }, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.cancel();
                    }
                });
                return true;
//                return super.onJsConfirm(view, url, message, result);
            }

            @Override
            public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {
                CLog.i(TAG, "onJsBeforeUnload:" + message);
                return super.onJsBeforeUnload(view, url, message, result);
            }

            @Override
            public void onExceededDatabaseQuota(String url, String databaseIdentifier, long quota, long estimatedDatabaseSize, long totalQuota, WebStorage.QuotaUpdater quotaUpdater) {
                CLog.i(TAG, "onExceededDatabaseQuota:" + databaseIdentifier);
                super.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize, totalQuota, quotaUpdater);
            }

            //扩充缓存的容量
            @Override
            public void onReachedMaxAppCacheSize(long requiredStorage, long quota, WebStorage.QuotaUpdater quotaUpdater) {
                CLog.i(TAG, "onReachedMaxAppCacheSize:" + requiredStorage);
                super.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater);
            }

            /**
             * Note that for applications targeting Android N and later SDKs (API level > M)
             * this method is only called for requests originating from secure origins such as https.
             * On non-secure origins geolocation requests are automatically denied.
             *
             * @param origin   The origin of the web content attempting to use the Geolocation API.
             * @param callback The callback to use to set the permission state for the origin.
             */
            @Override
            public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) {
                CLog.i(TAG, "onGeolocationPermissionsShowPrompt:" + origin);
                //User have to grant ACCESS_FINE_LOCATION permission first.
                final Dialog myDialog = new Dialog(ctx);
                myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                myDialog.setContentView(R.layout.dialog_checkbox);
                //设置dialog背景透明
                myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                myDialog.show();

                final TextView tv_title = myDialog.findViewById(R.id.tv_title);
                tv_title.setText(ctx.getString(R.string.dialog_title_hint));
                final TextView tv_message = myDialog.findViewById(R.id.tv_message);
                tv_message.setText(String.format("%s%s", origin, ctx.getString(R.string.would_like_to_use_your_current_location)));
                final CheckBox cb = myDialog.findViewById(R.id.cb);
                final Button bt_ok = myDialog.findViewById(R.id.bt_ok);
                bt_ok.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        callback.invoke(origin, true, cb.isChecked());
                        myDialog.dismiss();
                    }
                });
                final Button bt_cancel = myDialog.findViewById(R.id.bt_cancel);
                bt_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        callback.invoke(origin, false, cb.isChecked());
                        myDialog.dismiss();
                    }
                });
//                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }

            /**
             * 通知程序有定位权限请求。如果onGeolocationPermissionsShowPrompt权限申请操作被取消,则隐藏相关的UI界面。
             */
            @Override
            public void onGeolocationPermissionsHidePrompt() {
                CLog.i(TAG, "onGeolocationPermissionsHidePrompt");
                super.onGeolocationPermissionsHidePrompt();
            }

            @Override
            public void onPermissionRequest(final PermissionRequest request) {
                CLog.i(TAG, "onPermissionRequest");
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                    final String[] res = request.getResources();
                    StringBuilder context = new StringBuilder();
                    for (String s : res) {
                        context.append(s);
                        context.append(", ");
                    }
                    context.deleteCharAt(context.length() - 1);
                    DialogManager.showAlertDialog(ctx, String.format("%s\n\n%s", ctx.getResources().getString(R.string.This_page_wants_to_use_following_resources), context), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                request.grant(res);
                            }
                        }
                    }, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                request.deny();
                            }
                        }
                    });
                }
//                super.onPermissionRequest(request);
            }

            /**
             * 通知主程序相关权限被取消。任何相关UI都应该隐藏掉。
             */
            @Override
            public void onPermissionRequestCanceled(PermissionRequest request) {
                CLog.i(TAG, "onPermissionRequestCanceled");
                super.onPermissionRequestCanceled(request);
            }

            /**
             * 通知主程序 执行的Js操作超时。客户端决定是否中断JavaScript继续执行。如果客户端返回true,JavaScript中断执行。如果客户端返回false,则执行继续。注意:如果继续执行,重置JavaScript超时计时器。如果Js下一次检查点仍没有结束,则再次提示。
             */
            @Override
            public boolean onJsTimeout() {
                CLog.i(TAG, "onJsTimeout");
                DialogManager.showErrorDialog(ctx, "JavaScript timeout. Do you want to retry?", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        jsTimeout = true;
                    }
                }, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        jsTimeout = false;
                    }
                });
                return jsTimeout;
//                super.onJsTimeout();
            }

            @Override
            public void onConsoleMessage(String message, int lineNumber, String sourceID) {
                CLog.i(TAG, "onConsoleMessage:" + message);
                if (keepLog) {
                    config.writeWebViewLog(String.format(Locale.ENGLISH, "lineNumber(%d), sourceID(%s), message:%s", lineNumber, sourceID, message));
                }
                super.onConsoleMessage(message, lineNumber, sourceID);
            }

            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                CLog.i(TAG, "onConsoleMessage");
                if (keepLog) {
                    config.writeWebViewLog(String.format(Locale.ENGLISH, "lineNumber(%d), sourceID(%s), message:%s", consoleMessage.lineNumber(), consoleMessage.sourceId(), consoleMessage.message()));
                }
                return super.onConsoleMessage(consoleMessage);
            }

            @Override
            public Bitmap getDefaultVideoPoster() {
                CLog.i(TAG, "getDefaultVideoPoster");
                return super.getDefaultVideoPoster();
            }

            @Override
            public View getVideoLoadingProgressView() {
                CLog.i(TAG, "getVideoLoadingProgressView");
                return super.getVideoLoadingProgressView();
            }

            @Override
            public void getVisitedHistory(ValueCallback<String[]> callback) {
                CLog.i(TAG, "getVisitedHistory");
                super.getVisitedHistory(callback);
            }

            //Android 4.1+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                CLog.i(TAG, "onShowFileChooser:" + acceptType + ", capture:" + capture);
                activityResultListener.addValueCallback(uploadMsg);
                Intent i;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
                    i = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                else
                    i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                String type = TextUtils.isEmpty(acceptType) ? "*/*" : acceptType;
                i.setType(type);
                ((Activity) ctx).startActivityForResult(Intent.createChooser(i, "File Chooser"), Constants.FILECHOOSER_RESULTCODE);
            }

            //Android 5.0+
            @Override
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                CLog.i(TAG, "onShowFileChooser:" + fileChooserParams.getAcceptTypes()[0] + ", capture:" + fileChooserParams.isCaptureEnabled());
                activityResultListener.addValueCallbackL(filePathCallback);
                Intent i = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);

                String type = "*/*";
                if (fileChooserParams != null && fileChooserParams.getAcceptTypes() != null
                        && fileChooserParams.getAcceptTypes().length > 0) {
                    type = fileChooserParams.getAcceptTypes()[0];
                }
                i.setType(type);
                ((Activity) ctx).startActivityForResult(Intent.createChooser(i, "File Chooser"), Constants.FILECHOOSER_RESULTCODE);
                return true;
//                return super.onShowFileChooser(webView, filePathCallback, fileChooserParams);
            }
        });
        setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
                CLog.e(TAG, "onReceivedSslError");
                String message = "SSL Certificate error.";
                switch (error.getPrimaryError()) {
                    case SslError.SSL_UNTRUSTED:
                        message = "The certificate authority is not trusted.";
                        break;
                    case SslError.SSL_EXPIRED:
                        message = "The certificate has expired.";
                        break;
                    case SslError.SSL_IDMISMATCH:
                        message = "The certificate Hostname mismatch.";
                        break;
                    case SslError.SSL_NOTYETVALID:
                        message = "The certificate is not yet valid.";
                        break;
                }
                message += " Do you want to continue anyway?";
                DialogManager.showErrorDialog(ctx, "SSL Error:\n" + message, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        handler.proceed();
                    }
                }, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        handler.cancel();
                        if (canGoBack()) {
                            goBack();
                        }
                    }
                });
//                        super.onReceivedSslError(view, handler, error);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                CLog.i(TAG, "shouldOverrideUrlLoading:" + url);
                loadUrl(url);
                return true;
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                CLog.i(TAG, "shouldOverrideUrlLoading2");
                return super.shouldOverrideUrlLoading(view, request);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
//                CLog.i(TAG, "onPageStarted:" + url);
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
//              CLog.i(TAG, "onPageFinished:" + url);
                super.onPageFinished(view, url);
            }

            //在加载页面资源时会调用,每一个资源(比如图片)的加载都会调用一次。
            @Override
            public void onLoadResource(WebView view, String url) {
                CLog.i(TAG, "onLoadResource:" + url);
                super.onLoadResource(view, url);
            }

            @Override
            public void onPageCommitVisible(WebView view, String url) {
                CLog.i(TAG, "onPageCommitVisible:" + url);
                super.onPageCommitVisible(view, url);
            }

            //拦截替换网络请求数据,  API 11开始引入,API 21弃用
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                CLog.i(TAG, "shouldInterceptRequest:" + url);
                return super.shouldInterceptRequest(view, url);
            }

            //拦截替换网络请求数据,  从API 21开始引入
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                CLog.i(TAG, "shouldInterceptRequest2");
                return super.shouldInterceptRequest(view, request);
            }

            @Override
            public void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg) {
                CLog.w(TAG, "onTooManyRedirects:" + continueMsg);
                super.onTooManyRedirects(view, cancelMsg, continueMsg);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                CLog.e(TAG, "onReceivedError:" + description);
                String message = String.format(Locale.ENGLISH, "%s\nError code:%d\n%s", failingUrl, errorCode, description);
                DialogManager.showErrorDialog(ctx, message, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (canGoBack())
                            goBack();
                    }
                });
//                super.onReceivedError(view, errorCode, description, failingUrl);
            }

            @Override
            @TargetApi(Build.VERSION_CODES.M)
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                CLog.e(TAG, "onReceivedError2");
                String message = String.format(Locale.ENGLISH, "%s\nError code:%d\n%s", request.getUrl(), error.getErrorCode(), error.getDescription());
                DialogManager.showErrorDialog(ctx, message, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (canGoBack())
                            goBack();
                    }
                });
//                super.onReceivedError(view, request, error);
            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                CLog.e(TAG, "onReceivedHttpError");
                super.onReceivedHttpError(view, request, errorResponse);
            }

            /**
             * 是否重发POST请求数据,默认不重发。
             */
            @Override
            public void onFormResubmission(WebView view, Message dontResend, Message resend) {
                CLog.i(TAG, "onFormResubmission:" + dontResend);
                super.onFormResubmission(view, dontResend, resend);
            }

            @Override
            public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
                CLog.i(TAG, "doUpdateVisitedHistory:" + url);
                super.doUpdateVisitedHistory(view, url, isReload);
            }

            @Override
            public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) {
                CLog.w(TAG, "onReceivedClientCertRequest");
                super.onReceivedClientCertRequest(view, request);
            }

            /**
             * 通知主程序:WebView接收HTTP认证请求,主程序可以使用HttpAuthHandler为请求设置WebView响应。默认取消请求。
             */
            @Override
            public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
                CLog.w(TAG, "onReceivedHttpAuthRequest");
                super.onReceivedHttpAuthRequest(view, handler, host, realm);
            }

            @Override
            public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
                CLog.i(TAG, "shouldOverrideKeyEvent");
                return super.shouldOverrideKeyEvent(view, event);
            }

            @Override
            public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
                CLog.w(TAG, "onUnhandledKeyEvent");
                super.onUnhandledKeyEvent(view, event);
            }

//                    @Override
//                    public void onScaleChanged(WebView view, float oldScale, float newScale) {
//                        CLog.i(TAG, "onScaleChanged");
//                        super.onScaleChanged(view, oldScale, newScale);
//                    }

            /**
             * 通知主程序执行了自动登录请求。
             */
            @Override
            public void onReceivedLoginRequest(WebView view, String realm, String account, String args) {
                CLog.w(TAG, "onReceivedLoginRequest");
                super.onReceivedLoginRequest(view, realm, account, args);
            }

            @Override
            public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
                CLog.i(TAG, "onRenderProcessGone");
                return super.onRenderProcessGone(view, detail);
            }

        });
        //Download resources from websites
        setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                CLog.d(TAG, "Start to download:" + url);
                CLog.d(TAG, String.format(Locale.ENGLISH, "userAgent:%s, contentDisposition:%s, mimetype:%s, length:%d%n", userAgent, contentDisposition, mimetype, contentLength));
                downloadManager.download(url);
            }
        });
    }

    /**
     * Allow JavaScript, access files, contents, location and so forth.
     *
     * @param safeBrowsing boolean
     */
    @SuppressLint("SetJavaScriptEnabled")
    private void safeBrowsing(boolean safeBrowsing) {
        WebSettings settings = getSettings();
        if (safeBrowsing) {
            settings.setJavaScriptEnabled(false);
            settings.setJavaScriptCanOpenWindowsAutomatically(false);
            settings.setAllowContentAccess(false);
            settings.setAllowFileAccess(false);
            settings.setGeolocationEnabled(false);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                settings.setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                settings.setSafeBrowsingEnabled(false);
            }
        } else {
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setAllowContentAccess(true);
            settings.setAllowFileAccess(true);
            settings.setGeolocationEnabled(true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                settings.setSafeBrowsingEnabled(true);
            }
        }
    }

    /**
     * Include DomStorage, DB, AppCache
     *
     * @param enableCache boolean
     */

    public void enableCache(boolean enableCache) {
        WebSettings settings = getSettings();
        if (enableCache) {
            settings.setSaveFormData(true);
            settings.setDomStorageEnabled(true);
            settings.setDatabaseEnabled(true);
            settings.setAppCacheEnabled(true);
            settings.setDatabasePath(MyApplication.INSTANCE.getDiskCacheDir("webview").getAbsolutePath());
            settings.setGeolocationDatabasePath(MyApplication.INSTANCE.getDiskCacheDir("webview").getAbsolutePath());
            settings.setAppCachePath(MyApplication.INSTANCE.getDiskCacheDir("webview").getAbsolutePath());
            if (networkHelper.isNetworkHealthy()) {
                settings.setCacheMode(WebSettings.LOAD_DEFAULT);
            } else {
                settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
            }
            settings.setAppCacheMaxSize(5 * 1024 * 1024);//5M
        } else {
            settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        }
    }

    /**
     * Loading progress from 0 to 100
     *
     * @param progressListener it'll call back while updating the progress
     */
    public void addWebViewProgressListener(WebViewProgressListener progressListener) {
        this.progressListener = progressListener;
    }

    /**
     * 不是用来加载整个页面文件的,而是用来加载一段代码片,不能加载图片。
     *
     * @param data 代码片段内容
     */
    public void loadData(String data) throws UnsupportedEncodingException {
        //解决字符冲突,注意做内容encode和后面的编码方式要一样。
        loadData(URLEncoder.encode(data, "utf-8"), "text/html", "utf-8");
    }

    /**
     * @param data     代码片段内容,不能包括'#', '%', '\' , '?'
     * @param mimeType 代码片段所对应的MIME类型,如果传null,则默认为text/html
     * @param encoding 代码片段的编码方式
     */
    @Override
    public void loadData(String data, String mimeType, String encoding) {
        super.loadData(data, mimeType, encoding);
    }

    /**
     * 所有{@link #loadData(String, String, String)}做的到的事都做得到,而且不会有字符冲突,可开启图片。
     *
     * @param data 代码片段内容。
     */
    public void loadDataWithBaseURL(String data) {
        loadDataWithBaseURL(null, data);
    }

    /**
     * 所有{@link #loadData(String, String, String)}做的到的事都做得到,而且不会有字符冲突,可开启图片。
     *
     * @param baseUrl 如果data中的url是相对地址,则就会加上基准url来拼接出完整的地址。
     * @param data    代码片段内容。
     */
    public void loadDataWithBaseURL(String baseUrl, String data) {
        loadDataWithBaseURL(baseUrl, data, "text/html", "utf-8", null);
    }

    /**
     * 所有{@link #loadData(String, String, String)}做的到的事都做得到,而且不会有字符冲突,可开启图片。
     *
     * @param baseUrl    如果data中的url是相对地址,则就会加上基准url来拼接出完整的地址。
     * @param data       代码片段内容。
     * @param mimeType   代码片段所对应的MIME类型,如果传null,则默认为text/html
     * @param encoding   代码片段的编码方式
     * @param historyUrl 当前的历史记录所要存储的值。
     */
    @Override
    public void loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl) {
        super.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl);
    }

    @Override
    public void loadUrl(String urlString) {
        String url = NetworkHelper.formattedUrl(urlString);
        CLog.i(TAG, "Load " + url);
        if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("file:///") || url.startsWith("content://") || url.startsWith("javascript:")) {
            super.loadUrl(url);
        } else if (url.startsWith("intent://")) {
            try {
                Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                if (intent != null) {
                    stopLoading();
                    PackageManager packageManager = ctx.getPackageManager();
                    ResolveInfo info = packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
                    if (info != null) {
                        ctx.startActivity(intent);
                    } else {
                        String fallbackUrl = intent.getStringExtra("browser_fallback_url");
                        super.loadUrl(fallbackUrl);

                        // or call external browser
//                    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(fallbackUrl));
//                    context.startActivity(browserIntent);
                    }
                }
            } catch (URISyntaxException e) {
                e.printStackTrace();
                DialogManager.showErrorDialog(ctx, "Can't resolve intent://", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
            }
        } else {
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                ctx.startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
//                DialogManager.showErrorDialog(getActivity(), "Failed to load URL, try other URL", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                    }
//                });

                //try to google
                super.loadUrl("https://www.google.com/search?q=" + urlString);
            }
        }
    }

}


text:
package monix.eval

import cats.Eval
import monix.execution.atomic.Atomic
import monix.execution.exceptions.DummyException

import scala.util.Failure

object CoevalCatsConversions extends BaseTestSuite {
  test("Coeval.now(value).toEval") { _ =>
    assertEquals(Coeval.now(10).toEval.value, 10)
  }

  test("Coeval.raiseError(e).toEval") { _ =>
    val dummy = DummyException("dummy")
    val eval = Coeval.raiseError(dummy).toEval
    intercept[DummyException] { eval.value }
  }

  test("Coeval.eval(thunk).toEval") { _ =>
    val effect = Atomic(0)
    val eval = Coeval.eval(effect.incrementAndGet()).toEval

    assertEquals(eval.value, 1)
    assertEquals(eval.value, 2)
  }

  test("Coeval.evalOnce(thunk).toEval") { _ =>
    val effect = Atomic(0)
    val eval = Coeval.evalOnce(effect.incrementAndGet()).toEval

    assertEquals(eval.value, 1)
    assertEquals(eval.value, 1)
  }

  test("Coeval.now(value).toIO") { _ =>
    assertEquals(Coeval.now(10).toIO.unsafeRunSync(), 10)
  }

  test("Coeval.raiseError(e).toIO") { _ =>
    val dummy = DummyException("dummy")
    val ioRef = Coeval.raiseError(dummy).toIO
    intercept[DummyException] { ioRef.unsafeRunSync() }
  }

  test("Coeval.eval(thunk).toIO") { _ =>
    val effect = Atomic(0)
    val ioRef = Coeval.eval(effect.incrementAndGet()).toIO

    assertEquals(ioRef.unsafeRunSync(), 1)
    assertEquals(ioRef.unsafeRunSync(), 2)
  }

  test("Coeval.evalOnce(thunk).toIO") { _ =>
    val effect = Atomic(0)
    val eval = Coeval.evalOnce(effect.incrementAndGet()).toIO

    assertEquals(eval.unsafeRunSync(), 1)
    assertEquals(eval.unsafeRunSync(), 1)
  }

  test("Coeval.fromEval(Eval.now(v))") { _ =>
    assertEquals(Coeval.fromEval(Eval.now(10)), Coeval.Now(10))
  }

  test("Coeval.fromEval(Eval.always(v))") { _ =>
    val effect = Atomic(0)
    val eval = Coeval.fromEval(Eval.always(effect.incrementAndGet()))

    assertEquals(eval.value(), 1)
    assertEquals(eval.value(), 2)
    assertEquals(eval.value(), 3)
  }

  test("Coeval.fromEval(Eval.later(v))") { _ =>
    val effect = Atomic(0)
    val eval = Coeval.fromEval(Eval.later(effect.incrementAndGet()))

    assertEquals(eval.value(), 1)
    assertEquals(eval.value(), 1)
  }

  test("Coeval.fromEval protects against user error") { implicit s =>
    val dummy = new DummyException("dummy")
    val eval = Coeval.fromEval(Eval.always { throw dummy })
    assertEquals(eval.runTry(), Failure(dummy))
  }
}


text:
package org.apache.felix.dm.itest.api;

import org.apache.felix.dm.Component;
import org.apache.felix.dm.DependencyManager;
import org.apache.felix.dm.itest.util.Ensure;
import org.apache.felix.dm.itest.util.TestBase;

/**
 * @author Felix Project Team
 */
public class CompositionTest extends TestBase {
    public void testComposition() {
        DependencyManager m = getDM();
        // helper class that ensures certain steps get executed in sequence
        Ensure e = new Ensure();
        // create a service provider and consumer
        Component sp = m.createComponent().setImplementation(new ServiceProvider(e)).setInterface(ServiceInterface.class.getName(), null);
        Component sc = m.createComponent().setImplementation(new ServiceConsumer(e))
                                      .setComposition("getComposition")
                                      .add(m.createServiceDependency().setService(ServiceInterface.class).setRequired(true).setCallbacks("add", null));
        m.add(sp);
        m.add(sc);
        // ensure we executed all steps inside the component instance
        e.step(6);
        m.clear();
    }

    static interface ServiceInterface {
        public void invoke();
    }

    static class ServiceProvider implements ServiceInterface {
        private final Ensure m_ensure;
        public ServiceProvider(Ensure e) {
            m_ensure = e;
        }
        public void invoke() {
            m_ensure.step(4);
        }
    }

    static class ServiceConsumer {
        private final Ensure m_ensure;
        private ServiceConsumerComposite m_composite;
        @SuppressWarnings("unused")
        private ServiceInterface m_service;

        public ServiceConsumer(Ensure e) {
            m_ensure = e;
            m_composite = new ServiceConsumerComposite(m_ensure);
        }

        public Object[] getComposition() {
            return new Object[] { this, m_composite };
        }

        void add(ServiceInterface service) {
            m_ensure.step(1);
            m_service = service; // This method seems to not being called anymore
        }

        void start() {
            m_composite.invoke();
            m_ensure.step(5);
        }
    }

    static class ServiceConsumerComposite {
        ServiceInterface m_service;
        private Ensure m_ensure;

        ServiceConsumerComposite(Ensure ensure)
        {
            m_ensure = ensure;
        }

        void add(ServiceInterface service) {

            m_ensure.step(2);
            m_service = service;
        }

        void invoke()
        {
            m_ensure.step(3);
            m_service.invoke();
        }
    }
}