text:
package nl.hsac.fitnesse.sample;

import fitnesse.util.Base64;
import nl.hsac.fitnesse.fixture.slim.SlimFixtureException;
import nl.hsac.fitnesse.fixture.slim.StopTestException;
import nl.hsac.fitnesse.fixture.slim.web.BrowserTest;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.HasDevTools;
import org.openqa.selenium.devtools.v97.emulation.Emulation;
import org.openqa.selenium.devtools.v97.fetch.Fetch;
import org.openqa.selenium.devtools.v97.fetch.model.RequestPattern;
import org.openqa.selenium.devtools.v97.fetch.model.RequestStage;
import org.openqa.selenium.devtools.v97.log.Log;
import org.openqa.selenium.devtools.v97.network.Network;
import org.openqa.selenium.devtools.v97.network.model.Cookie;
import org.openqa.selenium.devtools.v97.network.model.CookiePriority;
import org.openqa.selenium.devtools.v97.network.model.CookieSameSite;
import org.openqa.selenium.devtools.v97.network.model.Headers;
import org.openqa.selenium.devtools.v97.network.model.RequestId;
import org.openqa.selenium.devtools.v97.network.model.RequestWillBeSent;
import org.openqa.selenium.devtools.v97.network.model.ResourceType;
import org.openqa.selenium.devtools.v97.network.model.ResponseReceived;
import org.openqa.selenium.devtools.v97.network.model.TimeSinceEpoch;
import org.openqa.selenium.devtools.v97.page.Page;
import org.openqa.selenium.devtools.v97.performance.Performance;
import org.openqa.selenium.devtools.v97.performance.model.Metric;
import org.openqa.selenium.devtools.v97.runtime.Runtime;
import org.openqa.selenium.devtools.v97.security.Security;

import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import static java.util.Collections.singletonList;
import static java.util.Optional.empty;

/**
 * Examples
 * @param <T>
 */
public class DevToolsBrowserTest<T extends WebElement> extends BrowserTest<T> {
    private DevTools devTools;
    private final List<String> logEntries = new ArrayList<>();
    private final List<RequestWillBeSent> requests = new ArrayList<>();
    private final List<ResponseReceived> responses = new ArrayList<>();
    private final List<RequestPattern> requestPatternsToOverride = new ArrayList<>();

    /**
     * Experimental class leveraging selenium 4's devTools api's. Use with devTools enabled browser
     * Current api: v97
     */

    public DevToolsBrowserTest() {
        super();
        ensureDevToolsEnabledDriver();
        enableConsoleLogCapturing();
    }

    public DevToolsBrowserTest(int secondsBeforeTimeout) {
        super(secondsBeforeTimeout);
        ensureDevToolsEnabledDriver();
        enableConsoleLogCapturing();
    }

    public DevToolsBrowserTest(int secondsBeforeTimeout, boolean confirmAlertIfAvailable) {
        super(secondsBeforeTimeout, confirmAlertIfAvailable);
        ensureDevToolsEnabledDriver();
        enableConsoleLogCapturing();
    }

    private void ensureDevToolsEnabledDriver() {
        if (!(getSeleniumHelper().driver() instanceof HasDevTools)) {
            throw new StopTestException(false, "DevTools enabled Browser Test can only be used with a chromium based browser (Chrome/Edge)");
        }
        devTools = ((HasDevTools) getSeleniumHelper().driver()).getDevTools();
        devTools.createSessionIfThereIsNotOne();
        devTools.send(Network.enable(Optional.of(100000), Optional.of(100000), Optional.of(100000)));
    }

    /**
     * Inject custom request headers in each request the browser sends
     *
     * @param headers A map conaining headers as key:value
     */
    public void injectHttpHeaders(Map<String, Object> headers) {
        devTools.send(Network.setExtraHTTPHeaders(new Headers(headers)));
    }

    /**
     * Clear the browser's cache
     */
    public void clearBrowserCache() {
        devTools.send(Network.clearBrowserCache());
    }

    /**
     * Delete ALL cookies (not limited to current domain)
     */
    public void clearBrowserCookies() {
        devTools.send(Network.clearBrowserCookies());
    }

    /**
     * Get a map containing all cookies for the given URL
     *
     * @param url The url to list cookies for
     * @return a map containing the cookies as name:value pairs
     */
    public Map<String, String> getCookiesForUrl(String url) {
        Map<String, String> result = new HashMap<>();
        List<Cookie> cookies = devTools.send(Network.getCookies(Optional.of(singletonList(url))));
        for (Cookie c : cookies) {
            result.put(c.getName(), c.getValue());
        }
        return result.size() > 0 ? result : null;
    }

    /**
     * Set a cookie for a specific domain
     *
     * @param name   The name of the cookie
     * @param value  The cookie value
     * @param domain The domain the cookie is valid for
     */
    public void setCookieWithValueForDomain(String name, String value, String domain) {
        devTools.send(Network.setCookie(name, value, empty(), Optional.of(domain),
                empty(), empty(), empty(), empty(), empty(), empty(), empty(), empty(), empty()));
    }

    /**
     * Set a cookie with the possibility to set all properties
     *
     * @param cookieData a map containing key/value for name, value, url, domain, path, secure, httpOnly, sameSite, expires, priority
     *                   Only name and value are mandatory, the others are optional.
     */
    public void setCookieFromMap(Map<String, Object> cookieData) {
        devTools.send(Network.setCookie(
                String.valueOf(cookieData.get("name")),
                String.valueOf(cookieData.get("value")),
                Optional.of(String.valueOf(cookieData.get("url"))),
                Optional.of(String.valueOf(cookieData.get("domain"))),
                Optional.of(String.valueOf(cookieData.get("path"))),
                Optional.of(Boolean.valueOf(cookieData.get("secure").toString())),
                Optional.of(Boolean.valueOf(cookieData.get("httpOnly").toString())),
                Optional.of(CookieSameSite.fromString(String.valueOf(cookieData.get("sameSite")))),
                Optional.of(new TimeSinceEpoch(new BigInteger(String.valueOf(cookieData.get("expires"))))),
                Optional.of(CookiePriority.fromString(String.valueOf(cookieData.get("priority")))),
                empty(),
                empty(),
                empty()
        ));
    }

    /**
     * Toggle browser caching
     *
     * @param disable true to disable caching, false to re-enable it
     */
    public void disableBrowserCache(boolean disable) {
        devTools.send(Network.setCacheDisabled(disable));
    }

    /**
     * Mock geo location and accuracy
     *
     * @param lat      Latitude
     * @param lon      Longitude
     * @param accuracy Accuracy
     */
    public void setGeoLocationLatLonAccuracy(String lat, String lon, String accuracy) {
        devTools.send(Emulation.setGeolocationOverride(Optional.of(Double.valueOf(lat)), Optional.of(Double.valueOf(lon)), Optional.of(Integer.valueOf(accuracy))));
    }

    /**
     * Mock geo location with a default accuracy of 1.
     *
     * @param lat Latitude
     * @param lon Longitude
     */
    public void setGeoLocationLatLon(String lat, String lon) {
        setGeoLocationLatLonAccuracy(lat, lon, "1");
    }

    /**
     * Override the user agent string
     *
     * @param userAgent The useragent String to identify with
     */
    public void setUserAgent(String userAgent) {
        devTools.send(Network.setUserAgentOverride(userAgent, empty(), empty(), empty()));
    }

    /**
     * Take a screenshot of the full web page, by mocking the viewport size to the current content's size
     *
     * @param baseName The base name of the screensho file
     * @return A link to the screenshot file
     */
    public String takeFullPageScreenshot(String baseName) {
        Page.GetLayoutMetricsResponse layoutMetrics = devTools.send(Page.getLayoutMetrics());

        devTools.send(Emulation.setDeviceMetricsOverride(
                layoutMetrics.getContentSize().getWidth().intValue(),
                layoutMetrics.getContentSize().getHeight().intValue(), 1, false,
                empty(), empty(), empty(), empty(), empty(), empty(), empty(), empty(), empty()));

        String result = takeScreenshot(baseName);

        devTools.send(Emulation.clearDeviceMetricsOverride());

        return result;
    }

    /**
     * Ignore SSL errors
     *
     * @param ignore true to ignore, false for default behaviour
     */
    public void ignoreCertificateErrors(boolean ignore) {
        devTools.send(Security.setIgnoreCertificateErrors(ignore));
    }

    /**
     * Retrieve the console output
     *
     * @return Log entries, one on each line
     */
    public String consoleLog() {
        return formattedConsoleLog(logEntries);
    }

    private String formattedConsoleLog(List<String> logEntryList) {
        devTools.send(Log.enable());
        String logView = logEntryList.stream().map(entry -> entry + "\r\n").collect(Collectors.joining());
        return logView;
    }

    /**
     * Clear the list of logEntries
     */
    public void clearConsoleLog() {
        logEntries.clear();
    }

    /**
     * Start collecting performance metrics
     */
    public void startPerformanceMetrics() {
        devTools.send(Performance.enable(Optional.of(Performance.EnableTimeDomain.TIMETICKS)));
    }

    /**
     * Stop collecting performance metrics
     */
    public void stopPerformanceMetrics() {
        devTools.send(Performance.disable());
    }

    /**
     * Get the collected performance metrics as a key:value map
     *
     * @return All collected metrics
     */
    public Map<String, Number> performanceMetrics() {
        return devTools.send(Performance.getMetrics()).stream()
                .collect(Collectors.toMap(Metric::getName, Metric::getValue, (a, b) -> b));
    }

    /**
     * Get a specific metric by name
     *
     * @param metric the metric to retrieve
     * @return a number representing the metric's measurement
     */
    public Number performanceMetric(String metric) {
        return devTools.send(Performance.getMetrics()).stream().filter(m ->
                m.getName().equalsIgnoreCase(metric)).findFirst().map(Metric::getValue).orElse(null);
    }

    /**
     * Keep track of requests and responses during the session
     */
    public void startRequestLogging() {
        devTools.addListener(Network.requestWillBeSent(), requests::add);
        devTools.addListener(Network.responseReceived(), responses::add);
    }

    /**
     * Keep track of requets and responses for a specific ResourceType during the session.
     *
     * @param resourceType The resource type to log. Valid options: Document, Stylesheet, Image, Media, Font, Script,
     *                     TextTrack, XHR, Fetch, EventSource, WebSocket, Manifest, SignedExchange, Ping,
     *                     CSPViolationReport, Other
     */
    public void startRequestLoggingFor(String resourceType) {
        devTools.addListener(Network.requestWillBeSent(), requestWillBeSent -> {
            if (requestWillBeSent.getType().orElse(ResourceType.OTHER).equals(ResourceType.fromString(resourceType))) {
                requests.add(requestWillBeSent);
            }
        });
        devTools.addListener(Network.responseReceived(), responseReceived -> {
            if (responseReceived.getType().equals(ResourceType.fromString(resourceType))) {
                responses.add(responseReceived);
            }
        });
    }

    /**
     * Currently only shows browser's own messages (i.e. XSS warnings)
     * Cannot use Runtime.ConsoleApiCalled , as the fromJson of RemoteObject is broken in alpha 6.
     * Await new version that uses the idealized version of the CDP impl.
     */
    private void enableConsoleLogCapturing() {
        //TODO: Add runtime Console API call logging when new version is released
        devTools.send(Log.enable());
        devTools.addListener(Runtime.consoleAPICalled(), call -> {
            String entry = call.getType().toString() + "; " +
                    new Timestamp(System.currentTimeMillis()).getTime() + "; " +
                    call.getArgs().stream().map(Object::toString).collect(Collectors.joining());

            logEntries.add(entry);
        });
        devTools.addListener(Log.entryAdded(), logEntry -> {
            String entry = logEntry.getLevel().name() + "; " +
                    logEntry.getTimestamp().toString() + "; " +
                    logEntry.getText();
            logEntries.add(entry);
        });

    }

    /**
     * Override the response for a given URL pattern.
     * This method can not be used in combination with override authentication
     *
     * @param urlPattern   The url pattern to match. Wildcards ('*' -> zero or more, '?' -> exactly one) are allowed.
     *                     Escape character is backslash.
     * @param type         The resource type. Allowed Values: Document, Stylesheet, Image, Media, Font, Script, TextTrack, XHR,
     *                     Fetch, EventSource, WebSocket, Manifest, SignedExchange, Ping, CSPViolationReport, Other
     * @param responseBody The response to inject
     */
    public void overrideResponseForUrlOfTypeWith(String urlPattern, String type, String responseBody) {
        requestPatternsToOverride.add(new RequestPattern(
                Optional.of(urlPattern),
                Optional.of(ResourceType.fromString(type)),
                Optional.of(RequestStage.RESPONSE)));

        devTools.addListener(Fetch.requestPaused(), requestPaused -> {
            if (requestPaused.getRequest().getUrl().matches(wildcardAsRegex(urlPattern))) {
                devTools.send(Fetch.fulfillRequest(
                        requestPaused.getRequestId(),
                        requestPaused.getResponseStatusCode().orElse(200),
                        requestPaused.getResponseHeaders(),
                        empty(),
                        Optional.of(Base64.encode(responseBody)),
                        empty()));
            } else {
                devTools.send(Fetch.continueRequest(requestPaused.getRequestId(), empty(), empty(), empty(), empty(), empty()));
            }
        });
    }

    /**
     * Enable response- or authentication overrides
     */
    public void enableNetworkOverrides() {
        Optional<List<RequestPattern>> patterns = requestPatternsToOverride.isEmpty() ? empty() : Optional.of(requestPatternsToOverride);
        boolean overrideAuth = false;
        devTools.send(Fetch.enable(patterns, Optional.of(overrideAuth)));
    }

    /**
     * Clear any response- or authentication overrides
     */
    public void clearNetworkOverrides() {
        devTools.clearListeners();
        requestPatternsToOverride.clear();
        devTools.send(Fetch.disable());
    }

    /**
     * Get the response body of a request to a url that matches the pattern
     *
     * @param requestUrlPattern The url pattern to match. Wildcards ('*' -> zero or more, '?' -> exactly one) are allowed.
     *                          Escape character is backslash.
     * @return the response body as a String
     */
    public String responseBodyOfRequestTo(String requestUrlPattern) {
        RequestId id = getRequestIdForUrl(requestUrlPattern);
        Network.GetResponseBodyResponse body = devTools.send(Network.getResponseBody(id));
        return body.getBody();
    }

    /**
     * Get the response status of a request to a url that matches the pattern
     *
     * @param requestUrlPattern The url pattern to match. Wildcards ('*' -> zero or more, '?' -> exactly one) are allowed.
     *                          Escape character is backslash.
     * @return the response status code (i.e. 200 for OK)
     */
    public int responseStatusOfRequestTo(String requestUrlPattern) {
        RequestId id = getRequestIdForUrl(requestUrlPattern);
        return responses.stream().filter(response -> response.getRequestId().toString().equals(id.toString())).findFirst()
                .orElseThrow(() -> new SlimFixtureException("No response found for: " + requestUrlPattern)).getResponse().getStatus();
    }

    /**
     * Get a list of logged urls that were requested
     *
     * @return list of request URL's
     */
    public List<String> requestLog() {
        return requests.stream().map(request -> request.getRequest().getUrl()).collect(Collectors.toList());
    }

    private RequestId getRequestIdForUrl(String requestUrlPattern) {
        for (RequestWillBeSent r : requests) {
            if (r.getRequest().getUrl().matches(wildcardAsRegex(requestUrlPattern))) {
                return r.getRequestId();
            }
        }
        throw new SlimFixtureException(false, "No request found for: " + requestUrlPattern);
    }

    /**
     * Convert a wildcard pattern to a regex pattern so we can match consistently
     *
     * @param wildcardPattern The pattern to convert
     * @return a regex String
     */
    private String wildcardAsRegex(String wildcardPattern) {
        return "\\Q" + wildcardPattern
                .replace("?", "\\E.\\Q")
                .replace("*", "\\E.*\\Q") +
                "\\E";
    }

}


text:
namespace Microsoft.Azure.Management.DataMigration.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Selected tables for the migration
    /// </summary>
    public partial class MigratePostgreSqlAzureDbForPostgreSqlSyncDatabaseTableInput
    {
        /// <summary>
        /// Initializes a new instance of the
        /// MigratePostgreSqlAzureDbForPostgreSqlSyncDatabaseTableInput class.
        /// </summary>
        public MigratePostgreSqlAzureDbForPostgreSqlSyncDatabaseTableInput()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the
        /// MigratePostgreSqlAzureDbForPostgreSqlSyncDatabaseTableInput class.
        /// </summary>
        /// <param name="name">Name of the table to migrate</param>
        public MigratePostgreSqlAzureDbForPostgreSqlSyncDatabaseTableInput(string name = default(string))
        {
            Name = name;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets name of the table to migrate
        /// </summary>
        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }

    }
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * 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 specic language governing permissions and
 * limitations under the License.
 */

package app.metatron.discovery.spec.druid.ingestion;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.PathNotFoundException;

import org.junit.Test;

import java.util.List;
import java.util.Map;

import app.metatron.discovery.TestUtils;
import app.metatron.discovery.common.GlobalObjectMapper;
import app.metatron.discovery.common.datasource.DataType;
import app.metatron.discovery.domain.datasource.DataSource;
import app.metatron.discovery.domain.datasource.Field;
import app.metatron.discovery.domain.datasource.ingestion.HiveIngestionInfo;
import app.metatron.discovery.domain.datasource.ingestion.file.OrcFileFormat;
import app.metatron.discovery.domain.datasource.ingestion.file.ParquetFileFormat;
import app.metatron.discovery.spec.druid.ingestion.index.IndexSpec;
import app.metatron.discovery.util.PolarisUtils;

import static app.metatron.discovery.domain.datasource.DataSource.ConnectionType.ENGINE;
import static app.metatron.discovery.domain.datasource.DataSource.DataSourceType.MASTER;
import static app.metatron.discovery.domain.datasource.DataSource.GranularityType.DAY;
import static app.metatron.discovery.domain.datasource.DataSource.SourceType.HIVE;
import static app.metatron.discovery.domain.datasource.Field.FieldRole.DIMENSION;
import static app.metatron.discovery.domain.datasource.Field.FieldRole.MEASURE;
import static app.metatron.discovery.domain.datasource.Field.FieldRole.TIMESTAMP;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

public class IndexSpecTest {

  @Test
  public void orcTypeSpecTest() {

    String sourceTable = "default.sample_ingestion_partition_parti_orc";

    DataSource dataSource = new DataSource();
    dataSource.setName("Hive Ingestion orc partition " + PolarisUtils.randomString(5));
    dataSource.setDsType(MASTER);
    dataSource.setConnType(ENGINE);
    dataSource.setGranularity(DAY);
    dataSource.setSegGranularity(DAY);
    dataSource.setSrcType(HIVE);

    List<Field> fields = Lists.newArrayList();
    fields.add(new Field("time", DataType.TIMESTAMP, TIMESTAMP, 0L));
    fields.add(new Field("d", DataType.STRING, DIMENSION, 1L));
    fields.add(new Field("sd", DataType.STRING, DIMENSION, 2L));
    fields.add(new Field("m1", DataType.DOUBLE, MEASURE, 3L));
    fields.add(new Field("m2", DataType.DOUBLE, MEASURE, 4L));
    dataSource.setFields(fields);

    Map<String, Object> context = Maps.newHashMap();

    List<String> intervals = Lists.newArrayList("2017-01-01/2017-12-01");

    List<Map<String, Object>> partitions = Lists.newArrayList();
    partitions.add(TestUtils.makeMap("ym", "201704"));

    HiveIngestionInfo hiveIngestionInfo = new HiveIngestionInfo(
        new OrcFileFormat(), //new CsvFileFormat(),
        sourceTable,
        partitions,
        null,
        null,
        intervals,
        context);

    dataSource.setIngestion(GlobalObjectMapper.writeValueAsString(hiveIngestionInfo));

    IngestionSpecBuilder ingestionSpecBuilder = new IngestionSpecBuilder();
    IngestionSpec ingestionSpec = ingestionSpecBuilder.dataSchema(dataSource)
                                                      .hiveIoConfig(hiveIngestionInfo.getSource(), null, null, null)
                                                      .build();

    System.out.println(GlobalObjectMapper.writeValueAsString(ingestionSpec));

    DocumentContext jsonContext = JsonPath.parse(GlobalObjectMapper.writeValueAsString(ingestionSpec));

    assertThat(jsonContext.read("$['ioConfig']['type']"), is("hadoop"));
    assertThat(jsonContext.read("$['dataSchema']['parser']['type']"), is("orc"));

    boolean thrown = false;
    try {
      jsonContext.read("$['ioConfig']['inputSpec']['typeString']");
    } catch (PathNotFoundException e) {
      thrown = true;
    }
    assertTrue(thrown);

  }

  @Test
  public void parquetTypeSpecTest() {
    String sourceTable = "default.sample_ingestion_parquet";

    DataSource dataSource = new DataSource();
    dataSource.setName("Hive Ingestion parquet partition " + PolarisUtils.randomString(5));
    dataSource.setDsType(MASTER);
    dataSource.setConnType(ENGINE);
    dataSource.setGranularity(DAY);
    dataSource.setSegGranularity(DAY);
    dataSource.setSrcType(HIVE);

    List<Field> fields = Lists.newArrayList();
    fields.add(new Field("time", DataType.TIMESTAMP, TIMESTAMP, 0L));
    fields.add(new Field("d", DataType.STRING, DIMENSION, 1L));
    fields.add(new Field("sd", DataType.STRING, DIMENSION, 2L));
    fields.add(new Field("m1", DataType.DOUBLE, MEASURE, 3L));
    fields.add(new Field("m2", DataType.DOUBLE, MEASURE, 4L));
    dataSource.setFields(fields);

    Map<String, Object> context = Maps.newHashMap();

    List<String> intervals = Lists.newArrayList("2017-01-01/2017-12-01");

    List<Map<String, Object>> partitions = Lists.newArrayList();
    partitions.add(TestUtils.makeMap("ym", "201704"));

    HiveIngestionInfo hiveIngestionInfo = new HiveIngestionInfo(
        new ParquetFileFormat(), //new CsvFileFormat(),
        sourceTable,
        partitions,
        null,
        null,
        intervals,
        context);

    dataSource.setIngestion(GlobalObjectMapper.writeValueAsString(hiveIngestionInfo));

    IngestionSpecBuilder ingestionSpecBuilder = new IngestionSpecBuilder();
    IngestionSpec ingestionSpec = ingestionSpecBuilder.dataSchema(dataSource)
                                                      .hiveIoConfig(hiveIngestionInfo.getSource(), null, null, null)
                                                      .build();

    System.out.println(GlobalObjectMapper.writeValueAsString(ingestionSpec));

    DocumentContext jsonContext = JsonPath.parse(GlobalObjectMapper.writeValueAsString(ingestionSpec));

    assertThat(jsonContext.read("$['ioConfig']['type']"), is("hadoop"));
    assertThat(jsonContext.read("$['dataSchema']['parser']['type']"), is("map"));
    assertThat(jsonContext.read("$['dataSchema']['parser']['parseSpec']['timestampSpec']['replaceWrongColumn']"), is(false));

    boolean thrown = false;
    try {
      jsonContext.read("$['ioConfig']['inputSpec']['typeString']");
    } catch (PathNotFoundException e) {
      thrown = true;
    }
    assertTrue(thrown);
  }

  @Test
  public void BatchTuningConfigTest() {
    IngestionSpecBuilder ingestionSpecBuilder = new IngestionSpecBuilder();
    Map<String, Object> tuningProperties = Maps.newHashMap();
    tuningProperties.put("workingPath", "data");
    tuningProperties.put("ignoreInvalidRows", true);

    IndexSpec indexSpec = new IndexSpec();
    indexSpec.setAllowNullForNumbers(true);

    tuningProperties.put("indexSpec", indexSpec);

    IngestionSpec ingestionSpec = ingestionSpecBuilder.batchTuningConfig(tuningProperties).build();

    String s = GlobalObjectMapper.writeValueAsString(ingestionSpec);

    System.out.println(s);

    DocumentContext jsonContext = JsonPath.parse(s);

    assertThat(jsonContext.read("$['tuningConfig']['type']"), is("index"));
    assertThat(jsonContext.read("$['tuningConfig']['workingPath']"), is("data"));
    assertThat(jsonContext.read("$['tuningConfig']['indexSpec']['allowNullForNumbers']"), is(true));

  }

  @Test
  public void HdfsTuningConfigTest() {
    IngestionSpecBuilder ingestionSpecBuilder = new IngestionSpecBuilder();

    Map<String, Object> tuningProperties = Maps.newHashMap();
    tuningProperties.put("ignoreInvalidRows", true);

    IndexSpec indexSpec = new IndexSpec();
    indexSpec.setAllowNullForNumbers(true);

    tuningProperties.put("indexSpec", indexSpec);

    Map<String, Object> jobProperties = Maps.newHashMap();
    jobProperties.put("abc", "def");
    jobProperties.put("mapreduce.map.memory.mb", 1024);

    IngestionSpec ingestionSpec = ingestionSpecBuilder.hdfsTuningConfig(tuningProperties, jobProperties).build();

    String s = GlobalObjectMapper.writeValueAsString(ingestionSpec);

    System.out.println(s);

    DocumentContext jsonContext = JsonPath.parse(s);

    assertThat(jsonContext.read("$['tuningConfig']['type']"), is("hadoop"));
    assertThat(jsonContext.read("$['tuningConfig']['ignoreInvalidRows']"), is(true));
    assertThat(jsonContext.read("$['tuningConfig']['indexSpec']['allowNullForNumbers']"), is(true));
    assertThat(jsonContext.read("$['tuningConfig']['jobProperties']['mapreduce.map.memory.mb']"), is("1024"));

  }

  @Test
  public void HiveTuningConfigTest() {
    IngestionSpecBuilder ingestionSpecBuilder = new IngestionSpecBuilder();

    Map<String, Object> tuningProperties = Maps.newHashMap();
    tuningProperties.put("ignoreInvalidRows", true);

    IndexSpec indexSpec = new IndexSpec();
    indexSpec.setAllowNullForNumbers(true);

    tuningProperties.put("indexSpec", indexSpec);
    tuningProperties.put("mapSplitSize", "512MB");

    Map<String, Object> jobProperties = Maps.newHashMap();
    jobProperties.put("abc", "def");
    jobProperties.put("mapreduce.map.memory.mb", 1024);

    IngestionSpec ingestionSpec = ingestionSpecBuilder.hiveTuningConfig(tuningProperties, jobProperties).build();

    String s = GlobalObjectMapper.writeValueAsString(ingestionSpec);

    System.out.println(s);

    DocumentContext jsonContext = JsonPath.parse(s);

    assertThat(jsonContext.read("$['tuningConfig']['type']"), is("hadoop"));
    assertThat(jsonContext.read("$['tuningConfig']['ignoreInvalidRows']"), is(true));
    assertThat(jsonContext.read("$['tuningConfig']['indexSpec']['allowNullForNumbers']"), is(true));
    assertThat(jsonContext.read("$['tuningConfig']['jobProperties']['mapreduce.map.memory.mb']"), is("1024"));

  }

  @Test
  public void KafkaTuningConfigTest() {
    KafkaRealTimeIndexBuilder ingestionSpecBuilder = new KafkaRealTimeIndexBuilder();

    Map<String, Object> tuningProperties = Maps.newHashMap();
    tuningProperties.put("ignoreInvalidRows", true);

    IndexSpec indexSpec = new IndexSpec();
    indexSpec.setAllowNullForNumbers(true);

    tuningProperties.put("indexSpec", indexSpec);

    Map<String, Object> jobProperties = Maps.newHashMap();
    jobProperties.put("abc", "def");

    KafkaRealTimeIndex realTimeIndex = ingestionSpecBuilder.tuningConfig(tuningProperties).build();

    String s = GlobalObjectMapper.writeValueAsString(realTimeIndex);

    System.out.println(s);

    DocumentContext jsonContext = JsonPath.parse(s);

    assertThat(jsonContext.read("$['tuningConfig']['type']"), is("kafka"));
    assertThat(jsonContext.read("$['tuningConfig']['ignoreInvalidRows']"), is(true));
    assertThat(jsonContext.read("$['tuningConfig']['indexSpec']['allowNullForNumbers']"), is(true));

  }

}


text:
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: k8s.io/apimachinery/pkg/api/resource/generated.proto

/*
Package resource is a generated protocol buffer package.

It is generated from these files:
	k8s.io/apimachinery/pkg/api/resource/generated.proto

It has these top-level messages:
	Quantity
*/
package resource

import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"

import io "io"

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package

// Quantity is a fixed-point representation of a number.
// It provides convenient marshaling/unmarshaling in JSON and YAML,
// in addition to String() and Int64() accessors.
//
// The serialization format is:
//
// <quantity>        ::= <signedNumber><suffix>
//   (Note that <suffix> may be empty, from the "" case in <decimalSI>.)
// <digit>           ::= 0 | 1 | ... | 9
// <digits>          ::= <digit> | <digit><digits>
// <number>          ::= <digits> | <digits>.<digits> | <digits>. | .<digits>
// <sign>            ::= "+" | "-"
// <signedNumber>    ::= <number> | <sign><number>
// <suffix>          ::= <binarySI> | <decimalExponent> | <decimalSI>
// <binarySI>        ::= Ki | Mi | Gi | Ti | Pi | Ei
//   (International System of units; See: http://physics.nist.gov/cuu/Units/binary.html)
// <decimalSI>       ::= m | "" | k | M | G | T | P | E
//   (Note that 1024 = 1Ki but 1000 = 1k; I didn't choose the capitalization.)
// <decimalExponent> ::= "e" <signedNumber> | "E" <signedNumber>
//
// No matter which of the three exponent forms is used, no quantity may represent
// a number greater than 2^63-1 in magnitude, nor may it have more than 3 decimal
// places. Numbers larger or more precise will be capped or rounded up.
// (E.g.: 0.1m will rounded up to 1m.)
// This may be extended in the future if we require larger or smaller quantities.
//
// When a Quantity is parsed from a string, it will remember the type of suffix
// it had, and will use the same type again when it is serialized.
//
// Before serializing, Quantity will be put in "canonical form".
// This means that Exponent/suffix will be adjusted up or down (with a
// corresponding increase or decrease in Mantissa) such that:
//   a. No precision is lost
//   b. No fractional digits will be emitted
//   c. The exponent (or suffix) is as large as possible.
// The sign will be omitted unless the number is negative.
//
// Examples:
//   1.5 will be serialized as "1500m"
//   1.5Gi will be serialized as "1536Mi"
//
// Note that the quantity will NEVER be internally represented by a
// floating point number. That is the whole point of this exercise.
//
// Non-canonical values will still parse as long as they are well formed,
// but will be re-emitted in their canonical form. (So always use canonical
// form, or don't diff.)
//
// This format is intended to make it difficult to use these numbers without
// writing some sort of special handling code in the hopes that that will
// cause implementors to also use a fixed point implementation.
//
// +protobuf=true
// +protobuf.embed=string
// +protobuf.options.marshal=false
// +protobuf.options.(gogoproto.goproto_stringer)=false
// +k8s:deepcopy-gen=true
// +k8s:openapi-gen=true
type Quantity struct {
	String_          *string `protobuf:"bytes,1,opt,name=string" json:"string,omitempty"`
	XXX_unrecognized []byte  `json:"-"`
}

func (m *Quantity) Reset()                    { *m = Quantity{} }
func (m *Quantity) String() string            { return proto.CompactTextString(m) }
func (*Quantity) ProtoMessage()               {}
func (*Quantity) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{0} }

func (m *Quantity) GetString_() string {
	if m != nil && m.String_ != nil {
		return *m.String_
	}
	return ""
}

func init() {
	proto.RegisterType((*Quantity)(nil), "k8s.io.apimachinery.pkg.api.resource.Quantity")
}
func (m *Quantity) Marshal() (dAtA []byte, err error) {
	size := m.Size()
	dAtA = make([]byte, size)
	n, err := m.MarshalTo(dAtA)
	if err != nil {
		return nil, err
	}
	return dAtA[:n], nil
}

func (m *Quantity) MarshalTo(dAtA []byte) (int, error) {
	var i int
	_ = i
	var l int
	_ = l
	if m.String_ != nil {
		dAtA[i] = 0xa
		i++
		i = encodeVarintGenerated(dAtA, i, uint64(len(*m.String_)))
		i += copy(dAtA[i:], *m.String_)
	}
	if m.XXX_unrecognized != nil {
		i += copy(dAtA[i:], m.XXX_unrecognized)
	}
	return i, nil
}

func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int {
	for v >= 1<<7 {
		dAtA[offset] = uint8(v&0x7f | 0x80)
		v >>= 7
		offset++
	}
	dAtA[offset] = uint8(v)
	return offset + 1
}
func (m *Quantity) Size() (n int) {
	var l int
	_ = l
	if m.String_ != nil {
		l = len(*m.String_)
		n += 1 + l + sovGenerated(uint64(l))
	}
	if m.XXX_unrecognized != nil {
		n += len(m.XXX_unrecognized)
	}
	return n
}

func sovGenerated(x uint64) (n int) {
	for {
		n++
		x >>= 7
		if x == 0 {
			break
		}
	}
	return n
}
func sozGenerated(x uint64) (n int) {
	return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *Quantity) Unmarshal(dAtA []byte) error {
	l := len(dAtA)
	iNdEx := 0
	for iNdEx < l {
		preIndex := iNdEx
		var wire uint64
		for shift := uint(0); ; shift += 7 {
			if shift >= 64 {
				return ErrIntOverflowGenerated
			}
			if iNdEx >= l {
				return io.ErrUnexpectedEOF
			}
			b := dAtA[iNdEx]
			iNdEx++
			wire |= (uint64(b) & 0x7F) << shift
			if b < 0x80 {
				break
			}
		}
		fieldNum := int32(wire >> 3)
		wireType := int(wire & 0x7)
		if wireType == 4 {
			return fmt.Errorf("proto: Quantity: wiretype end group for non-group")
		}
		if fieldNum <= 0 {
			return fmt.Errorf("proto: Quantity: illegal tag %d (wire type %d)", fieldNum, wire)
		}
		switch fieldNum {
		case 1:
			if wireType != 2 {
				return fmt.Errorf("proto: wrong wireType = %d for field String_", wireType)
			}
			var stringLen uint64
			for shift := uint(0); ; shift += 7 {
				if shift >= 64 {
					return ErrIntOverflowGenerated
				}
				if iNdEx >= l {
					return io.ErrUnexpectedEOF
				}
				b := dAtA[iNdEx]
				iNdEx++
				stringLen |= (uint64(b) & 0x7F) << shift
				if b < 0x80 {
					break
				}
			}
			intStringLen := int(stringLen)
			if intStringLen < 0 {
				return ErrInvalidLengthGenerated
			}
			postIndex := iNdEx + intStringLen
			if postIndex > l {
				return io.ErrUnexpectedEOF
			}
			s := string(dAtA[iNdEx:postIndex])
			m.String_ = &s
			iNdEx = postIndex
		default:
			iNdEx = preIndex
			skippy, err := skipGenerated(dAtA[iNdEx:])
			if err != nil {
				return err
			}
			if skippy < 0 {
				return ErrInvalidLengthGenerated
			}
			if (iNdEx + skippy) > l {
				return io.ErrUnexpectedEOF
			}
			m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
			iNdEx += skippy
		}
	}

	if iNdEx > l {
		return io.ErrUnexpectedEOF
	}
	return nil
}
func skipGenerated(dAtA []byte) (n int, err error) {
	l := len(dAtA)
	iNdEx := 0
	for iNdEx < l {
		var wire uint64
		for shift := uint(0); ; shift += 7 {
			if shift >= 64 {
				return 0, ErrIntOverflowGenerated
			}
			if iNdEx >= l {
				return 0, io.ErrUnexpectedEOF
			}
			b := dAtA[iNdEx]
			iNdEx++
			wire |= (uint64(b) & 0x7F) << shift
			if b < 0x80 {
				break
			}
		}
		wireType := int(wire & 0x7)
		switch wireType {
		case 0:
			for shift := uint(0); ; shift += 7 {
				if shift >= 64 {
					return 0, ErrIntOverflowGenerated
				}
				if iNdEx >= l {
					return 0, io.ErrUnexpectedEOF
				}
				iNdEx++
				if dAtA[iNdEx-1] < 0x80 {
					break
				}
			}
			return iNdEx, nil
		case 1:
			iNdEx += 8
			return iNdEx, nil
		case 2:
			var length int
			for shift := uint(0); ; shift += 7 {
				if shift >= 64 {
					return 0, ErrIntOverflowGenerated
				}
				if iNdEx >= l {
					return 0, io.ErrUnexpectedEOF
				}
				b := dAtA[iNdEx]
				iNdEx++
				length |= (int(b) & 0x7F) << shift
				if b < 0x80 {
					break
				}
			}
			iNdEx += length
			if length < 0 {
				return 0, ErrInvalidLengthGenerated
			}
			return iNdEx, nil
		case 3:
			for {
				var innerWire uint64
				var start int = iNdEx
				for shift := uint(0); ; shift += 7 {
					if shift >= 64 {
						return 0, ErrIntOverflowGenerated
					}
					if iNdEx >= l {
						return 0, io.ErrUnexpectedEOF
					}
					b := dAtA[iNdEx]
					iNdEx++
					innerWire |= (uint64(b) & 0x7F) << shift
					if b < 0x80 {
						break
					}
				}
				innerWireType := int(innerWire & 0x7)
				if innerWireType == 4 {
					break
				}
				next, err := skipGenerated(dAtA[start:])
				if err != nil {
					return 0, err
				}
				iNdEx = start + next
			}
			return iNdEx, nil
		case 4:
			return iNdEx, nil
		case 5:
			iNdEx += 4
			return iNdEx, nil
		default:
			return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
		}
	}
	panic("unreachable")
}

var (
	ErrInvalidLengthGenerated = fmt.Errorf("proto: negative length found during unmarshaling")
	ErrIntOverflowGenerated   = fmt.Errorf("proto: integer overflow")
)

func init() {
	proto.RegisterFile("k8s.io/apimachinery/pkg/api/resource/generated.proto", fileDescriptorGenerated)
}

var fileDescriptorGenerated = []byte{
	// 146 bytes of a gzipped FileDescriptorProto
	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0xc9, 0xb6, 0x28, 0xd6,
	0xcb, 0xcc, 0xd7, 0x4f, 0x2c, 0xc8, 0xcc, 0x4d, 0x4c, 0xce, 0xc8, 0xcc, 0x4b, 0x2d, 0xaa, 0xd4,
	0x2f, 0xc8, 0x4e, 0x07, 0x09, 0xe8, 0x17, 0xa5, 0x16, 0xe7, 0x97, 0x16, 0x25, 0xa7, 0xea, 0xa7,
	0xa7, 0xe6, 0xa5, 0x16, 0x25, 0x96, 0xa4, 0xa6, 0xe8, 0x15, 0x14, 0xe5, 0x97, 0xe4, 0x0b, 0xa9,
	0x40, 0x74, 0xe9, 0x21, 0xeb, 0xd2, 0x2b, 0xc8, 0x4e, 0x07, 0x09, 0xe8, 0xc1, 0x74, 0x29, 0x29,
	0x71, 0x71, 0x04, 0x96, 0x26, 0xe6, 0x95, 0x64, 0x96, 0x54, 0x0a, 0x89, 0x71, 0xb1, 0x15, 0x97,
	0x14, 0x65, 0xe6, 0xa5, 0x4b, 0x30, 0x2a, 0x30, 0x6a, 0x70, 0x06, 0x41, 0x79, 0x4e, 0x52, 0x27,
	0x1e, 0xc9, 0x31, 0x5e, 0x78, 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x8c, 0xc7, 0x72, 0x0c,
	0x51, 0x1c, 0x30, 0xfd, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x78, 0xb7, 0x88, 0x6c, 0x9c, 0x00,
	0x00, 0x00,
}


text:
#ifndef MITKCOREEXTCONSTANTS_H_
#define MITKCOREEXTCONSTANTS_H_

#include <QString>

#include <org_mitk_core_ext_Export.h>

namespace mitk
{
  /**
  * The CoreExt Constants contains a list of unique ids in the following form:

  * "org.mitk.mybundle.mytype.propername"

  *
  * This ids have the purpose of connecting the plugin.xml of each bundle to the
  * appropriate classes.
  *
  * Additionally it includes names of tags, which are used in XML files

  * regarding any input device.
  *
  * @ingroup org_mitk_core_ext
  */
  struct MITKCOREEXT_EXPORT CoreExtConstants
  {
    static const QString INPUTDEVICE_SERVICE;
    static const QString INPUTDEVICE_PREFERENCES;
    static const QString INPUTDEVICE_EXTENSION_NAME;
    static const QString INPUTDEVICE_XMLATTRIBUTE_CLASS;
    static const QString INPUTDEVICE_XMLATTRIBUTE_DESCRIPTION;
    static const QString INPUTDEVICE_XMLATTRIBUTE_NAME;
    static const QString INPUTDEVICE_XMLATTRIBUTE_ID;
    static const QString WIIMOTE_SURFACEINTERACTION;
    static const QString WIIMOTE_HEADTRACKING;
    static const QString WIIMOTE_XMLATTRIBUTE_NAME;
  };
}

#endif /*MITKCOREEXTCONSTANTS_H_*/


text:
package view.noSequenceEntered;

import com.github.vatbub.common.core.logging.FOKLogger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;

/**
 * An alert box that pops up if the user has entered no letter sequence.
 *
 * @author frede
 */
public class NoSequenceEntered {

    private static final ResourceBundle bundle = ResourceBundle.getBundle("view.noSequenceEntered.AlertDialog");
    private static Stage stage;

    @FXML // ResourceBundle that was given to the FXMLLoader
    private ResourceBundle resources;

    @FXML // URL location of the FXML file that was given to the FXMLLoader
    private URL location;

    @SuppressWarnings("CanBeFinal")
    @FXML // fx:id="detailsLabel"
    private Label detailsLabel; // Value injected by FXMLLoader

    @FXML // fx:id="messageLabel"
    private Label messageLabel; // Value injected by FXMLLoader

    @FXML // fx:id="okButton"
    private Button okButton; // Value injected by FXMLLoader

    @FXML // fx:id="okParent"
    private HBox okParent; // Value injected by FXMLLoader

    public static void show() {
        stage = new Stage();
        Parent root;
        try {
            root = FXMLLoader.load(NoSequenceEntered.class.getResource("AlertDialog.fxml"), bundle);
            Scene scene = new Scene(root);
            // scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());

            stage.setTitle(bundle.getString("windowTitle"));

            stage.setMinWidth(scene.getRoot().minWidth(0) + 70);
            stage.setMinHeight(scene.getRoot().minHeight(0) + 70);

            stage.setScene(scene);
            stage.show();
        } catch (IOException e) {
            FOKLogger.log(NoSequenceEntered.class.getName(), Level.SEVERE, "An error occurred", e);
        }
    }

    public static void hide() {
        stage.hide();
    }

    // Handler for Button[fx:id="okButton"] onAction
    @FXML
    void okButtonOnAction(ActionEvent event) {
        // handle the event here
        hide();
    }

    @FXML
        // This method is called by the FXMLLoader when initialization is complete
    void initialize() {
        assert detailsLabel != null : "fx:id=\"detailsLabel\" was not injected: check your FXML file 'AlertDialog.fxml'.";
        assert messageLabel != null : "fx:id=\"messageLabel\" was not injected: check your FXML file 'AlertDialog.fxml'.";
        assert okButton != null : "fx:id=\"okButton\" was not injected: check your FXML file 'AlertDialog.fxml'.";
        assert okParent != null : "fx:id=\"okParent\" was not injected: check your FXML file 'AlertDialog.fxml'.";

        // Initialize your logic here: all @FXML variables will have been injected

    }

}


text:
package org.openehealth.ipf.platform.camel.ihe.hl7v3.iti55.asyncresponse;

import org.apache.camel.ExchangePattern;
import org.openehealth.ipf.commons.ihe.hl7v3.Hl7v3Utils;
import org.openehealth.ipf.commons.ihe.hl7v3.iti55.Iti55Utils;
import org.openehealth.ipf.commons.ihe.hl7v3.iti55.asyncresponse.Iti55AsyncResponsePortType;
import org.openehealth.ipf.platform.camel.ihe.ws.AbstractAsyncResponseWebService;

/**
 * Service implementation for the ITI-55 XCPD Initiating Gateway actor
 * (receiver of asynchronous responses).
 * @author Dmytro Rud
 */
public class Iti55AsyncResponseService extends AbstractAsyncResponseWebService implements Iti55AsyncResponsePortType {

    @Override
    public void receiveAsyncResponse(String responseString) {
        process(responseString, null, ExchangePattern.InOnly);
    }

    @Override
    protected String[] getAlternativeResponseKeys(Object response) {
        return new String[] { Iti55Utils.responseQueryId(Hl7v3Utils.slurp((String) response)) };
    }
}


text:
// This file is automatically generated.

package adila.db;

/*
 * ZTE V9A
 *
 * DEVICE: v9plus
 * MODEL: ZTE V9A
 */
final class v9plus_zte20v9a {
    public static final String DATA = "ZTE|V9A|";
}


text:
"""Implements the Ensemble Selection algorithm."""

import collections
from typing import Any, Callable, Dict, List, Optional

from absl import logging
import numpy as np
import tensorflow as tf

from nitroml.protos import problem_statement_pb2 as ps_pb2

LoadedSavedModel = Any
LoadedModelPredictFn = Callable[[LoadedSavedModel, tf.Tensor], tf.Tensor]

def _default_predict_fn(loaded_model, x):
  """Default predict function (callable) for running inference."""
  predictions_dict = loaded_model.signatures['serving_default'](x)
  keys = list(predictions_dict.keys())
  if len(keys) == 1:
    return predictions_dict[keys[0]]
  if 'scores' in predictions_dict:
    return predictions_dict['scores']
  raise ValueError(
      'The predictions dict must be either a single entry or contain a scores key.'
  )

class EnsembleSelection(object):
  """Implements the Ensemble Selection algorithm by Caruana et al."""

  def __init__(self,
               problem_statement: ps_pb2.ProblemStatement,
               saved_model_paths: Dict[str, str],
               ensemble_size: int,
               metric: tf.keras.metrics.Metric,
               predict_fn: Optional[LoadedModelPredictFn] = None,
               goal: Optional[str] = 'maximize'):
    # pyformat: disable
    """Construct an Ensemble Selection object.

    Args:
      problem_statement: ProblemStatement proto identifying the task.
      saved_model_paths: A dict mapping model ids (strings) to SavedModel paths.
      ensemble_size: Maximum number of models (with replacement) to select. This
        is the number of rounds (iterations) for which the ensemble selection
        algorithm will run. The number of models in the final ensemble will be
        at most ensemble_size.
      metric: The TF Keras Metric to optimize for during ensemble selection.
      predict_fn: A function (callable) that maps an input (tf.Tensor) to a
        prediction (tf.Tensor). In addition to the input tf.Tensor, the callable
        takes as argument the (loaded) model that generates the prediction.
        Concretely, predict_fn follows the signature:
        * `loaded_model`: The (loaded) model used for the prediction.
        * `x`: The input (tf.Tensor) to the model.
      goal: String 'maximize' or 'minimize' depending on the goal of the metric.

    Raises:
      ValueError: When goal not 'maximize' or 'minimize'.
    """
    # pyformat: enable
    if goal not in ['maximize', 'minimize']:
      raise ValueError('goal must be either \'maximize\' or \'minimize\'')

    self._problem_statement = problem_statement
    self._saved_model_paths = saved_model_paths
    self._ensemble_size = ensemble_size
    self._metric = metric
    self._predict_fn = predict_fn or _default_predict_fn
    self._goal = goal
    self._weights = {}

  @property
  def weights(self) -> Dict[str, float]:
    return self._weights

  def fit(self, x: np.ndarray, y: np.ndarray):
    """Ensemble selection method by Caruana et al.

    Args:
      x: Numpy array of serialized TF Examples used to make predictions.
      y: Numpy array of labels.
    """
    model_id_to_predictions = self._get_predictions_dict(x)
    ensemble_prediction = np.array(0)
    ensemble_count = collections.defaultdict(int)
    best_ensemble_count = collections.defaultdict(int)
    best_score_overall = -np.inf if self._goal == 'maximize' else np.inf
    for i in range(self._ensemble_size):
      best_score = -np.inf if self._goal == 'maximize' else np.inf
      best_model = None
      for model_id, model_prediction in sorted(model_id_to_predictions.items()):
        updated_ensemble_prediction = self._calculate_ensemble_prediction(
            i, ensemble_prediction, model_prediction)
        self._metric.reset_states()
        score = self._metric(
            y, self._apply_activation(updated_ensemble_prediction))
        if self._score_improved(score, best_score):
          best_score = score
          best_model = model_id
      ensemble_prediction = self._calculate_ensemble_prediction(
          i, ensemble_prediction, model_id_to_predictions[best_model])
      ensemble_count[best_model] += 1
      if self._score_improved(best_score, best_score_overall):
        best_score_overall = best_score
        best_ensemble_count = ensemble_count.copy()
      logging.info('round %d, best score: %s', i, best_score)
    self._calculate_weights(best_ensemble_count)

  def predict(self, x: np.ndarray) -> np.ndarray:
    """Given serialized tf.Examples, compute predictions.

    Args:
      x: Numpy array of serialized TF Examples used to make predictions.

    Returns:
      Numpy array of predictions based on weighted combination of base-model
      predictions determined in `fit`.

    Raises:
      ValueError if called before `fit`.
    """
    if not self.weights:
      raise ValueError(
          'Weights cannot be empty. Must call `fit` before `predict`.')

    return self._get_predictions(x)

  def evaluate(self, x: np.ndarray, y: np.ndarray,
               metrics: List[tf.keras.metrics.Metric]) -> List[float]:
    """Given serialized tf.Examples and labels and metrics, compute evaluations.

    Args:
      x: Numpy 1D array of serialized TF Examples used to make predictions.
      y: Numpy array of labels whose shape either matches or can be broadcast to
        the shape of the ensemble predictions.
      metrics: List of TF Keras Metrics

    Returns:
      A list containing each computed metric value as a float  in the same order
      as they appear in the input `metrics` list.

    Raises:
      ValueError if called before `fit`.
    """
    if not self.weights:
      raise ValueError(
          'Weights cannot be empty. Must call `fit` before `evaluate`.')

    ensemble_prediction = self.predict(x)
    return [metric(y, ensemble_prediction) for metric in metrics]

  def save(self, export_path: str) -> str:
    """Saves ensemble to disk as a SavedModel to be used for serving.

    Args:
      export_path (str): The directory where the combined SavedModel will be
        exported.

    Returns:
      A string containing the path to the saved model.
    """
    return self._save_combined_model(export_path)

  def _get_predictions_dict(self, x: np.ndarray) -> Dict[str, np.ndarray]:
    """Returns predictions for every model loaded from saved_model_paths.

    Args:
      x: Numpy array of serialized TF Examples used to make predictions.
    """
    predictions = {}
    for model_id, path in self._saved_model_paths.items():
      reloaded_model = tf.saved_model.load(path)
      predictions[model_id] = self._predict_fn(reloaded_model,
                                               tf.constant(x)).numpy()
    return predictions

  def _score_improved(self, score: float, best_score: float) -> bool:
    """Returns if the score improved from the previous best score.

    Args:
      score: The new score as a float.
      best_score: Previous best score to compare against.
    """
    if self._goal == 'maximize':
      return score > best_score
    return score < best_score

  def _calculate_ensemble_prediction(
      self, round_num: int, prev_prediction: np.ndarray,
      model_prediction: np.ndarray) -> np.ndarray:
    """Returns the new ensemble prediction by computing the streaming mean.

    Args:
      round_num: The round number, or iteration number, of the ensemble.
      prev_prediction: The ensemble prediction prior to adding the new model.
      model_prediction: Prediction values of the added model.
    """
    return (round_num * prev_prediction + model_prediction) / (round_num + 1)

  def _calculate_weights(self, ensemble_count: Dict[str, int]):
    """Updates weights from the results of fit.

    Args:
      ensemble_count: A dict mapping model id strings to its count in the
        ensemble.
    """
    total_count = sum(ensemble_count.values())
    for model_id, count in ensemble_count.items():
      self._weights[model_id] = count / total_count

  def _apply_activation(self, predictions):
    """Returns the Estimator Head for this task."""

    task_type = self._problem_statement.tasks[0].type
    if task_type.HasField('multi_class_classification'):
      return tf.nn.softmax(predictions)
    if task_type.HasField('binary_classification'):
      return tf.nn.softmax(predictions)[:, 1]
    return predictions

  def _get_predictions(self, x: np.ndarray) -> np.ndarray:
    predictions = np.zeros(shape=(len(x), 1))
    for model_id, weight in self.weights.items():
      reloaded_model = tf.saved_model.load(self._saved_model_paths[model_id])
      model_prediction = self._predict_fn(reloaded_model,
                                          tf.convert_to_tensor(x)).numpy()
      predictions = predictions + model_prediction * weight
    return predictions

  def _get_weighted_prediction(self, loaded_models: Dict[str, LoadedSavedModel],
                               examples: tf.Tensor) -> tf.Tensor:
    """Returns the weighted prediction for the provided example.

    Args:
      loaded_models: A dict of model_id to loaded saved models.
      examples: A tensor of Examples used to make predictions.

    Returns:
      The weighted predictions (output) for the provided examples
    """
    weighted_prediction = tf.constant(0.0)
    for model_id, weight in self.weights.items():
      loaded_model = loaded_models[model_id]
      weighted_prediction = weighted_prediction + self._predict_fn(
          loaded_model, examples) * weight
    return self._apply_activation(weighted_prediction)

  def _save_combined_model(self, export_path: str) -> str:
    """Saves a weighted combination of saved models as a standalone SavedModel.

    The weighted combination refers to the final output (prediction) of the
    combined model. For every input, the output of the combined model is the
    weighted (as specified by weights) sum of the outputs of the input saved
    models.

    Args:
      export_path (str): The directory where the combined SavedModel will be
        exported.

    Returns:
      A string containing the path to the combined saved model.
    """

    def _model_fn(features: Dict[str, tf.Tensor], labels: tf.Tensor,
                  mode: tf.estimator.ModeKeys) -> tf.estimator.EstimatorSpec:
      """Model function passed to tf.estimator.Estimator.

      Args:
        features: Examples to be used to make predictions.
        labels: The labels for the given Examples.
        mode: Specifies if this is training, evaluation or prediction.

      Returns:
        A tf.estimator.EstimatorSpec defining the model to be run by an
        Estimator.
      """
      del labels

      loaded_models = {
          model_id: tf.saved_model.load(self._saved_model_paths[model_id])
          for model_id in self.weights.keys()
      }

      # Train with no-op so that the Estimator doesn't throw an exception.
      if mode == tf.estimator.ModeKeys.TRAIN:
        step = tf.compat.v1.train.get_global_step()
        train_op = step.assign_add(1)
        return tf.estimator.EstimatorSpec(
            mode=mode, loss=tf.constant([0]), train_op=train_op)

      if mode == tf.estimator.ModeKeys.PREDICT:
        predictions = self._get_weighted_prediction(loaded_models,
                                                    features['example'])
        return tf.estimator.EstimatorSpec(
            mode=mode, predictions=predictions, train_op=None)

    def _serving_input_fn():
      """Input fn for serving export, starting from serialized example."""
      serialized_example = tf.compat.v1.placeholder(
          dtype=tf.string, shape=(None), name='serialized_example')
      return tf.estimator.export.ServingInputReceiver(
          features={'example': serialized_example},
          receiver_tensors=serialized_example)

    # Train for 1 step so that the Estimator doesn't throw an exception.
    estimator = tf.estimator.Estimator(_model_fn)
    estimator.train(
        input_fn=lambda: (tf.constant('empty'), tf.no_op()), max_steps=1)
    saved_path = estimator.export_saved_model(export_path, _serving_input_fn)
    return saved_path


text:
const chalk = require('chalk');
var exports = module.exports;

const actions = {
    1 : "can i play",
    2 : "can we play",
    3 : "add me",
    4 : "can i join"
}

const responses = {
    1: "Sorry, Brinnie only plays with Subs. Asking repeatedly may result in a timeout or ban codyvsBrinnie",
    2: "Sorry, Brinnie only plays with Subs. Asking repeatedly may result in a timeout or ban codyvsBrinnie",
    3: "Sorry, Brinnie only adds Subs to her friends list. Asking repeatedly may result in a timeout or ban codyvsBrinnie",
    4: "Sorry, Brinnie only plays with Subs. Asking repeatedly may result in a timeout or ban codyvsBrinnie"
}
exports.reply = {
    actions,
    responses
};


text:
import React from 'react';
import Terser from 'terser';
import { COLOR_MODE_KEY, COLORS, INITIAL_COLOR_MODE_CSS_PROP } from './theme';

import AppWrapper from './components/App/AppWrapper';

function setColorsByTheme() {
	const colors = '🌈';
	const colorModeKey = '🔑';
	const colorModeCssProp = '⚡';

	const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)');
	const prefersDarkFromMedia = systemPrefersDark.matches;
	const persistedPreference = localStorage.getItem(colorModeKey);

	let colorMode = 'light';
	const hasUsedToggle = typeof persistedPreference === 'string';

	if (hasUsedToggle) {
		colorMode = persistedPreference;
	} else {
		colorMode = prefersDarkFromMedia ? 'dark' : 'light';
	}

	const root = document.body;
	root.style.setProperty(colorModeCssProp, colorMode);

	Object.entries(colors).forEach(([name, colorByTheme]) => {
		const cssVariableName = `--color-${name}`;

		root.style.setProperty(cssVariableName, colorByTheme[colorMode]);
	});
}

const MagicScriptTag = () => {
	const boundFn = String(setColorsByTheme)
		.replace("'🌈'", JSON.stringify(COLORS))
		.replace('🔑', COLOR_MODE_KEY)
		.replace('⚡', INITIAL_COLOR_MODE_CSS_PROP);

	let calledFunction = `(${boundFn})()`;

	calledFunction = Terser.minify(calledFunction).code;

	// eslint-disable-next-line react/no-danger
	return <script dangerouslySetInnerHTML={{ __html: calledFunction }} />;
};

// This will get run if javascript is disabled in the users browser
const FallbackStyles = () => {
	const cssVariableString = Object.entries(COLORS).reduce((acc, [name, colorByTheme]) => {
		return `${acc}\n--color-${name}: ${colorByTheme.light};`;
	}, '');

	// set the css variables
	const wrappedInSelector = `html { ${cssVariableString} }`;

	return <style>{wrappedInSelector}</style>;
};

export const onRenderBody = ({ setPreBodyComponents, setHeaderComponents }) => {
	setHeaderComponents(<FallbackStyles />);
	setPreBodyComponents(<MagicScriptTag />);
};

// eslint-disable-next-line react/prop-types
export const wrapPageElement = ({ element }) => {
	return <AppWrapper>{element}</AppWrapper>;
};